title: ioctl_fat(2)

summary: manipulating the FAT filesystem

text:
# ioctl_fat(2)

## NAME
ioctl_fat - manipulating the FAT filesystem

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/msdos_fs.h>     /* Definition of [V]FAT_* and
                                   ATTR_* constants*/"
#include <sys/ioctl.h>
```

```
int ioctl(int fd, FAT_IOCTL_GET_ATTRIBUTES, uint32_t *attr);
int ioctl(int fd, FAT_IOCTL_SET_ATTRIBUTES, uint32_t *attr);
int ioctl(int fd, FAT_IOCTL_GET_VOLUME_ID, uint32_t *id);
int ioctl(int fd, VFAT_IOCTL_READDIR_BOTH,
          struct __fat_dirent entry[2]);
int ioctl(int fd, VFAT_IOCTL_READDIR_SHORT,
          struct __fat_dirent entry[2]);
```

## DESCRIPTION
The ioctl(2) system call can be used to read and write metadata of FAT filesystems that are not accessible using other system calls.

### Reading and setting file attributes
Files and directories in the FAT filesystem possess an attribute bit mask that can be read with FAT_IOCTL_GET_ATTRIBUTES and written with FAT_IOCTL_SET_ATTRIBUTES.

The fd argument contains a file descriptor for a file or directory. It is sufficient to create the file descriptor by calling open(2) with the O_RDONLY flag.

The attr argument contains a pointer to a bit mask. The bits of the bit mask are:

ATTR_RO

This bit specifies that the file or directory is read-only.

ATTR_HIDDEN

This bit specifies that the file or directory is hidden.

ATTR_SYS

This bit specifies that the file is a system file.

ATTR_VOLUME

This bit specifies that the file is a volume label. This attribute is read-only.

ATTR_DIR

This bit specifies that this is a directory. This attribute is read-only.

ATTR_ARCH

This bit indicates that this file or directory should be archived. It is set when a file is created or modified. It is reset by an archiving system.

The zero value ATTR_NONE can be used to indicate that no attribute bit is set.

### Reading the volume ID
FAT filesystems are identified by a volume ID. The volume ID can be read with FAT_IOCTL_GET_VOLUME_ID.

The fd argument can be a file descriptor for any file or directory of the filesystem. It is sufficient to create the file descriptor by calling open(2) with the O_RDONLY flag.

The id argument is a pointer to the field that will be filled with the volume ID. Typically the volume ID is displayed to the user as a group of two 16-bit fields:

```
printf("Volume ID %04x-%04x\n", id >> 16, id & 0xFFFF);
```

### Reading short filenames of a directory
A file or directory on a FAT filesystem always has a short filename consisting of up to 8 capital letters, optionally followed by a period and up to 3 capital letters for the file extension. If the actual filename does not fit into this scheme, it is stored as a long filename of up to 255 UTF-16 characters.

The short filenames in a directory can be read with VFAT_IOCTL_READDIR_SHORT. VFAT_IOCTL_READDIR_BOTH reads both the short and the long filenames.

The fd argument must be a file descriptor for a directory. It is sufficient to create the file descriptor by calling open(2) with the O_RDONLY flag. The file descriptor can be used only once to iterate over the directory entries by calling ioctl(2) repeatedly.

The entry argument is a two-element array of the following structures:

```
struct __fat_dirent {

    long            d_ino;

    __kernel_off_t  d_off;

    uint32_t short  d_reclen;

    char            d_name[256];
};
```

The first entry in the array is for the short filename. The second entry is for the long filename.

The d_ino and d_off fields are filled only for long filenames. The d_ino field holds the inode number of the directory. The d_off field holds the offset of the file entry in the directory. As these values are not available for short filenames, the user code should simply ignore them.

The field d_reclen contains the length of the filename in the field d_name. To keep backward compatibility, a length of 0 for the short filename signals that the end of the directory has been reached. However, the preferred method for detecting the end of the directory is to test the ioctl(2) return value. If no long filename exists, field d_reclen is set to 0 and d_name is a character string of length 0 for the long filename.

## RETURN VALUE
On error, -1 is returned, and errno is set to indicate the error.

For VFAT_IOCTL_READDIR_BOTH and VFAT_IOCTL_READDIR_SHORT a return value of 1 signals that a new directory entry has been read and a return value of 0 signals that the end of the directory has been reached.

## ERRORS
ENOENT

This error is returned by VFAT_IOCTL_READDIR_BOTH and VFAT_IOCTL_READDIR_SHORT if the file descriptor fd refers to a removed, but still open directory.

ENOTDIR

This error is returned by VFAT_IOCTL_READDIR_BOTH and VFAT_IOCTL_READDIR_SHORT if the file descriptor fd does not refer to a directory.

ENOTTY

The file descriptor fd does not refer to an object in a FAT filesystem.

For further error values, see ioctl(2).

## STANDARDS
Linux.

## HISTORY
VFAT_IOCTL_READDIR_BOTH

VFAT_IOCTL_READDIR_SHORT

Linux 2.0.

FAT_IOCTL_GET_ATTRIBUTES

FAT_IOCTL_SET_ATTRIBUTES

Linux 2.6.12.

FAT_IOCTL_GET_VOLUME_ID

Linux 3.11.

## EXAMPLES

### Toggling the archive flag
The following program demonstrates the usage of ioctl(2) to manipulate file attributes. The program reads and displays the archive attribute of a file. After inverting the value of the attribute, the program reads and displays the attribute again.

The following was recorded when applying the program for the file /mnt/user/foo:

```
# ./toggle_fat_archive_flag /mnt/user/foo
Archive flag is set
Toggling archive flag
Archive flag is not set
```

### Program source (toggle_fat_archive_flag.c)

```
#include <fcntl.h>
#include <linux/msdos_fs.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
/*

 * Read file attributes of a file on a FAT filesystem.

 * Output the state of the archive flag.

 */
static uint32_t
readattr(int fd)
{

    int       ret;

    uint32_t  attr;

    ret = ioctl(fd, FAT_IOCTL_GET_ATTRIBUTES, &attr);

    if (ret == -1) {

        perror("ioctl");

        exit(EXIT_FAILURE);

    }

    if (attr & ATTR_ARCH)

        printf("Archive flag is set\n");

    else

        printf("Archive flag is not set\n");

    return attr;
}
int
main(int argc, char *argv[])
{

    int       fd;

    int       ret;

    uint32_t  attr;

    if (argc != 2) {

        printf("Usage: %s FILENAME\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    fd = open(argv[1], O_RDONLY);

    if (fd == -1) {

        perror("open");

        exit(EXIT_FAILURE);

    }

    /*

     * Read and display the FAT file attributes.

     */

    attr = readattr(fd);

    /*

     * Invert archive attribute.

     */

    printf("Toggling archive flag\n");

    attr ^= ATTR_ARCH;

    /*

     * Write the changed FAT file attributes.

     */

    ret = ioctl(fd, FAT_IOCTL_SET_ATTRIBUTES, &attr);

    if (ret == -1) {

        perror("ioctl");

        exit(EXIT_FAILURE);

    }

    /*

     * Read and display the FAT file attributes.

     */

    readattr(fd);

    close(fd);

    exit(EXIT_SUCCESS);
}
```

### Reading the volume ID
The following program demonstrates the use of ioctl(2) to display the volume ID of a FAT filesystem.

The following output was recorded when applying the program for directory /mnt/user:

```
$ ./display_fat_volume_id /mnt/user
Volume ID 6443-6241
```

### Program source (display_fat_volume_id.c)

```
#include <fcntl.h>
#include <linux/msdos_fs.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{

    int       fd;

    int       ret;

    uint32_t  id;

    if (argc != 2) {

        printf("Usage: %s FILENAME\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    fd = open(argv[1], O_RDONLY);

    if (fd == -1) {

        perror("open");

        exit(EXIT_FAILURE);

    }

    /*

     * Read volume ID.

     */

    ret = ioctl(fd, FAT_IOCTL_GET_VOLUME_ID, &id);

    if (ret == -1) {

        perror("ioctl");

        exit(EXIT_FAILURE);

    }

    /*

     * Format the output as two groups of 16 bits each.

     */

    printf("Volume ID %04x-%04x\n", id >> 16, id & 0xFFFF);

    close(fd);

    exit(EXIT_SUCCESS);
}
```

### Listing a directory
The following program demonstrates the use of ioctl(2) to list a directory.

The following was recorded when applying the program to the directory /mnt/user:

```
$ ./fat_dir /mnt/user
. -> ''
.. -> ''
ALONGF~1.TXT -> 'a long filename.txt'
UPPER.TXT -> ''
LOWER.TXT -> 'lower.txt'
```

### Program source

```
#include <fcntl.h>
#include <linux/msdos_fs.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{

    int                  fd;

    int                  ret;

    struct __fat_dirent  entry[2];

    if (argc != 2) {

        printf("Usage: %s DIRECTORY\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    /*

     * Open file descriptor for the directory.

     */

    fd = open(argv[1], O_RDONLY | O_DIRECTORY);

    if (fd == -1) {

        perror("open");

        exit(EXIT_FAILURE);

    }

    for (;;) {

        /*

         * Read next directory entry.

         */

        ret = ioctl(fd, VFAT_IOCTL_READDIR_BOTH, entry);

        /*

         * If an error occurs, the return value is -1.

         * If the end of the directory list has been reached,

         * the return value is 0.

         * For backward compatibility the end of the directory

         * list is also signaled by d_reclen == 0.

         */

        if (ret < 1)

            break;

        /*

         * Write both the short name and the long name.

         */

        printf("%s -> '%s'\n", entry[0].d_name, entry[1].d_name);

    }

    if (ret == -1) {

        perror("VFAT_IOCTL_READDIR_BOTH");

        exit(EXIT_FAILURE);

    }

    /*

     * Close the file descriptor.

     */

    close(fd);

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
ioctl(2)


package: man-pages

title: ioctl_ficlonerange(2)

text:
# ioctl_ficlonerange(2)

## NAME
ioctl_ficlonerange, ioctl_ficlone - share some the data of one file with another file

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/fs.h>        /* Definition of FICLONE* constants */
#include <sys/ioctl.h>
```

```
int ioctl(int dest_fd, FICLONERANGE, struct file_clone_range *arg);
int ioctl(int dest_fd, FICLONE, int src_fd);
```

## DESCRIPTION
If a filesystem supports files sharing physical storage between multiple files ("reflink"), this ioctl(2) operation can be used to make some of the data in the src_fd file appear in the dest_fd file by sharing the underlying storage, which is faster than making a separate physical copy of the data. Both files must reside within the same filesystem. If a file write should occur to a shared region, the filesystem must ensure that the changes remain private to the file being written. This behavior is commonly referred to as "copy on write".

This ioctl reflinks up to src_length bytes from file descriptor src_fd at offset src_offset into the file dest_fd at offset dest_offset, provided that both are files. If src_length is zero, the ioctl reflinks to the end of the source file. This information is conveyed in a structure of the following form:

```
struct file_clone_range {

    __s64 src_fd;

    __u64 src_offset;

    __u64 src_length;

    __u64 dest_offset;
};
```

Clones are atomic with regards to concurrent writes, so no locks need to be taken to obtain a consistent cloned copy.

The FICLONE ioctl clones entire files.

## RETURN VALUE
On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
Error codes can be one of, but are not limited to, the following:

EBADF

src_fd is not open for reading; dest_fd is not open for writing or is open for append-only writes; or the filesystem which src_fd resides on does not support reflink.

EINVAL

The filesystem does not support reflinking the ranges of the given files. This error can also appear if either file descriptor represents a device, FIFO, or socket. Disk filesystems generally require the offset and length arguments to be aligned to the fundamental block size. XFS and Btrfs do not support overlapping reflink ranges in the same file.

EISDIR

One of the files is a directory and the filesystem does not support shared regions in directories.

EOPNOTSUPP

This can appear if the filesystem does not support reflinking either file descriptor, or if either file descriptor refers to special inodes.

EPERM

dest_fd is immutable.

ETXTBSY

One of the files is a swap file. Swap files cannot share storage.

EXDEV

dest_fd and src_fd are not on the same mounted filesystem.

## STANDARDS
Linux.

## HISTORY
Linux 4.5.

They were previously known as BTRFS_IOC_CLONE and BTRFS_IOC_CLONE_RANGE, and were private to Btrfs.

## NOTES
Because a copy-on-write operation requires the allocation of new storage, the fallocate(2) operation may unshare shared blocks to guarantee that subsequent writes will not fail because of lack of disk space.

## SEE ALSO
ioctl(2)


title: ioctl_fideduperange(2)

text:
# ioctl_fideduperange(2)

## NAME
ioctl_fideduperange - share some the data of one file with another file

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/fs.h>      /* Definition of FIDEDUPERANGE and
                              FILE_DEDUPE_* constants*/
#include <sys/ioctl.h>
```

```
int ioctl(int src_fd, FIDEDUPERANGE, struct file_dedupe_range *arg);
```

## DESCRIPTION
If a filesystem supports files sharing physical storage between multiple files, this ioctl(2) operation can be used to make some of the data in the src_fd file appear in the dest_fd file by sharing the underlying storage if the file data is identical ("deduplication"). Both files must reside within the same filesystem. This reduces storage consumption by allowing the filesystem to store one shared copy of the data. If a file write should occur to a shared region, the filesystem must ensure that the changes remain private to the file being written. This behavior is commonly referred to as "copy on write".

This ioctl performs the "compare and share if identical" operation on up to src_length bytes from file descriptor src_fd at offset src_offset. This information is conveyed in a structure of the following form:

```
struct file_dedupe_range {

    __u64 src_offset;

    __u64 src_length;

    __u16 dest_count;

    __u16 reserved1;

    __u32 reserved2;

    struct file_dedupe_range_info info[0];
};
```

Deduplication is atomic with regards to concurrent writes, so no locks need to be taken to obtain a consistent deduplicated copy.

The fields reserved1 and reserved2 must be zero.

Destinations for the deduplication operation are conveyed in the array at the end of the structure. The number of destinations is given in dest_count, and the destination information is conveyed in the following form:

```
struct file_dedupe_range_info {

    __s64 dest_fd;

    __u64 dest_offset;

    __u64 bytes_deduped;

    __s32 status;

    __u32 reserved;
};
```

Each deduplication operation targets src_length bytes in file descriptor dest_fd at offset dest_offset. The field reserved must be zero. During the call, src_fd must be open for reading and dest_fd must be open for writing. The combined size of the struct file_dedupe_range and the struct file_dedupe_range_info array must not exceed the system page size. The maximum size of src_length is filesystem dependent and is typically 16 MiB. This limit will be enforced silently by the filesystem. By convention, the storage used by src_fd is mapped into dest_fd and the previous contents in dest_fd are freed.

Upon successful completion of this ioctl, the number of bytes successfully deduplicated is returned in bytes_deduped and a status code for the deduplication operation is returned in status. If even a single byte in the range does not match, the deduplication request will be ignored and status set to FILE_DEDUPE_RANGE_DIFFERS. The status code is set to FILE_DEDUPE_RANGE_SAME for success, a negative error code in case of error, or FILE_DEDUPE_RANGE_DIFFERS if the data did not match.

## RETURN VALUE
On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
Possible errors include (but are not limited to) the following:

EBADF

src_fd is not open for reading; dest_fd is not open for writing or is open for append-only writes; or the filesystem which src_fd resides on does not support deduplication.

EINVAL

The filesystem does not support deduplicating the ranges of the given files. This error can also appear if either file descriptor represents a device, FIFO, or socket. Disk filesystems generally require the offset and length arguments to be aligned to the fundamental block size. Neither Btrfs nor XFS support overlapping deduplication ranges in the same file.

EISDIR

One of the files is a directory and the filesystem does not support shared regions in directories.

ENOMEM

The kernel was unable to allocate sufficient memory to perform the operation or dest_count is so large that the input argument description spans more than a single page of memory.

EOPNOTSUPP

This can appear if the filesystem does not support deduplicating either file descriptor, or if either file descriptor refers to special inodes.

EPERM

dest_fd is immutable.

ETXTBSY

One of the files is a swap file. Swap files cannot share storage.

EXDEV

dest_fd and src_fd are not on the same mounted filesystem.

## VERSIONS
Some filesystems may limit the amount of data that can be deduplicated in a single call.

## STANDARDS
Linux.

## HISTORY
Linux 4.5.

It was previously known as BTRFS_IOC_FILE_EXTENT_SAME and was private to Btrfs.

## NOTES
Because a copy-on-write operation requires the allocation of new storage, the fallocate(2) operation may unshare shared blocks to guarantee that subsequent writes will not fail because of lack of disk space.

## SEE ALSO
ioctl(2)


title: ioctl_fslabel(2)

summary: get or set a filesystem label

text:
# ioctl_fslabel(2)

## NAME
ioctl_fslabel - get or set a filesystem label

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/fs.h>       /* Definition of *FSLABEL* constants */
#include <sys/ioctl.h>
```

```
int ioctl(int fd, FS_IOC_GETFSLABEL, char label[FSLABEL_MAX]);
int ioctl(int fd, FS_IOC_SETFSLABEL, char label[FSLABEL_MAX]);
```

## DESCRIPTION
If a filesystem supports online label manipulation, these ioctl(2) operations can be used to get or set the filesystem label for the filesystem on which fd resides. The FS_IOC_SETFSLABEL operation requires privilege (CAP_SYS_ADMIN).

## RETURN VALUE
On success zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
Possible errors include (but are not limited to) the following:

EFAULT

label references an inaccessible memory area.

EINVAL

The specified label exceeds the maximum label length for the filesystem.

ENOTTY

This can appear if the filesystem does not support online label manipulation.

EPERM

The calling process does not have sufficient permissions to set the label.

## STANDARDS
Linux.

## HISTORY
Linux 4.18.

They were previously known as BTRFS_IOC_GET_FSLABEL and BTRFS_IOC_SET_FSLABEL and were private to Btrfs.

## NOTES
The maximum string length for this interface is FSLABEL_MAX, including the terminating null byte ('\0'). Filesystems have differing maximum label lengths, which may or may not include the terminating null. The string provided to FS_IOC_SETFSLABEL must always be null-terminated, and the string returned by FS_IOC_GETFSLABEL will always be null-terminated.

## SEE ALSO
ioctl(2), blkid(8)


title: ioctl_getfsmap(2)

text:
# ioctl_getfsmap(2)

## NAME
ioctl_getfsmap - retrieve the physical layout of the filesystem

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/fsmap.h>  /* Definition of FS_IOC_GETFSMAP,
                             FM?_OF_*, and *FMR_OWN_* constants */
#include <sys/ioctl.h>
```

```
int ioctl(int fd, FS_IOC_GETFSMAP, struct fsmap_head * arg);
```

## DESCRIPTION
This ioctl(2) operation retrieves physical extent mappings for a filesystem. This information can be used to discover which files are mapped to a physical block, examine free space, or find known bad blocks, among other things.

The sole argument to this operation should be a pointer to a single struct fsmap_head:

```
struct fsmap {

    __u32 fmr_device;      /* Device ID */

    __u32 fmr_flags;       /* Mapping flags */

    __u64 fmr_physical;    /* Device offset of segment */

    __u64 fmr_owner;       /* Owner ID */

    __u64 fmr_offset;      /* File offset of segment */

    __u64 fmr_length;      /* Length of segment */

    __u64 fmr_reserved[3]; /* Must be zero */
};
struct fsmap_head {

    __u32 fmh_iflags;       /* Control flags */

    __u32 fmh_oflags;       /* Output flags */

    __u32 fmh_count;        /* # of entries in array incl. input */

    __u32 fmh_entries;      /* # of entries filled in (output) */

    __u64 fmh_reserved[6];  /* Must be zero */

    struct fsmap fmh_keys[2];  /* Low and high keys for

                                  the mapping search */

    struct fsmap fmh_recs[];   /* Returned records */
};
```

The two fmh_keys array elements specify the lowest and highest reverse-mapping key for which the application would like physical mapping information. A reverse mapping key consists of the tuple (device, block, owner, offset). The owner and offset fields are part of the key because some filesystems support sharing physical blocks between multiple files and therefore may return multiple mappings for a given physical block.

Filesystem mappings are copied into the fmh_recs array, which immediately follows the header data.

### Fields of struct fsmap_head
The fmh_iflags field is a bit mask passed to the kernel to alter the output. No flags are currently defined, so the caller must set this value to zero.

The fmh_oflags field is a bit mask of flags set by the kernel concerning the returned mappings. If FMH_OF_DEV_T is set, then the fmr_device field represents a dev_t structure containing the major and minor numbers of the block device.

The fmh_count field contains the number of elements in the array being passed to the kernel. If this value is 0, fmh_entries will be set to the number of records that would have been returned had the array been large enough; no mapping information will be returned.

The fmh_entries field contains the number of elements in the fmh_recs array that contain useful information.

The fmh_reserved fields must be set to zero.

### Keys
The two key records in fsmap_head.fmh_keys specify the lowest and highest extent records in the keyspace that the caller wants returned. A filesystem that can share blocks between files likely requires the tuple (device, physical, owner, offset, flags) to uniquely index any filesystem mapping record. Classic non-sharing filesystems might be able to identify any record with only (device, physical, flags). For example, if the low key is set to (8:0, 36864, 0, 0, 0), the filesystem will only return records for extents starting at or above 36 KiB on disk. If the high key is set to (8:0, 1048576, 0, 0, 0), only records below 1 MiB will be returned. The format of fmr_device in the keys must match the format of the same field in the output records, as defined below. By convention, the field fsmap_head.fmh_keys[0] must contain the low key and fsmap_head.fmh_keys[1] must contain the high key for the request.

For convenience, if fmr_length is set in the low key, it will be added to fmr_block or fmr_offset as appropriate. The caller can take advantage of this subtlety to set up subsequent calls by copying fsmap_head.fmh_recs[fsmap_head.fmh_entries - 1] into the low key. The function fsmap_advance (defined in linux/fsmap.h) provides this functionality.

### Fields of struct fsmap
The fmr_device field uniquely identifies the underlying storage device. If the FMH_OF_DEV_T flag is set in the header's fmh_oflags field, this field contains a dev_t from which major and minor numbers can be extracted. If the flag is not set, this field contains a value that must be unique for each unique storage device.

The fmr_physical field contains the disk address of the extent in bytes.

The fmr_owner field contains the owner of the extent. This is an inode number unless FMR_OF_SPECIAL_OWNER is set in the fmr_flags field, in which case the value is determined by the filesystem. See the section below about owner values for more details.

The fmr_offset field contains the logical address in the mapping record in bytes. This field has no meaning if the FMR_OF_SPECIAL_OWNER or FMR_OF_EXTENT_MAP flags are set in fmr_flags.

The fmr_length field contains the length of the extent in bytes.

The fmr_flags field is a bit mask of extent state flags. The bits are:

FMR_OF_PREALLOC

The extent is allocated but not yet written.

FMR_OF_ATTR_FORK

This extent contains extended attribute data.

FMR_OF_EXTENT_MAP

This extent contains extent map information for the owner.

FMR_OF_SHARED

Parts of this extent may be shared.

FMR_OF_SPECIAL_OWNER

The fmr_owner field contains a special value instead of an inode number.

FMR_OF_LAST

This is the last record in the data set.

The fmr_reserved field will be set to zero.

### Owner values
Generally, the value of the fmr_owner field for non-metadata extents should be an inode number. However, filesystems are under no obligation to report inode numbers; they may instead report FMR_OWN_UNKNOWN if the inode number cannot easily be retrieved, if the caller lacks sufficient privilege, if the filesystem does not support stable inode numbers, or for any other reason. If a filesystem wishes to condition the reporting of inode numbers based on process capabilities, it is strongly urged that the CAP_SYS_ADMIN capability be used for this purpose.

The following special owner values are generic to all filesystems:

FMR_OWN_FREE

Free space.

FMR_OWN_UNKNOWN

This extent is in use but its owner is not known or not easily retrieved.

FMR_OWN_METADATA

This extent is filesystem metadata.

XFS can return the following special owner values:

XFS_FMR_OWN_FREE

Free space.

XFS_FMR_OWN_UNKNOWN

This extent is in use but its owner is not known or not easily retrieved.

XFS_FMR_OWN_FS

Static filesystem metadata which exists at a fixed address. These are the AG superblock, the AGF, the AGFL, and the AGI headers.

XFS_FMR_OWN_LOG

The filesystem journal.

XFS_FMR_OWN_AG

Allocation group metadata, such as the free space btrees and the reverse mapping btrees.

XFS_FMR_OWN_INOBT

The inode and free inode btrees.

XFS_FMR_OWN_INODES

Inode records.

XFS_FMR_OWN_REFC

Reference count information.

XFS_FMR_OWN_COW

This extent is being used to stage a copy-on-write.

XFS_FMR_OWN_DEFECTIVE:

This extent has been marked defective either by the filesystem or the underlying device.

ext4 can return the following special owner values:

EXT4_FMR_OWN_FREE

Free space.

EXT4_FMR_OWN_UNKNOWN

This extent is in use but its owner is not known or not easily retrieved.

EXT4_FMR_OWN_FS

Static filesystem metadata which exists at a fixed address. This is the superblock and the group descriptors.

EXT4_FMR_OWN_LOG

The filesystem journal.

EXT4_FMR_OWN_INODES

Inode records.

EXT4_FMR_OWN_BLKBM

Block bit map.

EXT4_FMR_OWN_INOBM

Inode bit map.

## RETURN VALUE
On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
The error placed in errno can be one of, but is not limited to, the following:

EBADF

fd is not open for reading.

EBADMSG

The filesystem has detected a checksum error in the metadata.

EFAULT

The pointer passed in was not mapped to a valid memory address.

EINVAL

The array is not long enough, the keys do not point to a valid part of the filesystem, the low key points to a higher point in the filesystem's physical storage address space than the high key, or a nonzero value was passed in one of the fields that must be zero.

ENOMEM

Insufficient memory to process the request.

EOPNOTSUPP

The filesystem does not support this command.

EUCLEAN

The filesystem metadata is corrupt and needs repair.

## STANDARDS
Linux.

Not all filesystems support it.

## HISTORY
Linux 4.12.

## EXAMPLES
See io/fsmap.c in the xfsprogs distribution for a sample program.

## SEE ALSO
ioctl(2)


title: ioctl_iflags(2)

summary: ioctl() operations for inode flags

text:
# ioctl_iflags(2)

## NAME
ioctl_iflags - ioctl() operations for inode flags

## DESCRIPTION
Various Linux filesystems support the notion of inode flags—attributes that modify the semantics of files and directories. These flags can be retrieved and modified using two ioctl(2) operations:

```
int attr;
fd = open("pathname", ...);
ioctl(fd, FS_IOC_GETFLAGS, &attr);  /* Place current flags

                                       in 'attr' */
attr |= FS_NOATIME_FL;              /* Tweak returned bit mask */
ioctl(fd, FS_IOC_SETFLAGS, &attr);  /* Update flags for inode

                                       referred to by 'fd' */
```

The lsattr(1) and chattr(1) shell commands provide interfaces to these two operations, allowing a user to view and modify the inode flags associated with a file.

The following flags are supported (shown along with the corresponding letter used to indicate the flag by lsattr(1) and chattr(1)):

FS_APPEND_FL 'a'

The file can be opened only with the O_APPEND flag. (This restriction applies even to the superuser.) Only a privileged process (CAP_LINUX_IMMUTABLE) can set or clear this attribute.

FS_COMPR_FL 'c'

Store the file in a compressed format on disk. This flag is not supported by most of the mainstream filesystem implementations; one exception is btrfs(5).

FS_DIRSYNC_FL 'D' (since Linux 2.6.0)

Write directory changes synchronously to disk. This flag provides semantics equivalent to the mount(2) MS_DIRSYNC option, but on a per-directory basis. This flag can be applied only to directories.

FS_IMMUTABLE_FL 'i'

The file is immutable: no changes are permitted to the file contents or metadata (permissions, timestamps, ownership, link count, and so on). (This restriction applies even to the superuser.) Only a privileged process (CAP_LINUX_IMMUTABLE) can set or clear this attribute.

FS_JOURNAL_DATA_FL 'j'

Enable journaling of file data on ext3(5) and ext4(5) filesystems. On a filesystem that is journaling in ordered or writeback mode, a privileged (CAP_SYS_RESOURCE) process can set this flag to enable journaling of data updates on a per-file basis.

FS_NOATIME_FL 'A'

Don't update the file last access time when the file is accessed. This can provide I/O performance benefits for applications that do not care about the accuracy of this timestamp. This flag provides functionality similar to the mount(2) MS_NOATIME flag, but on a per-file basis.

FS_NOCOW_FL 'C' (since Linux 2.6.39)

The file will not be subject to copy-on-write updates. This flag has an effect only on filesystems that support copy-on-write semantics, such as Btrfs. See chattr(1) and btrfs(5).

FS_NODUMP_FL 'd'

Don't include this file in backups made using dump(8).

FS_NOTAIL_FL 't'

This flag is supported only on Reiserfs. It disables the Reiserfs tail-packing feature, which tries to pack small files (and the final fragment of larger files) into the same disk block as the file metadata.

FS_PROJINHERIT_FL 'P' (since Linux 4.5)

Inherit the quota project ID. Files and subdirectories will inherit the project ID of the directory. This flag can be applied only to directories.

FS_SECRM_FL 's'

Mark the file for secure deletion. This feature is not implemented by any filesystem, since the task of securely erasing a file from a recording medium is surprisingly difficult.

FS_SYNC_FL 'S'

Make file updates synchronous. For files, this makes all writes synchronous (as though all opens of the file were with the O_SYNC flag). For directories, this has the same effect as the FS_DIRSYNC_FL flag.

FS_TOPDIR_FL 'T'

Mark a directory for special treatment under the Orlov block-allocation strategy. See chattr(1) for details. This flag can be applied only to directories and has an effect only for ext2, ext3, and ext4.

FS_UNRM_FL 'u'

Allow the file to be undeleted if it is deleted. This feature is not implemented by any filesystem, since it is possible to implement file-recovery mechanisms outside the kernel.

In most cases, when any of the above flags is set on a directory, the flag is inherited by files and subdirectories created inside that directory. Exceptions include FS_TOPDIR_FL, which is not inheritable, and FS_DIRSYNC_FL, which is inherited only by subdirectories.

## STANDARDS
Linux.

## NOTES
In order to change the inode flags of a file using the FS_IOC_SETFLAGS operation, the effective user ID of the caller must match the owner of the file, or the caller must have the CAP_FOWNER capability.

The type of the argument given to the FS_IOC_GETFLAGS and FS_IOC_SETFLAGS operations is int *, notwithstanding the implication in the kernel source file include/uapi/linux/fs.h that the argument is long *.

## SEE ALSO
chattr(1), lsattr(1), mount(2), btrfs(5), ext4(5), xfs(5), xattr(7), mount(8)


title: ioctl_ns(2)

summary: ioctl() operations for Linux namespaces

text:
# ioctl_ns(2)

## NAME
ioctl_ns - ioctl() operations for Linux namespaces

## DESCRIPTION

### Discovering namespace relationships
The following ioctl(2) operations are provided to allow discovery of namespace relationships (see user_namespaces(7) and pid_namespaces(7)). The form of the calls is:

```
new_fd = ioctl(fd, request);
```

In each case, fd refers to a /proc/pid/ns/* file. Both operations return a new file descriptor on success.

NS_GET_USERNS (since Linux 4.9)

Returns a file descriptor that refers to the owning user namespace for the namespace referred to by fd.

NS_GET_PARENT (since Linux 4.9)

Returns a file descriptor that refers to the parent namespace of the namespace referred to by fd. This operation is valid only for hierarchical namespaces (i.e., PID and user namespaces). For user namespaces, NS_GET_PARENT is synonymous with NS_GET_USERNS.

The new file descriptor returned by these operations is opened with the O_RDONLY and O_CLOEXEC (close-on-exec; see fcntl(2)) flags.

By applying fstat(2) to the returned file descriptor, one obtains a stat structure whose st_dev (resident device) and st_ino (inode number) fields together identify the owning/parent namespace. This inode number can be matched with the inode number of another /proc/pid/ns/{pid,user} file to determine whether that is the owning/parent namespace.

Either of these ioctl(2) operations can fail with the following errors:

EPERM

The requested namespace is outside of the caller's namespace scope. This error can occur if, for example, the owning user namespace is an ancestor of the caller's current user namespace. It can also occur on attempts to obtain the parent of the initial user or PID namespace.

ENOTTY

The operation is not supported by this kernel version.

Additionally, the NS_GET_PARENT operation can fail with the following error:

EINVAL

fd refers to a nonhierarchical namespace.

See the EXAMPLES section for an example of the use of these operations.

### Discovering the namespace type
The NS_GET_NSTYPE operation (available since Linux 4.11) can be used to discover the type of namespace referred to by the file descriptor fd:

```
nstype = ioctl(fd, NS_GET_NSTYPE);
```

fd refers to a /proc/pid/ns/* file.

The return value is one of the CLONE_NEW* values that can be specified to clone(2) or unshare(2) in order to create a namespace.

### Discovering the owner of a user namespace
The NS_GET_OWNER_UID operation (available since Linux 4.11) can be used to discover the owner user ID of a user namespace (i.e., the effective user ID of the process that created the user namespace). The form of the call is:

```
uid_t uid;
ioctl(fd, NS_GET_OWNER_UID, &uid);
```

fd refers to a /proc/pid/ns/user file.

The owner user ID is returned in the uid_t pointed to by the third argument.

This operation can fail with the following error:

EINVAL

fd does not refer to a user namespace.

## ERRORS
Any of the above ioctl() operations can return the following errors:

ENOTTY

fd does not refer to a /proc/pid/ns/* file.

## STANDARDS
Linux.

## EXAMPLES
The example shown below uses the ioctl(2) operations described above to perform simple discovery of namespace relationships. The following shell sessions show various examples of the use of this program.

Trying to get the parent of the initial user namespace fails, since it has no parent:

```
$ ./ns_show /proc/self/ns/user p
The parent namespace is outside your namespace scope
```

Create a process running sleep(1) that resides in new user and UTS namespaces, and show that the new UTS namespace is associated with the new user namespace:

```
$ unshare -Uu sleep 1000 &
[1] 23235
$ ./ns_show /proc/23235/ns/uts u
Device/Inode of owning user namespace is: [0,3] / 4026532448
$ readlink /proc/23235/ns/user
user:[4026532448]
```

Then show that the parent of the new user namespace in the preceding example is the initial user namespace:

```
$ readlink /proc/self/ns/user
user:[4026531837]
$ ./ns_show /proc/23235/ns/user p
Device/Inode of parent namespace is: [0,3] / 4026531837
```

Start a shell in a new user namespace, and show that from within this shell, the parent user namespace can't be discovered. Similarly, the UTS namespace (which is associated with the initial user namespace) can't be discovered.

```
$ PS1="sh2$ " unshare -U bash
sh2$ ./ns_show /proc/self/ns/user p
The parent namespace is outside your namespace scope
sh2$ ./ns_show /proc/self/ns/uts u
The owning user namespace is outside your namespace scope
```

### Program source

```
/* ns_show.c

   Licensed under the GNU General Public License v2 or later.
*/
#include <errno.h>
#include <fcntl.h>
#include <linux/nsfs.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{

    int          fd, userns_fd, parent_fd;

    struct stat  sb;

    if (argc < 2) {

        fprintf(stderr, "Usage: %s /proc/[pid]/ns/[file] [p|u]\n",

                argv[0]);

        fprintf(stderr, "\nDisplay the result of one or both "

                "of NS_GET_USERNS (u) or NS_GET_PARENT (p)\n"

                "for the specified /proc/[pid]/ns/[file]. If neither "

                "'p' nor 'u' is specified,\n"

                "NS_GET_USERNS is the default.\n");

        exit(EXIT_FAILURE);

    }

    /* Obtain a file descriptor for the 'ns' file specified

       in argv[1]. */

    fd = open(argv[1], O_RDONLY);

    if (fd == -1) {

        perror("open");

        exit(EXIT_FAILURE);

    }

    /* Obtain a file descriptor for the owning user namespace and

       then obtain and display the inode number of that namespace. */

    if (argc < 3 || strchr(argv[2], 'u')) {

        userns_fd = ioctl(fd, NS_GET_USERNS);

        if (userns_fd == -1) {

            if (errno == EPERM)

                printf("The owning user namespace is outside "

                       "your namespace scope\n");

            else

               perror("ioctl-NS_GET_USERNS");

            exit(EXIT_FAILURE);

         }

        if (fstat(userns_fd, &sb) == -1) {

            perror("fstat-userns");

            exit(EXIT_FAILURE);

        }

        printf("Device/Inode of owning user namespace is: "

               "[%x,%x] / %ju\n",

               major(sb.st_dev),

               minor(sb.st_dev),

               (uintmax_t) sb.st_ino);

        close(userns_fd);

    }

    /* Obtain a file descriptor for the parent namespace and

       then obtain and display the inode number of that namespace. */

    if (argc > 2 && strchr(argv[2], 'p')) {

        parent_fd = ioctl(fd, NS_GET_PARENT);

        if (parent_fd == -1) {

            if (errno == EINVAL)

                printf("Can' get parent namespace of a "

                       "nonhierarchical namespace\n");

            else if (errno == EPERM)

                printf("The parent namespace is outside "

                       "your namespace scope\n");

            else

                perror("ioctl-NS_GET_PARENT");

            exit(EXIT_FAILURE);

        }

        if (fstat(parent_fd, &sb) == -1) {

            perror("fstat-parentns");

            exit(EXIT_FAILURE);

        }

        printf("Device/Inode of parent namespace is: [%x,%x] / %ju\n",

               major(sb.st_dev),

               minor(sb.st_dev),

               (uintmax_t) sb.st_ino);

        close(parent_fd);

    }

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
fstat(2), ioctl(2), proc(5), namespaces(7)


title: ioctl_pipe(2)

text:
# ioctl_pipe(2)

## NAME
ioctl_pipe - ioctl() operations for General notification mechanism

## SYNOPSIS

```
#include <linux/watch_queue.h>  /* Definition of IOC_WATCH_QUEUE_* */
#include <sys/ioctl.h>
```

```
int ioctl(int pipefd[1], IOC_WATCH_QUEUE_SET_SIZE, int size);
int ioctl(int pipefd[1], IOC_WATCH_QUEUE_SET_FILTER,
          struct watch_notification_filter *filter);
```

## DESCRIPTION
The following ioctl(2) operations are provided to set up general notification queue parameters. The notification queue is built on the top of a pipe(2) opened with the O_NOTIFICATION_PIPE flag.

IOC_WATCH_QUEUE_SET_SIZE (since Linux 5.8)

Preallocates the pipe buffer memory so that it can fit size notification messages. Currently, size must be between 1 and 512.

IOC_WATCH_QUEUE_SET_FILTER (since Linux 5.8)

Watch queue filter can limit events that are received. Filters are passed in a struct watch_notification_filter and each filter is described by a struct watch_notification_type_filter structure.

```
struct watch_notification_filter {

        __u32   nr_filters;

        __u32   __reserved;

        struct watch_notification_type_filter filters[];
};
struct watch_notification_type_filter {

        __u32   type;

        __u32   info_filter;

        __u32   info_mask;

        __u32   subtype_filter[8];
};

```

## SEE ALSO
pipe(2), ioctl(2)


title: ioctl_tty(2)

summary: ioctls for terminals and serial lines

text:
# ioctl_tty(2)

## NAME
ioctl_tty - ioctls for terminals and serial lines

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/ioctl.h>
#include <asm/termbits.h>   /* Definition of struct termios,
                               struct termios2, and
                               Bnnn, BOTHER, CBAUD, CLOCAL,
                               TC*{FLUSH,ON,OFF} and other constants */
```

```
int ioctl(int fd, int cmd, ...);
```

## DESCRIPTION
The ioctl(2) call for terminals and serial ports accepts many possible command arguments. Most require a third argument, of varying type, here called argp or arg.

Use of ioctl() makes for nonportable programs. Use the POSIX interface described in termios(3) whenever possible.

Please note that struct termios from <asm/termbits.h> is different and incompatible with struct termios from <termios.h>. These ioctl calls require struct termios from <asm/termbits.h>.

### Get and set terminal attributes
TCGETS

Argument: struct termios *argp

Equivalent to tcgetattr(fd, argp).

Get the current serial port settings.

TCSETS

Argument: const struct termios *argp

Equivalent to tcsetattr(fd, TCSANOW, argp).

Set the current serial port settings.

TCSETSW

Argument: const struct termios *argp

Equivalent to tcsetattr(fd, TCSADRAIN, argp).

Allow the output buffer to drain, and set the current serial port settings.

TCSETSF

Argument: const struct termios *argp

Equivalent to tcsetattr(fd, TCSAFLUSH, argp).

Allow the output buffer to drain, discard pending input, and set the current serial port settings.

The following four ioctls, added in Linux 2.6.20, are just like TCGETS, TCSETS, TCSETSW, TCSETSF, except that they take a struct termios2 * instead of a struct termios *. If the structure member c_cflag contains the flag BOTHER, then the baud rate is stored in the structure members c_ispeed and c_ospeed as integer values. These ioctls are not supported on all architectures.

TCGETS2

struct termios2 *argp

TCSETS2

const struct termios2 *argp

TCSETSW2

const struct termios2 *argp

TCSETSF2

const struct termios2 *argp

The following four ioctls are just like TCGETS, TCSETS, TCSETSW, TCSETSF, except that they take a struct termio * instead of a struct termios *.

TCGETA

struct termio *argp

TCSETA

const struct termio *argp

TCSETAW

const struct termio *argp

TCSETAF

const struct termio *argp

### Locking the termios structure
The termios structure of a terminal can be locked. The lock is itself a termios structure, with nonzero bits or fields indicating a locked value.

TIOCGLCKTRMIOS

Argument: struct termios *argp

Gets the locking status of the termios structure of the terminal.

TIOCSLCKTRMIOS

Argument: const struct termios *argp

Sets the locking status of the termios structure of the terminal. Only a process with the CAP_SYS_ADMIN capability can do this.

### Get and set window size
Window sizes are kept in the kernel, but not used by the kernel (except in the case of virtual consoles, where the kernel will update the window size when the size of the virtual console changes, for example, by loading a new font).

TIOCGWINSZ

Argument: struct winsize *argp

Get window size.

TIOCSWINSZ

Argument: const struct winsize *argp

Set window size.

The struct used by these ioctls is defined as

```
struct winsize {

    unsigned short ws_row;

    unsigned short ws_col;

    unsigned short ws_xpixel;   /* unused */

    unsigned short ws_ypixel;   /* unused */
};
```

When the window size changes, a SIGWINCH signal is sent to the foreground process group.

### Sending a break
TCSBRK

Argument: int arg

Equivalent to tcsendbreak(fd, arg).

If the terminal is using asynchronous serial data transmission, and arg is zero, then send a break (a stream of zero bits) for between 0.25 and 0.5 seconds. If the terminal is not using asynchronous serial data transmission, then either a break is sent, or the function returns without doing anything. When arg is nonzero, nobody knows what will happen.

(SVr4, UnixWare, Solaris, and Linux treat tcsendbreak(fd,arg) with nonzero arg like tcdrain(fd). SunOS treats arg as a multiplier, and sends a stream of bits arg times as long as done for zero arg. DG/UX and AIX treat arg (when nonzero) as a time interval measured in milliseconds. HP-UX ignores arg.)

TCSBRKP

Argument: int arg

So-called "POSIX version" of TCSBRK. It treats nonzero arg as a time interval measured in deciseconds, and does nothing when the driver does not support breaks.

TIOCSBRK

Argument: void

Turn break on, that is, start sending zero bits.

TIOCCBRK

Argument: void

Turn break off, that is, stop sending zero bits.

### Software flow control
TCXONC

Argument: int arg

Equivalent to tcflow(fd, arg).

See tcflow(3) for the argument values TCOOFF, TCOON, TCIOFF, TCION.

### Buffer count and flushing
FIONREAD

Argument: int *argp

Get the number of bytes in the input buffer.

TIOCINQ

Argument: int *argp

Same as FIONREAD.

TIOCOUTQ

Argument: int *argp

Get the number of bytes in the output buffer.

TCFLSH

Argument: int arg

Equivalent to tcflush(fd, arg).

See tcflush(3) for the argument values TCIFLUSH, TCOFLUSH, TCIOFLUSH.

TIOCSERGETLSR

Argument: int *argp

Get line status register. Status register has TIOCSER_TEMT bit set when output buffer is empty and also hardware transmitter is physically empty.

Does not have to be supported by all serial tty drivers.

tcdrain(3) does not wait and returns immediately when TIOCSER_TEMT bit is set.

### Faking input
TIOCSTI

Argument: const char *argp

Insert the given byte in the input queue.

### Redirecting console output
TIOCCONS

Argument: void

Redirect output that would have gone to /dev/console or /dev/tty0 to the given terminal. If that was a pseudoterminal master, send it to the slave. Before Linux 2.6.10, anybody can do this as long as the output was not redirected yet; since Linux 2.6.10, only a process with the CAP_SYS_ADMIN capability may do this. If output was redirected already, then EBUSY is returned, but redirection can be stopped by using this ioctl with fd pointing at /dev/console or /dev/tty0.

### Controlling terminal
TIOCSCTTY

Argument: int arg

Make the given terminal the controlling terminal of the calling process. The calling process must be a session leader and not have a controlling terminal already. For this case, arg should be specified as zero.

If this terminal is already the controlling terminal of a different session group, then the ioctl fails with EPERM, unless the caller has the CAP_SYS_ADMIN capability and arg equals 1, in which case the terminal is stolen, and all processes that had it as controlling terminal lose it.

TIOCNOTTY

Argument: void

If the given terminal was the controlling terminal of the calling process, give up this controlling terminal. If the process was session leader, then send SIGHUP and SIGCONT to the foreground process group and all processes in the current session lose their controlling terminal.

### Process group and session ID
TIOCGPGRP

Argument: pid_t *argp

When successful, equivalent to *argp = tcgetpgrp(fd).

Get the process group ID of the foreground process group on this terminal.

TIOCSPGRP

Argument: const pid_t *argp

Equivalent to tcsetpgrp(fd, *argp).

Set the foreground process group ID of this terminal.

TIOCGSID

Argument: pid_t *argp

When successful, equivalent to *argp = tcgetsid(fd).

Get the session ID of the given terminal. This fails with the error ENOTTY if the terminal is not a master pseudoterminal and not our controlling terminal. Strange.

### Exclusive mode
TIOCEXCL

Argument: void

Put the terminal into exclusive mode. No further open(2) operations on the terminal are permitted. (They fail with EBUSY, except for a process with the CAP_SYS_ADMIN capability.)

TIOCGEXCL

Argument: int *argp

(since Linux 3.8) If the terminal is currently in exclusive mode, place a nonzero value in the location pointed to by argp; otherwise, place zero in *argp.

TIOCNXCL

Argument: void

Disable exclusive mode.

### Line discipline
TIOCGETD

Argument: int *argp

Get the line discipline of the terminal.

TIOCSETD

Argument: const int *argp

Set the line discipline of the terminal.

### Pseudoterminal ioctls
TIOCPKT

Argument: const int *argp

Enable (when *argp is nonzero) or disable packet mode. Can be applied to the master side of a pseudoterminal only (and will return ENOTTY otherwise). In packet mode, each subsequent read(2) will return a packet that either contains a single nonzero control byte, or has a single byte containing zero ('\0') followed by data written on the slave side of the pseudoterminal. If the first byte is not TIOCPKT_DATA (0), it is an OR of one or more of the following bits:

TIOCPKT_FLUSHREAD

The read queue for the terminal is flushed.

TIOCPKT_FLUSHWRITE

The write queue for the terminal is flushed.

TIOCPKT_STOP

Output to the terminal is stopped.

TIOCPKT_START

Output to the terminal is restarted.

TIOCPKT_DOSTOP

The start and stop characters are ^S/^Q.

TIOCPKT_NOSTOP

The start and stop characters are not ^S/^Q.

While packet mode is in use, the presence of control status information to be read from the master side may be detected by a select(2) for exceptional conditions or a poll(2) for the POLLPRI event.

This mode is used by rlogin(1) and rlogind(8) to implement a remote-echoed, locally ^S/^Q flow-controlled remote login.

TIOCGPKT

Argument: const int *argp

(since Linux 3.8) Return the current packet mode setting in the integer pointed to by argp.

TIOCSPTLCK

Argument: int *argp

Set (if *argp is nonzero) or remove (if *argp is zero) the lock on the pseudoterminal slave device. (See also unlockpt(3).)

TIOCGPTLCK

Argument: int *argp

(since Linux 3.8) Place the current lock state of the pseudoterminal slave device in the location pointed to by argp.

TIOCGPTPEER

Argument: int flags

(since Linux 4.13) Given a file descriptor in fd that refers to a pseudoterminal master, open (with the given open(2)-style flags) and return a new file descriptor that refers to the peer pseudoterminal slave device. This operation can be performed regardless of whether the pathname of the slave device is accessible through the calling process's mount namespace.

Security-conscious programs interacting with namespaces may wish to use this operation rather than open(2) with the pathname returned by ptsname(3), and similar library functions that have insecure APIs. (For example, confusion can occur in some cases using ptsname(3) with a pathname where a devpts filesystem has been mounted in a different mount namespace.)

The BSD ioctls TIOCSTOP, TIOCSTART, TIOCUCNTL, and TIOCREMOTE have not been implemented under Linux.

### Modem control
TIOCMGET

Argument: int *argp

Get the status of modem bits.

TIOCMSET

Argument: const int *argp

Set the status of modem bits.

TIOCMBIC

Argument: const int *argp

Clear the indicated modem bits.

TIOCMBIS

Argument: const int *argp

Set the indicated modem bits.

The following bits are used by the above ioctls:

TIOCM_LE

DSR (data set ready/line enable)

TIOCM_DTR

DTR (data terminal ready)

TIOCM_RTS

RTS (request to send)

TIOCM_ST

Secondary TXD (transmit)

TIOCM_SR

Secondary RXD (receive)

TIOCM_CTS

CTS (clear to send)

TIOCM_CAR

DCD (data carrier detect)

TIOCM_CD

see TIOCM_CAR

TIOCM_RNG

RNG (ring)

TIOCM_RI

see TIOCM_RNG

TIOCM_DSR

DSR (data set ready)

TIOCMIWAIT

Argument: int arg

Wait for any of the 4 modem bits (DCD, RI, DSR, CTS) to change. The bits of interest are specified as a bit mask in arg, by ORing together any of the bit values, TIOCM_RNG, TIOCM_DSR, TIOCM_CD, and TIOCM_CTS. The caller should use TIOCGICOUNT to see which bit has changed.

TIOCGICOUNT

Argument: struct serial_icounter_struct *argp

Get counts of input serial line interrupts (DCD, RI, DSR, CTS). The counts are written to the serial_icounter_struct structure pointed to by argp.

Note: both 1->0 and 0->1 transitions are counted, except for RI, where only 0->1 transitions are counted.

### Marking a line as local
TIOCGSOFTCAR

Argument: int *argp

("Get software carrier flag") Get the status of the CLOCAL flag in the c_cflag field of the termios structure.

TIOCSSOFTCAR

Argument: const int *argp

("Set software carrier flag") Set the CLOCAL flag in the termios structure when *argp is nonzero, and clear it otherwise.

If the CLOCAL flag for a line is off, the hardware carrier detect (DCD) signal is significant, and an open(2) of the corresponding terminal will block until DCD is asserted, unless the O_NONBLOCK flag is given. If CLOCAL is set, the line behaves as if DCD is always asserted. The software carrier flag is usually turned on for local devices, and is off for lines with modems.

### Linux-specific
For the TIOCLINUX ioctl, see ioctl_console(2).

### Kernel debugging
\#include <linux/tty.h>

TIOCTTYGSTRUCT

Argument: struct tty_struct *argp

Get the tty_struct corresponding to fd. This command was removed in Linux 2.5.67.

## RETURN VALUE
The ioctl(2) system call returns 0 on success. On error, it returns -1 and sets errno to indicate the error.

## ERRORS
EINVAL

Invalid command parameter.

ENOIOCTLCMD

Unknown command.

ENOTTY

Inappropriate fd.

EPERM

Insufficient permission.

## EXAMPLES
Check the condition of DTR on the serial port.

```
#include <fcntl.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <unistd.h>
int
main(void)
{

    int fd, serial;

    fd = open("/dev/ttyS0", O_RDONLY);

    ioctl(fd, TIOCMGET, &serial);

    if (serial & TIOCM_DTR)

        puts("TIOCM_DTR is set");

    else

        puts("TIOCM_DTR is not set");

    close(fd);
}
```

Get or set arbitrary baudrate on the serial port.

```
/* SPDX-License-Identifier: GPL-2.0-or-later */
#include <asm/termbits.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
#if !defined BOTHER

    fprintf(stderr, "BOTHER is unsupported\n");

    /* Program may fallback to TCGETS/TCSETS with Bnnn constants */

    exit(EXIT_FAILURE);
#else

    /* Declare tio structure, its type depends on supported ioctl */
# if defined TCGETS2

    struct termios2 tio;
# else

    struct termios tio;
# endif

    int fd, rc;

    if (argc != 2 && argc != 3 && argc != 4) {

        fprintf(stderr, "Usage: %s device [output [input] ]\n", argv[0]);

        exit(EXIT_FAILURE);

    }

    fd = open(argv[1], O_RDWR | O_NONBLOCK | O_NOCTTY);

    if (fd < 0) {

        perror("open");

        exit(EXIT_FAILURE);

    }

    /* Get the current serial port settings via supported ioctl */
# if defined TCGETS2

    rc = ioctl(fd, TCGETS2, &tio);
# else

    rc = ioctl(fd, TCGETS, &tio);
# endif

    if (rc) {

        perror("TCGETS");

        close(fd);

        exit(EXIT_FAILURE);

    }

    /* Change baud rate when more arguments were provided */

    if (argc == 3 || argc == 4) {

        /* Clear the current output baud rate and fill a new value */

        tio.c_cflag &= ~CBAUD;

        tio.c_cflag |= BOTHER;

        tio.c_ospeed = atoi(argv[2]);

        /* Clear the current input baud rate and fill a new value */

        tio.c_cflag &= ~(CBAUD << IBSHIFT);

        tio.c_cflag |= BOTHER << IBSHIFT;

        /* When 4th argument is not provided reuse output baud rate */

        tio.c_ispeed = (argc == 4) ? atoi(argv[3]) : atoi(argv[2]);

        /* Set new serial port settings via supported ioctl */
# if defined TCSETS2

        rc = ioctl(fd, TCSETS2, &tio);
# else

        rc = ioctl(fd, TCSETS, &tio);
# endif

        if (rc) {

            perror("TCSETS");

            close(fd);

            exit(EXIT_FAILURE);

        }

        /* And get new values which were really configured */
# if defined TCGETS2

        rc = ioctl(fd, TCGETS2, &tio);
# else

        rc = ioctl(fd, TCGETS, &tio);
# endif

        if (rc) {

            perror("TCGETS");

            close(fd);

            exit(EXIT_FAILURE);

        }

    }

    close(fd);

    printf("output baud rate: %u\n", tio.c_ospeed);

    printf("input baud rate: %u\n", tio.c_ispeed);

    exit(EXIT_SUCCESS);
#endif
}
```

## SEE ALSO
ldattach(8), ioctl(2), ioctl_console(2), termios(3), pty(7)


title: ioctl_userfaultfd(2)

text:
# ioctl_userfaultfd(2)

## NAME
ioctl_userfaultfd - create a file descriptor for handling page faults in user space

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/userfaultfd.h>  /* Definition of UFFD* constants */
#include <sys/ioctl.h>
```

```
int ioctl(int fd, int cmd, ...);
```

## DESCRIPTION
Various ioctl(2) operations can be performed on a userfaultfd object (created by a call to userfaultfd(2)) using calls of the form:

```
ioctl(fd, cmd, argp);
```

In the above, fd is a file descriptor referring to a userfaultfd object, cmd is one of the commands listed below, and argp is a pointer to a data structure that is specific to cmd. The various ioctl(2) operations are described below. The UFFDIO_API, UFFDIO_REGISTER, and UFFDIO_UNREGISTER operations are used to configure userfaultfd behavior. These operations allow the caller to choose what features will be enabled and what kinds of events will be delivered to the application. The remaining operations are range operations. These operations enable the calling application to resolve page-fault events.

### UFFDIO_API
(Since Linux 4.3.) Enable operation of the userfaultfd and perform API handshake.

The argp argument is a pointer to a uffdio_api structure, defined as:

```
struct uffdio_api {

    __u64 api;        /* Requested API version (input) */

    __u64 features;   /* Requested features (input/output) */

    __u64 ioctls;     /* Available ioctl() operations (output) */
};
```

The api field denotes the API version requested by the application.

The kernel verifies that it can support the requested API version, and sets the features and ioctls fields to bit masks representing all the available features and the generic ioctl(2) operations available.

Before Linux 4.11, the features field must be initialized to zero before the call to UFFDIO_API, and zero (i.e., no feature bits) is placed in the features field by the kernel upon return from ioctl(2).

Starting from Linux 4.11, the features field can be used to ask whether particular features are supported and explicitly enable userfaultfd features that are disabled by default. The kernel always reports all the available features in the features field.

To enable userfaultfd features the application should set a bit corresponding to each feature it wants to enable in the features field. If the kernel supports all the requested features it will enable them. Otherwise it will zero out the returned uffdio_api structure and return EINVAL.

The following feature bits may be set:

UFFD_FEATURE_EVENT_FORK (since Linux 4.11)

When this feature is enabled, the userfaultfd objects associated with a parent process are duplicated into the child process during fork(2) and a UFFD_EVENT_FORK event is delivered to the userfaultfd monitor

UFFD_FEATURE_EVENT_REMAP (since Linux 4.11)

If this feature is enabled, when the faulting process invokes mremap(2), the userfaultfd monitor will receive an event of type UFFD_EVENT_REMAP.

UFFD_FEATURE_EVENT_REMOVE (since Linux 4.11)

If this feature is enabled, when the faulting process calls madvise(2) with the MADV_DONTNEED or MADV_REMOVE advice value to free a virtual memory area the userfaultfd monitor will receive an event of type UFFD_EVENT_REMOVE.

UFFD_FEATURE_EVENT_UNMAP (since Linux 4.11)

If this feature is enabled, when the faulting process unmaps virtual memory either explicitly with munmap(2), or implicitly during either mmap(2) or mremap(2), the userfaultfd monitor will receive an event of type UFFD_EVENT_UNMAP.

UFFD_FEATURE_MISSING_HUGETLBFS (since Linux 4.11)

If this feature bit is set, the kernel supports registering userfaultfd ranges on hugetlbfs virtual memory areas

UFFD_FEATURE_MISSING_SHMEM (since Linux 4.11)

If this feature bit is set, the kernel supports registering userfaultfd ranges on shared memory areas. This includes all kernel shared memory APIs: System V shared memory, tmpfs(5), shared mappings of /dev/zero, mmap(2) with the MAP_SHARED flag set, memfd_create(2), and so on.

UFFD_FEATURE_SIGBUS (since Linux 4.14)

If this feature bit is set, no page-fault events (UFFD_EVENT_PAGEFAULT) will be delivered. Instead, a SIGBUS signal will be sent to the faulting process. Applications using this feature will not require the use of a userfaultfd monitor for processing memory accesses to the regions registered with userfaultfd.

UFFD_FEATURE_THREAD_ID (since Linux 4.14)

If this feature bit is set, uffd_msg.pagefault.feat.ptid will be set to the faulted thread ID for each page-fault message.

UFFD_FEATURE_MINOR_HUGETLBFS (since Linux 5.13)

If this feature bit is set, the kernel supports registering userfaultfd ranges in minor mode on hugetlbfs-backed memory areas.

UFFD_FEATURE_MINOR_SHMEM (since Linux 5.14)

If this feature bit is set, the kernel supports registering userfaultfd ranges in minor mode on shmem-backed memory areas.

UFFD_FEATURE_EXACT_ADDRESS (since Linux 5.18)

If this feature bit is set, uffd_msg.pagefault.address will be set to the exact page-fault address that was reported by the hardware, and will not mask the offset within the page. Note that old Linux versions might indicate the exact address as well, even though the feature bit is not set.

The returned ioctls field can contain the following bits:

1 << _UFFDIO_API

The UFFDIO_API operation is supported.

1 << _UFFDIO_REGISTER

The UFFDIO_REGISTER operation is supported.

1 << _UFFDIO_UNREGISTER

The UFFDIO_UNREGISTER operation is supported.

This ioctl(2) operation returns 0 on success. On error, -1 is returned and errno is set to indicate the error. Possible errors include:

EFAULT

argp refers to an address that is outside the calling process's accessible address space.

EINVAL

The userfaultfd has already been enabled by a previous UFFDIO_API operation.

EINVAL

The API version requested in the api field is not supported by this kernel, or the features field passed to the kernel includes feature bits that are not supported by the current kernel version.

### UFFDIO_REGISTER
(Since Linux 4.3.) Register a memory address range with the userfaultfd object. The pages in the range must be "compatible". Please refer to the list of register modes below for the compatible memory backends for each mode.

The argp argument is a pointer to a uffdio_register structure, defined as:

```
struct uffdio_range {

    __u64 start;    /* Start of range */

    __u64 len;      /* Length of range (bytes) */
};
struct uffdio_register {

    struct uffdio_range range;

    __u64 mode;     /* Desired mode of operation (input) */

    __u64 ioctls;   /* Available ioctl() operations (output) */
};
```

The range field defines a memory range starting at start and continuing for len bytes that should be handled by the userfaultfd.

The mode field defines the mode of operation desired for this memory region. The following values may be bitwise ORed to set the userfaultfd mode for the specified range:

UFFDIO_REGISTER_MODE_MISSING

Track page faults on missing pages. Since Linux 4.3, only private anonymous ranges are compatible. Since Linux 4.11, hugetlbfs and shared memory ranges are also compatible.

UFFDIO_REGISTER_MODE_WP

Track page faults on write-protected pages. Since Linux 5.7, only private anonymous ranges are compatible.

UFFDIO_REGISTER_MODE_MINOR

Track minor page faults. Since Linux 5.13, only hugetlbfs ranges are compatible. Since Linux 5.14, compatibility with shmem ranges was added.

If the operation is successful, the kernel modifies the ioctls bit-mask field to indicate which ioctl(2) operations are available for the specified range. This returned bit mask can contain the following bits:

1 << _UFFDIO_COPY

The UFFDIO_COPY operation is supported.

1 << _UFFDIO_WAKE

The UFFDIO_WAKE operation is supported.

1 << _UFFDIO_WRITEPROTECT

The UFFDIO_WRITEPROTECT

1 << _UFFDIO_ZEROPAGE

The UFFDIO_ZEROPAGE operation is supported.

1 << _UFFDIO_CONTINUE

The UFFDIO_CONTINUE operation is supported.

This ioctl(2) operation returns 0 on success. On error, -1 is returned and errno is set to indicate the error. Possible errors include:

EBUSY

A mapping in the specified range is registered with another userfaultfd object.

EFAULT

argp refers to an address that is outside the calling process's accessible address space.

EINVAL

An invalid or unsupported bit was specified in the mode field; or the mode field was zero.

EINVAL

There is no mapping in the specified address range.

EINVAL

range.start or range.len is not a multiple of the system page size; or, range.len is zero; or these fields are otherwise invalid.

EINVAL

There as an incompatible mapping in the specified address range.

### UFFDIO_UNREGISTER
(Since Linux 4.3.) Unregister a memory address range from userfaultfd. The pages in the range must be "compatible" (see the description of UFFDIO_REGISTER.)

The address range to unregister is specified in the uffdio_range structure pointed to by argp.

This ioctl(2) operation returns 0 on success. On error, -1 is returned and errno is set to indicate the error. Possible errors include:

EINVAL

Either the start or the len field of the ufdio_range structure was not a multiple of the system page size; or the len field was zero; or these fields were otherwise invalid.

EINVAL

There as an incompatible mapping in the specified address range.

EINVAL

There was no mapping in the specified address range.

### UFFDIO_COPY
(Since Linux 4.3.) Atomically copy a continuous memory chunk into the userfault registered range and optionally wake up the blocked thread. The source and destination addresses and the number of bytes to copy are specified by the src, dst, and len fields of the uffdio_copy structure pointed to by argp:

```
struct uffdio_copy {

    __u64 dst;    /* Destination of copy */

    __u64 src;    /* Source of copy */

    __u64 len;    /* Number of bytes to copy */

    __u64 mode;   /* Flags controlling behavior of copy */

    __s64 copy;   /* Number of bytes copied, or negated error */
};
```

The following value may be bitwise ORed in mode to change the behavior of the UFFDIO_COPY operation:

UFFDIO_COPY_MODE_DONTWAKE

Do not wake up the thread that waits for page-fault resolution

UFFDIO_COPY_MODE_WP

Copy the page with read-only permission. This allows the user to trap the next write to the page, which will block and generate another write-protect userfault message. This is used only when both UFFDIO_REGISTER_MODE_MISSING and UFFDIO_REGISTER_MODE_WP modes are enabled for the registered range.

The copy field is used by the kernel to return the number of bytes that was actually copied, or an error (a negated errno-style value). If the value returned in copy doesn't match the value that was specified in len, the operation fails with the error EAGAIN. The copy field is output-only; it is not read by the UFFDIO_COPY operation.

This ioctl(2) operation returns 0 on success. In this case, the entire area was copied. On error, -1 is returned and errno is set to indicate the error. Possible errors include:

EAGAIN

The number of bytes copied (i.e., the value returned in the copy field) does not equal the value that was specified in the len field.

EINVAL

Either dst or len was not a multiple of the system page size, or the range specified by src and len or dst and len was invalid.

EINVAL

An invalid bit was specified in the mode field.

ENOENT (since Linux 4.11)

The faulting process has changed its virtual memory layout simultaneously with an outstanding UFFDIO_COPY operation.

ENOSPC (from Linux 4.11 until Linux 4.13)

The faulting process has exited at the time of a UFFDIO_COPY operation.

ESRCH (since Linux 4.13)

The faulting process has exited at the time of a UFFDIO_COPY operation.

### UFFDIO_ZEROPAGE
(Since Linux 4.3.) Zero out a memory range registered with userfaultfd.

The requested range is specified by the range field of the uffdio_zeropage structure pointed to by argp:

```
struct uffdio_zeropage {

    struct uffdio_range range;

    __u64 mode;     /* Flags controlling behavior of copy */

    __s64 zeropage; /* Number of bytes zeroed, or negated error */
};
```

The following value may be bitwise ORed in mode to change the behavior of the UFFDIO_ZEROPAGE operation:

UFFDIO_ZEROPAGE_MODE_DONTWAKE

Do not wake up the thread that waits for page-fault resolution.

The zeropage field is used by the kernel to return the number of bytes that was actually zeroed, or an error in the same manner as UFFDIO_COPY. If the value returned in the zeropage field doesn't match the value that was specified in range.len, the operation fails with the error EAGAIN. The zeropage field is output-only; it is not read by the UFFDIO_ZEROPAGE operation.

This ioctl(2) operation returns 0 on success. In this case, the entire area was zeroed. On error, -1 is returned and errno is set to indicate the error. Possible errors include:

EAGAIN

The number of bytes zeroed (i.e., the value returned in the zeropage field) does not equal the value that was specified in the range.len field.

EINVAL

Either range.start or range.len was not a multiple of the system page size; or range.len was zero; or the range specified was invalid.

EINVAL

An invalid bit was specified in the mode field.

ESRCH (since Linux 4.13)

The faulting process has exited at the time of a UFFDIO_ZEROPAGE operation.

### UFFDIO_WAKE
(Since Linux 4.3.) Wake up the thread waiting for page-fault resolution on a specified memory address range.

The UFFDIO_WAKE operation is used in conjunction with UFFDIO_COPY and UFFDIO_ZEROPAGE operations that have the UFFDIO_COPY_MODE_DONTWAKE or UFFDIO_ZEROPAGE_MODE_DONTWAKE bit set in the mode field. The userfault monitor can perform several UFFDIO_COPY and UFFDIO_ZEROPAGE operations in a batch and then explicitly wake up the faulting thread using UFFDIO_WAKE.

The argp argument is a pointer to a uffdio_range structure (shown above) that specifies the address range.

This ioctl(2) operation returns 0 on success. On error, -1 is returned and errno is set to indicate the error. Possible errors include:

EINVAL

The start or the len field of the ufdio_range structure was not a multiple of the system page size; or len was zero; or the specified range was otherwise invalid.

### UFFDIO_WRITEPROTECT (Since Linux 5.7)
Write-protect or write-unprotect a userfaultfd-registered memory range registered with mode UFFDIO_REGISTER_MODE_WP.

The argp argument is a pointer to a uffdio_range structure as shown below:

```
struct uffdio_writeprotect {

    struct uffdio_range range; /* Range to change write permission*/

    __u64 mode;                /* Mode to change write permission */
};
```

There are two mode bits that are supported in this structure:

UFFDIO_WRITEPROTECT_MODE_WP

When this mode bit is set, the ioctl will be a write-protect operation upon the memory range specified by range. Otherwise it will be a write-unprotect operation upon the specified range, which can be used to resolve a userfaultfd write-protect page fault.

UFFDIO_WRITEPROTECT_MODE_DONTWAKE

When this mode bit is set, do not wake up any thread that waits for page-fault resolution after the operation. This can be specified only if UFFDIO_WRITEPROTECT_MODE_WP is not specified.

This ioctl(2) operation returns 0 on success. On error, -1 is returned and errno is set to indicate the error. Possible errors include:

EINVAL

The start or the len field of the ufdio_range structure was not a multiple of the system page size; or len was zero; or the specified range was otherwise invalid.

EAGAIN

The process was interrupted; retry this call.

ENOENT

The range specified in range is not valid. For example, the virtual address does not exist, or not registered with userfaultfd write-protect mode.

EFAULT

Encountered a generic fault during processing.

### UFFDIO_CONTINUE
(Since Linux 5.13.) Resolve a minor page fault by installing page table entries for existing pages in the page cache.

The argp argument is a pointer to a uffdio_continue structure as shown below:

```
struct uffdio_continue {

    struct uffdio_range range;

                   /* Range to install PTEs for and continue */

    __u64 mode;    /* Flags controlling the behavior of continue */

    __s64 mapped;  /* Number of bytes mapped, or negated error */
};
```

The following value may be bitwise ORed in mode to change the behavior of the UFFDIO_CONTINUE operation:

UFFDIO_CONTINUE_MODE_DONTWAKE

Do not wake up the thread that waits for page-fault resolution.

The mapped field is used by the kernel to return the number of bytes that were actually mapped, or an error in the same manner as UFFDIO_COPY. If the value returned in the mapped field doesn't match the value that was specified in range.len, the operation fails with the error EAGAIN. The mapped field is output-only; it is not read by the UFFDIO_CONTINUE operation.

This ioctl(2) operation returns 0 on success. In this case, the entire area was mapped. On error, -1 is returned and errno is set to indicate the error. Possible errors include:

EAGAIN

The number of bytes mapped (i.e., the value returned in the mapped field) does not equal the value that was specified in the range.len field.

EINVAL

Either range.start or range.len was not a multiple of the system page size; or range.len was zero; or the range specified was invalid.

EINVAL

An invalid bit was specified in the mode field.

EEXIST

One or more pages were already mapped in the given range.

ENOENT

The faulting process has changed its virtual memory layout simultaneously with an outstanding UFFDIO_CONTINUE operation.

ENOMEM

Allocating memory needed to setup the page table mappings failed.

EFAULT

No existing page could be found in the page cache for the given range.

ESRCH

The faulting process has exited at the time of a UFFDIO_CONTINUE operation.

## RETURN VALUE
See descriptions of the individual operations, above.

## ERRORS
See descriptions of the individual operations, above. In addition, the following general errors can occur for all of the operations described above:

EFAULT

argp does not point to a valid memory address.

EINVAL

(For all operations except UFFDIO_API.) The userfaultfd object has not yet been enabled (via the UFFDIO_API operation).

## STANDARDS
Linux.

## BUGS
In order to detect available userfault features and enable some subset of those features the userfaultfd file descriptor must be closed after the first UFFDIO_API operation that queries features availability and reopened before the second UFFDIO_API operation that actually enables the desired features.

## EXAMPLES
See userfaultfd(2).

## SEE ALSO
ioctl(2), mmap(2), userfaultfd(2)

Documentation/admin-guide/mm/userfaultfd.rst in the Linux kernel source tree


ioperm

title: ioperm(2)

summary: set port input/output permissions

text:
# ioperm(2)

## NAME
ioperm - set port input/output permissions

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/io.h>
```

```
int ioperm(unsigned long from, unsigned long num, int turn_on);
```

## DESCRIPTION
ioperm() sets the port access permission bits for the calling thread for num bits starting from port address from. If turn_on is nonzero, then permission for the specified bits is enabled; otherwise it is disabled. If turn_on is nonzero, the calling thread must be privileged (CAP_SYS_RAWIO).

Before Linux 2.6.8, only the first 0x3ff I/O ports could be specified in this manner. For more ports, the iopl(2) system call had to be used (with a level argument of 3). Since Linux 2.6.8, 65,536 I/O ports can be specified.

Permissions are inherited by the child created by fork(2) (but see NOTES). Permissions are preserved across execve(2); this is useful for giving port access permissions to unprivileged programs.

This call is mostly for the i386 architecture. On many other architectures it does not exist or will always return an error.

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EINVAL

Invalid values for from or num.

EIO

(on PowerPC) This call is not supported.

ENOMEM

Out of memory.

EPERM

The calling thread has insufficient privilege.

## VERSIONS
glibc has an ioperm() prototype both in <sys/io.h> and in <sys/perm.h>. Avoid the latter, it is available on i386 only.

## STANDARDS
Linux.

## HISTORY
Before Linux 2.4, permissions were not inherited by a child created by fork(2).

## NOTES
The /proc/ioports file shows the I/O ports that are currently allocated on the system.

## SEE ALSO
iopl(2), outb(2), capabilities(7)


iopl

title: iopl(2)

summary: change I/O privilege level

text:
# iopl(2)

## NAME
iopl - change I/O privilege level

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <sys/io.h>
```

```
[[deprecated]] int iopl(int level);
```

## DESCRIPTION
iopl() changes the I/O privilege level of the calling thread, as specified by the two least significant bits in level.

The I/O privilege level for a normal thread is 0. Permissions are inherited from parents to children.

This call is deprecated, is significantly slower than ioperm(2), and is only provided for older X servers which require access to all 65536 I/O ports. It is mostly for the i386 architecture. On many other architectures it does not exist or will always return an error.

## RETURN VALUE
On success, zero is returned. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EINVAL

level is greater than 3.

ENOSYS

This call is unimplemented.

EPERM

The calling thread has insufficient privilege to call iopl(); the CAP_SYS_RAWIO capability is required to raise the I/O privilege level above its current value.

## VERSIONS
glibc2 has a prototype both in <sys/io.h> and in <sys/perm.h>. Avoid the latter, it is available on i386 only.

## STANDARDS
Linux.

## HISTORY
Prior to Linux 5.5 iopl() allowed the thread to disable interrupts while running at a higher I/O privilege level. This will probably crash the system, and is not recommended.

Prior to Linux 3.7, on some architectures (such as i386), permissions were inherited by the child produced by fork(2) and were preserved across execve(2). This behavior was inadvertently changed in Linux 3.7, and won't be reinstated.

## SEE ALSO
ioperm(2), outb(2), capabilities(7)


title: ioprio_set(2)

text:
# ioprio_set(2)

## NAME
ioprio_get, ioprio_set - get/set I/O scheduling class and priority

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/ioprio.h>    /* Definition of IOPRIO_* constants */
#include <sys/syscall.h>     /* Definition of SYS_* constants */
#include <unistd.h>
```

```
int syscall(SYS_ioprio_get, int which, int who);
int syscall(SYS_ioprio_set, int which, int who, int ioprio);
```

Note: glibc provides no wrappers for these system calls, necessitating the use of syscall(2).

## DESCRIPTION
The ioprio_get() and ioprio_set() system calls get and set the I/O scheduling class and priority of one or more threads.

The which and who arguments identify the thread(s) on which the system calls operate. The which argument determines how who is interpreted, and has one of the following values:

IOPRIO_WHO_PROCESS

who is a process ID or thread ID identifying a single process or thread. If who is 0, then operate on the calling thread.

IOPRIO_WHO_PGRP

who is a process group ID identifying all the members of a process group. If who is 0, then operate on the process group of which the caller is a member.

IOPRIO_WHO_USER

who is a user ID identifying all of the processes that have a matching real UID.

If which is specified as IOPRIO_WHO_PGRP or IOPRIO_WHO_USER when calling ioprio_get(), and more than one process matches who, then the returned priority will be the highest one found among all of the matching processes. One priority is said to be higher than another one if it belongs to a higher priority class (IOPRIO_CLASS_RT is the highest priority class; IOPRIO_CLASS_IDLE is the lowest) or if it belongs to the same priority class as the other process but has a higher priority level (a lower priority number means a higher priority level).

The ioprio argument given to ioprio_set() is a bit mask that specifies both the scheduling class and the priority to be assigned to the target process(es). The following macros are used for assembling and dissecting ioprio values:

IOPRIO_PRIO_VALUE(class, data)

Given a scheduling class and priority (data), this macro combines the two values to produce an ioprio value, which is returned as the result of the macro.

IOPRIO_PRIO_CLASS(mask)

Given mask (an ioprio value), this macro returns its I/O class component, that is, one of the values IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, or IOPRIO_CLASS_IDLE.

IOPRIO_PRIO_DATA(mask)

Given mask (an ioprio value), this macro returns its priority (data) component.

See the NOTES section for more information on scheduling classes and priorities, as well as the meaning of specifying ioprio as 0.

I/O priorities are supported for reads and for synchronous (O_DIRECT, O_SYNC) writes. I/O priorities are not supported for asynchronous writes because they are issued outside the context of the program dirtying the memory, and thus program-specific priorities do not apply.

## RETURN VALUE
On success, ioprio_get() returns the ioprio value of the process with highest I/O priority of any of the processes that match the criteria specified in which and who. On error, -1 is returned, and errno is set to indicate the error.

On success, ioprio_set() returns 0. On error, -1 is returned, and errno is set to indicate the error.

## ERRORS
EINVAL

Invalid value for which or ioprio. Refer to the NOTES section for available scheduler classes and priority levels for ioprio.

EPERM

The calling process does not have the privilege needed to assign this ioprio to the specified process(es). See the NOTES section for more information on required privileges for ioprio_set().

ESRCH

No process(es) could be found that matched the specification in which and who.

## STANDARDS
Linux.

## HISTORY
Linux 2.6.13.

## NOTES
Two or more processes or threads can share an I/O context. This will be the case when clone(2) was called with the CLONE_IO flag. However, by default, the distinct threads of a process will not share the same I/O context. This means that if you want to change the I/O priority of all threads in a process, you may need to call ioprio_set() on each of the threads. The thread ID that you would need for this operation is the one that is returned by gettid(2) or clone(2).

These system calls have an effect only when used in conjunction with an I/O scheduler that supports I/O priorities. As at kernel 2.6.17 the only such scheduler is the Completely Fair Queuing (CFQ) I/O scheduler.

If no I/O scheduler has been set for a thread, then by default the I/O priority will follow the CPU nice value (setpriority(2)). Before Linux 2.6.24, once an I/O priority had been set using ioprio_set(), there was no way to reset the I/O scheduling behavior to the default. Since Linux 2.6.24, specifying ioprio as 0 can be used to reset to the default I/O scheduling behavior.

### Selecting an I/O scheduler
I/O schedulers are selected on a per-device basis via the special file /sys/block/device/queue/scheduler.

One can view the current I/O scheduler via the /sys filesystem. For example, the following command displays a list of all schedulers currently loaded in the kernel:

```
$ cat /sys/block/sda/queue/scheduler
noop anticipatory deadline [cfq]
```

The scheduler surrounded by brackets is the one actually in use for the device (sda in the example). Setting another scheduler is done by writing the name of the new scheduler to this file. For example, the following command will set the scheduler for the sda device to cfq:

```
$ su
Password:
# echo cfq > /sys/block/sda/queue/scheduler
```

### The Completely Fair Queuing (CFQ) I/O scheduler
Since version 3 (also known as CFQ Time Sliced), CFQ implements I/O nice levels similar to those of CPU scheduling. These nice levels are grouped into three scheduling classes, each one containing one or more priority levels:

IOPRIO_CLASS_RT (1)

This is the real-time I/O class. This scheduling class is given higher priority than any other class: processes from this class are given first access to the disk every time. Thus, this I/O class needs to be used with some care: one I/O real-time process can starve the entire system. Within the real-time class, there are 8 levels of class data (priority) that determine exactly how much time this process needs the disk for on each service. The highest real-time priority level is 0; the lowest is 7. In the future, this might change to be more directly mappable to performance, by passing in a desired data rate instead.

IOPRIO_CLASS_BE (2)

This is the best-effort scheduling class, which is the default for any process that hasn't set a specific I/O priority. The class data (priority) determines how much I/O bandwidth the process will get. Best-effort priority levels are analogous to CPU nice values (see getpriority(2)). The priority level determines a priority relative to other processes in the best-effort scheduling class. Priority levels range from 0 (highest) to 7 (lowest).

IOPRIO_CLASS_IDLE (3)

This is the idle scheduling class. Processes running at this level get I/O time only when no one else needs the disk. The idle class has no class data. Attention is required when assigning this priority class to a process, since it may become starved if higher priority processes are constantly accessing the disk.

Refer to the kernel source file Documentation/block/ioprio.txt for more information on the CFQ I/O Scheduler and an example program.

### Required permissions to set I/O priorities
Permission to change a process's priority is granted or denied based on two criteria:

Process ownership

An unprivileged process may set the I/O priority only for a process whose real UID matches the real or effective UID of the calling process. A process which has the CAP_SYS_NICE capability can change the priority of any process.

What is the desired priority

Attempts to set very high priorities (IOPRIO_CLASS_RT) require the CAP_SYS_ADMIN capability. Up to Linux 2.6.24 also required CAP_SYS_ADMIN to set a very low priority (IOPRIO_CLASS_IDLE), but since Linux 2.6.25, this is no longer required.

A call to ioprio_set() must follow both rules, or the call will fail with the error EPERM.

## BUGS
glibc does not yet provide a suitable header file defining the function prototypes and macros described on this page. Suitable definitions can be found in linux/ioprio.h.

## SEE ALSO
ionice(1), getpriority(2), open(2), capabilities(7), cgroups(7)

Documentation/block/ioprio.txt in the Linux kernel source tree


ipc

title: ipc(2)

summary: System V IPC system calls

text:
# ipc(2)

## NAME
ipc - System V IPC system calls

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/ipc.h>        /* Definition of needed constants */
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
int syscall(SYS_ipc, unsigned int call, int first,
            unsigned long second, unsigned long third, void *ptr,
            long fifth);
```

Note: glibc provides no wrapper for ipc(), necessitating the use of syscall(2).

## DESCRIPTION
ipc() is a common kernel entry point for the System V IPC calls for messages, semaphores, and shared memory. call determines which IPC function to invoke; the other arguments are passed through to the appropriate call.

User-space programs should call the appropriate functions by their usual names. Only standard library implementors and kernel hackers need to know about ipc().

## VERSIONS
On some architectures—for example x86-64 and ARM—there is no ipc() system call; instead, msgctl(2), semctl(2), shmctl(2), and so on really are implemented as separate system calls.

## STANDARDS
Linux.

## SEE ALSO
msgctl(2), msgget(2), msgrcv(2), msgsnd(2), semctl(2), semget(2), semop(2), semtimedop(2), shmat(2), shmctl(2), shmdt(2), shmget(2), sysvipc(7)


kcmp

title: kcmp(2)

text:
# kcmp(2)

## NAME
kcmp - compare two processes to determine if they share a kernel resource

## LIBRARY
Standard C library (libc, -lc)

## SYNOPSIS

```
#include <linux/kcmp.h>       /* Definition of KCMP_* constants */
#include <sys/syscall.h>      /* Definition of SYS_* constants */
#include <unistd.h>
```

```
int syscall(SYS_kcmp, pid_t pid1, pid_t pid2, int type,
            unsigned long idx1, unsigned long idx2);
```

Note: glibc provides no wrapper for kcmp(), necessitating the use of syscall(2).

## DESCRIPTION
The kcmp() system call can be used to check whether the two processes identified by pid1 and pid2 share a kernel resource such as virtual memory, file descriptors, and so on.

Permission to employ kcmp() is governed by ptrace access mode PTRACE_MODE_READ_REALCREDS checks against both pid1 and pid2; see ptrace(2).

The type argument specifies which resource is to be compared in the two processes. It has one of the following values:

KCMP_FILE

Check whether a file descriptor idx1 in the process pid1 refers to the same open file description (see open(2)) as file descriptor idx2 in the process pid2. The existence of two file descriptors that refer to the same open file description can occur as a result of dup(2) (and similar) fork(2), or passing file descriptors via a domain socket (see unix(7)).

KCMP_FILES

Check whether the processes share the same set of open file descriptors. The arguments idx1 and idx2 are ignored. See the discussion of the CLONE_FILES flag in clone(2).

KCMP_FS

Check whether the processes share the same filesystem information (i.e., file mode creation mask, working directory, and filesystem root). The arguments idx1 and idx2 are ignored. See the discussion of the CLONE_FS flag in clone(2).

KCMP_IO

Check whether the processes share I/O context. The arguments idx1 and idx2 are ignored. See the discussion of the CLONE_IO flag in clone(2).

KCMP_SIGHAND

Check whether the processes share the same table of signal dispositions. The arguments idx1 and idx2 are ignored. See the discussion of the CLONE_SIGHAND flag in clone(2).

KCMP_SYSVSEM

Check whether the processes share the same list of System V semaphore undo operations. The arguments idx1 and idx2 are ignored. See the discussion of the CLONE_SYSVSEM flag in clone(2).

KCMP_VM

Check whether the processes share the same address space. The arguments idx1 and idx2 are ignored. See the discussion of the CLONE_VM flag in clone(2).

KCMP_EPOLL_TFD (since Linux 4.13)

Check whether the file descriptor idx1 of the process pid1 is present in the epoll(7) instance described by idx2 of the process pid2. The argument idx2 is a pointer to a structure where the target file is described. This structure has the form:

```
struct kcmp_epoll_slot {

    __u32 efd;

    __u32 tfd;

    __u64 toff;
};
```

Within this structure, efd is an epoll file descriptor returned from epoll_create(2), tfd is a target file descriptor number, and toff is a target file offset counted from zero. Several different targets may be registered with the same file descriptor number and setting a specific offset helps to investigate each of them.

Note the kcmp() is not protected against false positives which may occur if the processes are currently running. One should stop the processes by sending SIGSTOP (see signal(7)) prior to inspection with this system call to obtain meaningful results.

## RETURN VALUE
The return value of a successful call to kcmp() is simply the result of arithmetic comparison of kernel pointers (when the kernel compares resources, it uses their memory addresses).

The easiest way to explain is to consider an example. Suppose that v1 and v2 are the addresses of appropriate resources, then the return value is one of the following:

0

v1 is equal to v2; in other words, the two processes share the resource.

1

v1 is less than v2.

2

v1 is greater than v2.

3

v1 is not equal to v2, but ordering information is unavailable.

On error, -1 is returned, and errno is set to indicate the error.

kcmp() was designed to return values suitable for sorting. This is particularly handy if one needs to compare a large number of file descriptors.

## ERRORS
EBADF

type is KCMP_FILE and fd1 or fd2 is not an open file descriptor.

EFAULT

The epoll slot addressed by idx2 is outside of the user's address space.

EINVAL

type is invalid.

ENOENT

The target file is not present in epoll(7) instance.

EPERM

Insufficient permission to inspect process resources. The CAP_SYS_PTRACE capability is required to inspect processes that you do not own. Other ptrace limitations may also apply, such as CONFIG_SECURITY_YAMA, which, when /proc/sys/kernel/yama/ptrace_scope is 2, limits kcmp() to child processes; see ptrace(2).

ESRCH

Process pid1 or pid2 does not exist.

## STANDARDS
Linux.

## HISTORY
Linux 3.5.

Before Linux 5.12, this system call is available only if the kernel is configured with CONFIG_CHECKPOINT_RESTORE, since the original purpose of the system call was for the checkpoint/restore in user space (CRIU) feature. (The alternative to this system call would have been to expose suitable process information via the proc(5) filesystem; this was deemed to be unsuitable for security reasons.) Since Linux 5.12, this system call is also available if the kernel is configured with CONFIG_KCMP.

## NOTES
See clone(2) for some background information on the shared resources referred to on this page.

## EXAMPLES
The program below uses kcmp() to test whether pairs of file descriptors refer to the same open file description. The program tests different cases for the file descriptor pairs, as described in the program output. An example run of the program is as follows:

```
$ ./a.out
Parent PID is 1144
Parent opened file on FD 3
PID of child of fork() is 1145
	Compare duplicate FDs from different processes:
		kcmp(1145, 1144, KCMP_FILE, 3, 3) ==> same
Child opened file on FD 4
	Compare FDs from distinct open()s in same process:
		kcmp(1145, 1145, KCMP_FILE, 3, 4) ==> different
Child duplicated FD 3 to create FD 5
	Compare duplicated FDs in same process:
		kcmp(1145, 1145, KCMP_FILE, 3, 5) ==> same
```

### Program source

```
#define _GNU_SOURCE
#include <err.h>
#include <fcntl.h>
#include <linux/kcmp.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>
static int
kcmp(pid_t pid1, pid_t pid2, int type,

     unsigned long idx1, unsigned long idx2)
{

    return syscall(SYS_kcmp, pid1, pid2, type, idx1, idx2);
}
static void
test_kcmp(char *msg, pid_t pid1, pid_t pid2, int fd_a, int fd_b)
{

    printf("\t%s\n", msg);

    printf("\t\tkcmp(%jd, %jd, KCMP_FILE, %d, %d) ==> %s\n",

           (intmax_t) pid1, (intmax_t) pid2, fd_a, fd_b,

           (kcmp(pid1, pid2, KCMP_FILE, fd_a, fd_b) == 0) ?

                        "same" : "different");
}
int
main(void)
{

    int                fd1, fd2, fd3;

    static const char  pathname[] = "/tmp/kcmp.test";

    fd1 = open(pathname, O_CREAT | O_RDWR, 0600);

    if (fd1 == -1)

        err(EXIT_FAILURE, "open");

    printf("Parent PID is %jd\n", (intmax_t) getpid());

    printf("Parent opened file on FD %d\n\n", fd1);

    switch (fork()) {

    case -1:

        err(EXIT_FAILURE, "fork");

    case 0:

        printf("PID of child of fork() is %jd\n", (intmax_t) getpid());

        test_kcmp("Compare duplicate FDs from different processes:",

                  getpid(), getppid(), fd1, fd1);

        fd2 = open(pathname, O_CREAT | O_RDWR, 0600);

        if (fd2 == -1)

            err(EXIT_FAILURE, "open");

        printf("Child opened file on FD %d\n", fd2);

        test_kcmp("Compare FDs from distinct open()s in same process:",

                  getpid(), getpid(), fd1, fd2);

        fd3 = dup(fd1);

        if (fd3 == -1)

            err(EXIT_FAILURE, "dup");

        printf("Child duplicated FD %d to create FD %d\n", fd1, fd3);

        test_kcmp("Compare duplicated FDs in same process:",

                  getpid(), getpid(), fd1, fd3);

        break;

    default:

        wait(NULL);

    }

    exit(EXIT_SUCCESS);
}
```

## SEE ALSO
clone(2), unshare(2)