diff options
-rw-r--r-- | configure.ac | 9 | ||||
-rw-r--r-- | include/pathnames.h | 1 | ||||
-rw-r--r-- | include/sysfs.h | 2 | ||||
-rw-r--r-- | lib/sysfs.c | 153 | ||||
-rw-r--r-- | libblkid/src/devno.c | 130 | ||||
-rw-r--r-- | misc-utils/.gitignore | 1 | ||||
-rw-r--r-- | misc-utils/lslocks.c | 2 | ||||
-rw-r--r-- | sys-utils/.gitignore | 1 | ||||
-rw-r--r-- | sys-utils/Makefile.am | 13 | ||||
-rw-r--r-- | sys-utils/eject.1 | 154 | ||||
-rw-r--r-- | sys-utils/eject.c | 1082 | ||||
-rw-r--r-- | tests/commands.sh.in | 1 | ||||
-rw-r--r-- | tests/expected/eject/umount | 0 | ||||
-rw-r--r-- | tests/expected/eject/umount-by-disk | 1 | ||||
-rw-r--r-- | tests/expected/eject/umount-by-disk-mounted | 1 | ||||
-rw-r--r-- | tests/expected/eject/umount-by-disk-mounted-partition | 2 | ||||
-rw-r--r-- | tests/expected/eject/umount-by-partition | 2 | ||||
-rw-r--r-- | tests/expected/eject/umount-by-partition-mounted | 2 | ||||
-rwxr-xr-x | tests/ts/eject/umount | 111 |
19 files changed, 1535 insertions, 133 deletions
diff --git a/configure.ac b/configure.ac index 3085965de..8ed2e0b78 100644 --- a/configure.ac +++ b/configure.ac @@ -859,6 +859,15 @@ ruman1dir='${mandir}/ru/man1' AC_SUBST([ruman1dir]) +AC_ARG_ENABLE([eject], + AS_HELP_STRING([--disable-eject], [do not build eject]), + [], enable_eject=yes +) +UL_BUILD_INIT([eject]) +UL_REQUIRES_LINUX([eject]) +AM_CONDITIONAL(BUILD_EJECT, test "x$build_eject" = xyes) + + AC_ARG_ENABLE([agetty], AS_HELP_STRING([--disable-agetty], [do not build agetty]), [], enable_agetty=yes diff --git a/include/pathnames.h b/include/pathnames.h index 299d922eb..1757044f5 100644 --- a/include/pathnames.h +++ b/include/pathnames.h @@ -81,6 +81,7 @@ #define _PATH_PROC_DEVICES "/proc/devices" #define _PATH_PROC_MOUNTINFO "/proc/self/mountinfo" #define _PATH_PROC_LOCKS "/proc/locks" +#define _PATH_PROC_CDROMINFO "/proc/sys/dev/cdrom/info" #define _PATH_SYS_BLOCK "/sys/block" #define _PATH_SYS_DEVBLOCK "/sys/dev/block" diff --git a/include/sysfs.h b/include/sysfs.h index affd2bb76..8604aca5e 100644 --- a/include/sysfs.h +++ b/include/sysfs.h @@ -62,4 +62,6 @@ extern char *sysfs_get_slave(struct sysfs_cxt *cxt); extern int sysfs_is_partition_dirent(DIR *dir, struct dirent *d, const char *parent_name); +extern int sysfs_devno_to_wholedisk(dev_t dev, char *diskname, + size_t len, dev_t *diskdevno); #endif /* UTIL_LINUX_SYSFS_H */ diff --git a/lib/sysfs.c b/lib/sysfs.c index a57c0a6ba..3b5d045c4 100644 --- a/lib/sysfs.c +++ b/lib/sysfs.c @@ -2,6 +2,8 @@ * Copyright (C) 2011 Karel Zak <kzak@redhat.com> */ +#include <ctype.h> + #include "c.h" #include "at.h" #include "pathnames.h" @@ -285,8 +287,26 @@ int sysfs_is_partition_dirent(DIR *dir, struct dirent *d, const char *parent_nam d->d_type != DT_LNK) return 0; #endif - if (parent_name && strncmp(parent_name, d->d_name, strlen(parent_name))) - return 0; + if (parent_name) { + const char *p = parent_name; + size_t len; + + /* /dev/sda --> "sda" */ + if (*parent_name == '/') { + p = strrchr(parent_name, '/'); + if (!p) + return 0; + p++; + } + + len = strlen(p); + if (strlen(d->d_name) <= len) + return 0; + + /* partitions subdir name is "<parent>[:digit:]" */ + return strncmp(p, d->d_name, len) == 0 + && isdigit(*(d->d_name + len)); + } /* Cannot use /partition file, not supported on old sysfs */ snprintf(path, sizeof(path), "%s/start", d->d_name); @@ -439,6 +459,135 @@ char *sysfs_get_devname(struct sysfs_cxt *cxt, char *buf, size_t bufsiz) return buf; } +/* returns basename and keeps dirname in the @path */ +static char *stripoff_last_component(char *path) +{ + char *p = strrchr(path, '/'); + + if (!p) + return NULL; + *p = '\0'; + return ++p; +} + +static int get_dm_wholedisk(struct sysfs_cxt *cxt, char *diskname, + size_t len, dev_t *diskdevno) +{ + int rc = 0; + char *name; + + /* Note, sysfs_get_slave() returns the first slave only, + * if there is more slaves, then return NULL + */ + name = sysfs_get_slave(cxt); + if (!name) + return -1; + + if (diskname && len) { + strncpy(diskname, name, len); + diskname[len - 1] = '\0'; + } + + if (diskdevno) { + *diskdevno = sysfs_devname_to_devno(name, NULL); + if (!*diskdevno) + rc = -1; + } + + free(name); + return rc; +} + +int sysfs_devno_to_wholedisk(dev_t dev, char *diskname, + size_t len, dev_t *diskdevno) +{ + struct sysfs_cxt cxt; + int is_part = 0; + + if (!dev || sysfs_init(&cxt, dev, NULL) != 0) + return -1; + + is_part = sysfs_has_attribute(&cxt, "partition"); + if (!is_part) { + /* + * Extra case for partitions mapped by device-mapper. + * + * All regualar partitions (added by BLKPG ioctl or kernel PT + * parser) have the /sys/.../partition file. The partitions + * mapped by DM don't have such file, but they have "part" + * prefix in DM UUID. + */ + char *uuid = sysfs_strdup(&cxt, "dm/uuid"); + char *tmp = uuid; + char *prefix = uuid ? strsep(&tmp, "-") : NULL; + + if (prefix && strncasecmp(prefix, "part", 4) == 0) + is_part = 1; + free(uuid); + + if (is_part && + get_dm_wholedisk(&cxt, diskname, len, diskdevno) == 0) + /* + * partitioned device, mapped by DM + */ + goto done; + + is_part = 0; + } + + if (!is_part) { + /* + * unpartitioned device + */ + if (diskname && len) { + if (!sysfs_get_devname(&cxt, diskname, len)) + goto err; + } + if (diskdevno) + *diskdevno = dev; + + } else { + /* + * partitioned device + * - readlink /sys/dev/block/8:1 = ../../block/sda/sda1 + * - dirname ../../block/sda/sda1 = ../../block/sda + * - basename ../../block/sda = sda + */ + char linkpath[PATH_MAX]; + char *name; + int linklen; + + linklen = sysfs_readlink(&cxt, NULL, + linkpath, sizeof(linkpath) - 1); + if (linklen < 0) + goto err; + linkpath[linklen] = '\0'; + + stripoff_last_component(linkpath); /* dirname */ + name = stripoff_last_component(linkpath); /* basename */ + if (!name) + goto err; + + if (diskname && len) { + strncpy(diskname, name, len); + diskname[len - 1] = '\0'; + } + + if (diskdevno) { + *diskdevno = sysfs_devname_to_devno(name, NULL); + if (!*diskdevno) + goto err; + } + } + +done: + sysfs_deinit(&cxt); + return 0; +err: + sysfs_deinit(&cxt); + return -1; +} + #ifdef TEST_PROGRAM_SYSFS #include <errno.h> #include <err.h> diff --git a/libblkid/src/devno.c b/libblkid/src/devno.c index 59edfd85c..2996343a0 100644 --- a/libblkid/src/devno.c +++ b/libblkid/src/devno.c @@ -197,16 +197,7 @@ static const char *devdirs[] = { "/devices", "/devfs", "/dev", NULL }; * @short_description: mix of various utils for low-level and high-level API */ -/* returns basename and keeps dirname in the @path */ -static char *stripoff_last_component(char *path) -{ - char *p = strrchr(path, '/'); - if (!p) - return NULL; - *p = '\0'; - return ++p; -} static char *scandev_devno_to_devpath(dev_t devno) { @@ -279,33 +270,6 @@ char *blkid_devno_to_devname(dev_t devno) return path; } -static int get_dm_wholedisk(struct sysfs_cxt *cxt, char *diskname, - size_t len, dev_t *diskdevno) -{ - int rc = 0; - char *name; - - /* Note, sysfs_get_slave() returns the first slave only, - * if there is more slaves, then return NULL - */ - name = sysfs_get_slave(cxt); - if (!name) - return -1; - - if (diskname && len) { - strncpy(diskname, name, len); - diskname[len - 1] = '\0'; - } - - if (diskdevno) { - *diskdevno = sysfs_devname_to_devno(name, NULL); - if (!*diskdevno) - rc = -1; - } - - free(name); - return rc; -} /** * blkid_devno_to_wholedisk: @@ -346,99 +310,7 @@ static int get_dm_wholedisk(struct sysfs_cxt *cxt, char *diskname, int blkid_devno_to_wholedisk(dev_t dev, char *diskname, size_t len, dev_t *diskdevno) { - struct sysfs_cxt cxt = UL_SYSFSCXT_EMPTY; - int is_part = 0; - - if (!dev || sysfs_init(&cxt, dev, NULL) != 0) - return -1; - - is_part = sysfs_has_attribute(&cxt, "partition"); - if (!is_part) { - /* - * Extra case for partitions mapped by device-mapper. - * - * All regualar partitions (added by BLKPG ioctl or kernel PT - * parser) have the /sys/.../partition file. The partitions - * mapped by DM don't have such file, but they have "part" - * prefix in DM UUID. - */ - char *uuid = sysfs_strdup(&cxt, "dm/uuid"); - char *tmp = uuid; - char *prefix = uuid ? strsep(&tmp, "-") : NULL; - - if (prefix && strncasecmp(prefix, "part", 4) == 0) - is_part = 1; - free(uuid); - - if (is_part && - get_dm_wholedisk(&cxt, diskname, len, diskdevno) == 0) - /* - * partitioned device, mapped by DM - */ - goto done; - - is_part = 0; - } - - if (!is_part) { - /* - * unpartitioned device - */ - if (diskname && len) { - if (!sysfs_get_devname(&cxt, diskname, len)) - goto err; - } - if (diskdevno) - *diskdevno = dev; - - } else { - /* - * partitioned device - * - readlink /sys/dev/block/8:1 = ../../block/sda/sda1 - * - dirname ../../block/sda/sda1 = ../../block/sda - * - basename ../../block/sda = sda - */ - char linkpath[PATH_MAX]; - char *name; - int linklen; - - linklen = sysfs_readlink(&cxt, NULL, - linkpath, sizeof(linkpath) - 1); - if (linklen < 0) - goto err; - linkpath[linklen] = '\0'; - - stripoff_last_component(linkpath); /* dirname */ - name = stripoff_last_component(linkpath); /* basename */ - if (!name) - goto err; - - if (diskname && len) { - strncpy(diskname, name, len); - diskname[len - 1] = '\0'; - } - - if (diskdevno) { - *diskdevno = sysfs_devname_to_devno(name, NULL); - if (!*diskdevno) - goto err; - } - } - -done: - sysfs_deinit(&cxt); - - DBG(DEBUG_DEVNO, - printf("found entire diskname for devno 0x%04llx %s\n", - (long long) dev, diskname ? diskname : "")); - return 0; -err: - sysfs_deinit(&cxt); - - DBG(DEBUG_DEVNO, - printf("failed to convert 0x%04llx to wholedisk name, errno=%d\n", - (long long) dev, errno)); - return -1; + return sysfs_devno_to_wholedisk( dev, diskname, len, diskdevno); } /* diff --git a/misc-utils/.gitignore b/misc-utils/.gitignore index bde3ab8d9..927af2326 100644 --- a/misc-utils/.gitignore +++ b/misc-utils/.gitignore @@ -18,4 +18,3 @@ wipefs findmnt lsblk lslocks - diff --git a/misc-utils/lslocks.c b/misc-utils/lslocks.c index 0abc2a4bf..0631f684a 100644 --- a/misc-utils/lslocks.c +++ b/misc-utils/lslocks.c @@ -478,7 +478,7 @@ static void __attribute__ ((__noreturn__)) usage(FILE * out) fprintf(out, _(" %s [options]\n"), program_invocation_short_name); - fputs(_("\nGeneral Options:\n"), out); + fputs(USAGE_OPTIONS, out); fputs(_(" -p, --pid <pid> process id\n" " -o, --output <list> define which output columns to use\n" " -n, --noheadings don't print headings\n" diff --git a/sys-utils/.gitignore b/sys-utils/.gitignore index 38e8874b3..a5bf223c1 100644 --- a/sys-utils/.gitignore +++ b/sys-utils/.gitignore @@ -2,6 +2,7 @@ arch ctrlaltdel cytune dmesg +eject fallocate flock fsfreeze diff --git a/sys-utils/Makefile.am b/sys-utils/Makefile.am index 83f38cf90..828c48d9b 100644 --- a/sys-utils/Makefile.am +++ b/sys-utils/Makefile.am @@ -43,6 +43,19 @@ dist_man_MANS += \ endif # LINUX +if BUILD_EJECT +usrbin_exec_PROGRAMS += eject +eject_SOURCES = \ + eject.c \ + $(top_srcdir)/lib/strutils.c \ + $(top_srcdir)/lib/sysfs.c \ + $(top_srcdir)/lib/at.c +eject_LDADD = $(ul_libmount_la) +eject_CFLAGS = $(AM_CFLAGS) -I$(ul_libmount_incdir) +dist_man_MANS += eject.1 +endif + + if BUILD_LOSETUP sbin_PROGRAMS += losetup dist_man_MANS += losetup.8 diff --git a/sys-utils/eject.1 b/sys-utils/eject.1 new file mode 100644 index 000000000..8b1b11bc1 --- /dev/null +++ b/sys-utils/eject.1 @@ -0,0 +1,154 @@ +.\" Copyright (C) 1994-2005 Jeff Tranter (tranter@pobox.com) +.\" Copyright (C) 2012 Karel Zak <kzak@redhat.com> +.\" +.\" It may be distributed under the GNU Public License, version 2, or +.\" any higher version. See section COPYING of the GNU Public license +.\" for conditions under which this file may be redistributed. +.TH EJECT 1 "April 2012" "Linux" "User Commands" +.SH NAME +eject \- eject removable media +.SH SYNOPSIS +.B eject +.RB [ options ] +.IR device | mountpoint +.SH DESCRIPTION +.B Eject +allows removable media (typically a CD-ROM, floppy disk, tape, JAZ, ZIP or USB +disk) to be ejected under software control. The command can also control some +multi-disc CD-ROM changers, the auto-eject feature supported by some devices, +and close the disc tray of some CD-ROM drives. + +The device corresponding to \fIdevice\fP or \fImountpoint\fP is ejected. If no +name is specified, the default name /dev/cdrom is used. + +There are four different methods of ejecting, depending on whether the device +is a CD-ROM, SCSI device, removable floppy, or tape. By default eject tries all +four methods in order until it succeeds. + +If device partition is specified, the whole-disk device is used. If the device +or a device partition is currently mounted, it is unmounted before ejecting. + +.SH OPTIONS +.IP "\fB\-a, \-\-auto \fIon|off\fP" +This option controls the auto-eject mode, supported by some devices. When +enabled, the drive automatically ejects when the device is closed. +.IP "\fB\-c, \-\-changerslot \fIslot\fP" +With this option a CD slot can be selected from an ATAPI/IDE CD-ROM changer. +Linux 2.0 or higher is required to use this feature. The CD-ROM drive can not +be in use (mounted data CD or playing a music CD) for a change request to work. +Please also note that the first slot of the changer is referred to as 0, not 1. +.IP "\fB\-d, \-\-default\fP" +List the default device name. +.IP "\fB\-f, \-\-floppy\fP" +This option specifies that the drive should be ejected using a removable floppy +disk eject command. +.IP "\fB\-F, \-\-force\fP" +Force eject, don't check device type. +.IP "\fB\-h, \-\-help\fP" +Print a help text and exit. +.IP "\fB\-i, \-\-manualeject \fIon|off\fP" +This option controls locking of the hardware eject button. When enabled, the +drive will not be ejected when the button is pressed. This is useful when you +are carrying a laptop in a bag or case and don't want it to eject if the button +is inadvertently pressed. +.IP "\fB\-p, \-\-proc\fP" +This option allow you to use /proc/mounts instead /etc/mtab. It also passes the +\-n option to umount(1). +.IP "\fB\-q, \-\-tape\fP" +This option specifies that the drive should be ejected using a tape drive +offline command. +.IP "\fB\-m, \-\-no-unmount\fP" +This option allows eject to work with device drivers which automatically mount +removable media and therefore must be always mount()ed. The option tells eject +to not try to unmount the given device, even if it is mounted according to +/etc/mtab or /proc/mounts. +.IP "\fB\-n, \-\-noop\fP" +With this option the selected device is displayed but no action is performed. +.IP "\fB\-t, \-\-trayclose\fP" +With this option the drive is given a CD-ROM tray close command. Not all +devices support this command. +.IP "\fB\-T, \-\-traytoggle\fP" +With this option the drive is given a CD-ROM tray close command if it's opened, +and a CD-ROM tray eject command if it's closed. Not all devices support this +command, because it uses the above CD-ROM tray close command. +.IP "\fB\-r, \-\-cdrom\fP" +This option specifies that the drive should be ejected using a CDROM eject +command. +.IP "\fB\-s, \-\-scsi\fP" +This option specifies that the drive should be ejected using SCSI commands. + +.IP "\fB\-v, \-\-verbose\fP" +Run in verbose mode; more information is displayed about what the command is +doing. +.IP "\fB\-V, \-\-version\fP" +Display program version and exit. +.IP "\fB\-x, \-\-cdspeed \fI<speed>\fP" +With this option the drive is given a CD-ROM select speed command. The speed +argument is a number indicating the desired speed (e.g. 8 for 8X speed), or 0 +for maximum data rate. Not all devices support this command and you can only +specify speeds that the drive is capable of. Every time the media is changed +this option is cleared. This option can be used alone, or with the \-t and \-c +options. +.IP "\fB\-X, \-\-listspeed\fP" +With this option the CD-ROM drive will be probed to detect the available +speeds. The output is a list of speeds which can be used as an argument of the +\-x option. This only works with Linux 2.6.13 or higher, on previous versions +solely the maximum speed will be reported. Also note that some drive may not +correctly report the speed and therefore this option does not work with them. + +.SH EXIT STATUS +Returns 0 if operation was successful, 1 if operation failed or command syntax +was not valid. + +.SH NOTES +.B Eject +only works with devices that support one or more of the four methods of +ejecting. This includes most CD-ROM drives (IDE, SCSI, and proprietary), some +SCSI tape drives, JAZ drives, ZIP drives (parallel port, SCSI, and IDE +versions), and LS120 removable floppies. Users have also reported success with +floppy drives on Sun SPARC and Apple Macintosh systems. If +.B eject +does not work, it is most likely a limitation of the kernel driver for the +device and not the +.B eject +program itself. + +The \-r, \-s, \-f, and \-q options allow controlling which methods are used to +eject. More than one method can be specified. If none of these options are +specified, it tries all four (this works fine in most cases). + +.B Eject +may not always be able to determine if the device is mounted (e.g. if it has +several names). If the device name is a symbolic link, +.B eject +will follow the link and use the device that it points to. + +If +.B eject +determines that the device can have multiple partitions, it will attempt to +unmount all mounted partitions of the device before ejecting. If an unmount +fails, the program will not attempt to eject the media. + +You can eject an audio CD. Some CD-ROM drives will refuse to open the tray if +the drive is empty. Some devices do not support the tray close command. + +If the auto-eject feature is enabled, then the drive will always be ejected +after running this command. Not all Linux kernel CD-ROM drivers support the +auto-eject mode. There is no way to find out the state of the auto-eject mode. + +You need appropriate privileges to access the device files. Running as root is +required to eject some devices (e.g. SCSI devices). + +.SH AUTHORS +.nf +Jeff Tranter (tranter@pobox.com) - original author +Karel Zak (kzak@redhat.com), Michal Luscon (mluscon@redhat.com) - util-linux version +.fi +.SH SEE ALSO +.BR lsblk (8), +.BR findmnt (8), +.BR mount (8), +.BR umount (8) +.SH AVAILABILITY +The lsblk command is part of the util-linux package and is available from +ftp://ftp.kernel.org/pub/linux/utils/util-linux/. diff --git a/sys-utils/eject.c b/sys-utils/eject.c new file mode 100644 index 000000000..2d8b0cbcc --- /dev/null +++ b/sys-utils/eject.c @@ -0,0 +1,1082 @@ +/* + * Copyright (C) 1994-2005 Jeff Tranter (tranter@pobox.com) + * Copyright (C) 2012 Karel Zak <kzak@redhat.com> + * Copyright (C) Michal Luscon <mluscon@redhat.com> + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include <unistd.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <fcntl.h> +#include <limits.h> +#include <err.h> +#include <stdarg.h> + +#include <getopt.h> +#include <errno.h> +#include <regex.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/ioctl.h> +#include <sys/wait.h> +#include <sys/mtio.h> +#include <linux/cdrom.h> +#include <linux/fd.h> +#include <sys/mount.h> +#include <scsi/scsi.h> +#include <scsi/sg.h> +#include <scsi/scsi_ioctl.h> +#include <sys/time.h> + +#include <libmount.h> + +#include "c.h" +#include "nls.h" +#include "strutils.h" +#include "xalloc.h" +#include "pathnames.h" +#include "sysfs.h" + +#define EJECT_DEFAULT_DEVICE "/dev/cdrom" + + +/* Used by the toggle_tray() function. If ejecting the tray takes this + * time or less, the tray was probably already ejected, so we close it + * again. + */ +#define TRAY_WAS_ALREADY_OPEN_USECS 200000 /* about 0.2 seconds */ + +/* eject(1) is able to eject only 'removable' devices (attribute in /sys) + * _or_ devices connected by hotplug subsystem. + */ +static const char *hotplug_subsystems[] = { + "usb", + "ieee1394", + "pcmcia", + "mmc", + "ccw" +}; + +/* Global Variables */ +static int a_option; /* command flags and arguments */ +static int c_option; +static int d_option; +static int f_option; +static int F_option; +static int n_option; +static int q_option; +static int r_option; +static int s_option; +static int t_option; +static int T_option; +static int X_option; +static int v_option; +static int x_option; +static int p_option; +static int m_option; +static int i_option; +static int a_arg; +static int i_arg; +static long int c_arg; +static long int x_arg; + +struct libmnt_table *mtab; +struct libmnt_cache *cache; + +static void vinfo(const char *fmt, va_list va) +{ + fprintf(stdout, "%s: ", program_invocation_short_name); + vprintf(fmt, va); + fputc('\n', stdout); +} + +static inline void verbose(const char *fmt, ...) +{ + va_list va; + + if (!v_option) + return; + + va_start(va, fmt); + vinfo(fmt, va); + va_end(va); +} + +static inline void info(const char *fmt, ...) +{ + va_list va; + va_start(va, fmt); + vinfo(fmt, va); + va_end(va); +} + +static void __attribute__ ((__noreturn__)) usage(FILE * out) +{ + fputs(USAGE_HEADER, out); + + fprintf(out, + _(" %s [options] [<device>|<mountpoint>]\n"), program_invocation_short_name); + + fputs(USAGE_OPTIONS, out); + fputs(_(" -a, --auto <on|off> turn auto-eject feature on or off\n" + " -c, --changerslot <slot> switch discs on a CD-ROM changer\n" + " -d, --default display default device\n" + " -f, --floppy eject floppy\n" + " -F, --force don't care about device type\n" + " -i, --manualeject <on|off> toggle manual eject protection on/off\n" + " -m, --no-unmount do not unmount device even if it is mounted\n" + " -n, --noop don't eject, just show device found\n" + " -p, --proc use /proc/mounts instead of /etc/mtab\n" + " -q, --tape eject tape\n" + " -r, --cdrom eject CD-ROM\n" + " -s, --scsi eject SCSI device\n" + " -t, --trayclose close tray\n" + " -T, --traytoggle toggle tray\n" + " -v, --verbose enable verbose output\n" + " -x, --cdspeed <speed> set CD-ROM max speed\n" + " -X, --listspeed list CD-ROM available speeds\n"), + out); + + fputs(USAGE_SEPARATOR, out); + fputs(USAGE_HELP, out); + fputs(USAGE_VERSION, out); + + fputs(_("\nBy default tries -r, -s, -f, and -q in order until success.\n"), out); + fprintf(out, USAGE_MAN_TAIL("eject(1)")); + + exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS); +} + + +/* Handle command line options. */ +static void parse_args(int argc, char **argv, char **device) +{ + static const struct option long_opts[] = + { + {"auto", required_argument, NULL, 'a'}, + {"cdrom", no_argument, NULL, 'r'}, + {"cdspeed", required_argument, NULL, 'x'}, + {"changerslot", required_argument, NULL, 'c'}, + {"default", no_argument, NULL, 'd'}, + {"floppy", no_argument, NULL, 'f'}, + {"force", no_argument, NULL, 'F'}, + {"help", no_argument, NULL, 'h'}, + {"listspeed", no_argument, NULL, 'X'}, + {"manualeject", required_argument, NULL, 'i'}, + {"noop", no_argument, NULL, 'n'}, + {"no-unmount", no_argument, NULL, 'm'}, + {"proc", no_argument, NULL, 'p'}, + {"scsi", no_argument, NULL, 's'}, + {"tape", no_argument, NULL, 'q'}, + {"trayclose", no_argument, NULL, 't'}, + {"traytoggle", no_argument, NULL, 'T'}, + {"verbose", no_argument, NULL, 'v'}, + {"version", no_argument, NULL, 'V'}, + {0, 0, 0, 0} + }; + int c; + + while ((c = getopt_long(argc, argv, + "a:c:i:x:dfFhnqrstTXvVpm", long_opts, NULL)) != -1) { + switch (c) { + case 'a': + a_option = 1; + if (!strcmp(optarg, "0") || !strcmp(optarg, "off")) + a_arg = 0; + else if (!strcmp(optarg, "1") || !strcmp(optarg, "on")) + a_arg = 1; + else + errx(EXIT_FAILURE, _("invalid argument to --auto/-a option")); + break; + case 'c': + c_option = 1; + c_arg = strtoul_or_err(optarg, _("invalid argument to --changerslot/-c option")); + break; + case 'x': + x_option = 1; + x_arg = strtoul_or_err(optarg, _("invalid argument to --cdspeed/-x option")); + break; + case 'd': + d_option = 1; + break; + case 'f': + f_option = 1; + break; + case 'F': + F_option = 1; + break; + case 'h': + usage(stdout); + break; + case 'i': + i_option = 1; + if (!strcmp(optarg, "0") || !strcmp(optarg, "off")) + i_arg = 0; + else if (!strcmp(optarg, "1") || !strcmp(optarg, "on")) + i_arg = 1; + else + errx(EXIT_FAILURE, _("invalid argument to --manualeject/-i option")); + break; + case 'm': + m_option = 1; + break; + case 'n': + n_option = 1; + break; + case 'p': + p_option = 1; + break; + case 'q': + q_option = 1; + break; + case 'r': + r_option = 1; + break; + case 's': + s_option = 1; + break; + case 't': + t_option = 1; + break; + case 'T': + T_option = 1; + break; + case 'X': + X_option = 1; + break; + case 'v': + v_option = 1; + break; + case 'V': + printf(UTIL_LINUX_VERSION); + exit(EXIT_SUCCESS); + break; + default: + case '?': + usage(stderr); + break; + } + } + + /* check for a single additional argument */ + if ((argc - optind) > 1) + errx(EXIT_FAILURE, _("too many arguments")); + + if ((argc - optind) == 1) + *device = xstrdup(argv[optind]); +} + +/* + * Given name, such as foo, see if any of the following exist: + * + * foo (if foo starts with '.' or '/') + * /dev/foo + * + * If found, return the full path. If not found, return 0. + * Returns pointer to dynamically allocated string. + */ +static char *find_device(const char *name) +{ + if (!name) + return NULL; + + if ((*name == '.' || *name == '/') && access(name, F_OK) == 0) + return xstrdup(name); + else { + char buf[PATH_MAX]; + + snprintf(buf, sizeof(buf), "/dev/%s", name); + if (access(buf, F_OK) == 0) + return xstrdup(buf); + } + + return NULL; +} + +/* Set or clear auto-eject mode. */ +static void auto_eject(int fd, int on) +{ + int status = -1; + +#if defined(CDROM_SET_OPTIONS) && defined(CDROM_CLEAR_OPTIONS) + if (on) + status = ioctl(fd, CDROM_SET_OPTIONS, CDO_AUTO_EJECT); + else + status = ioctl(fd, CDROM_CLEAR_OPTIONS, CDO_AUTO_EJECT); +#else + errno = ENOSYS; +#endif + if (status < 0) + err(EXIT_FAILURE,_("CD-ROM auto-eject command failed")); +} + +/* + * Stops CDROM from opening on manual eject pressing the button. + * This can be useful when you carry your laptop + * in your bag while it's on and no CD inserted in it's drive. + * Implemented as found in Documentation/ioctl/cdrom.txt + * + * TODO: Maybe we should check this also: + * EDRIVE_CANT_DO_THIS Door lock function not supported. + * EBUSY Attempt to unlock when multiple users + * have the drive open and not CAP_SYS_ADMIN + */ +static void manual_eject(int fd, int on) +{ + if (ioctl(fd, CDROM_LOCKDOOR, on) < 0) + err(EXIT_FAILURE, _("CD-ROM lock door command failed")); + + if (on) + info(_("CD-Drive may NOT be ejected with device button")); + else + info(_("CD-Drive may be ejected with device button")); +} + +/* + * Changer select. CDROM_SELECT_DISC is preferred, older kernels used + * CDROMLOADFROMSLOT. + */ +static void changer_select(int fd, int slot) +{ +#ifdef CDROM_SELECT_DISC + if (ioctl(fd, CDROM_SELECT_DISC, slot) < 0) + err(EXIT_FAILURE, _("CD-ROM select disc command failed")); + +#elif defined CDROMLOADFROMSLOT + if (ioctl(fd, CDROMLOADFROMSLOT, slot) != 0) + err(EXIT_FAILURE, _("CD-ROM load from slot command failed")); +#else + warnx(_("IDE/ATAPI CD-ROM changer not supported by this kernel\n") ); +#endif +} + +/* + * Close tray. Not supported by older kernels. + */ +static void close_tray(int fd) +{ + int status; + +#if defined(CDROMCLOSETRAY) || defined(CDIOCCLOSE) +#if defined(CDROMCLOSETRAY) + status = ioctl(fd, CDROMCLOSETRAY); +#elif defined(CDIOCCLOSE) + status = ioctl(fd, CDIOCCLOSE); +#endif + if (status != 0) + err(EXIT_FAILURE, _("CD-ROM tray close command failed")); +#else + warnx(_("CD-ROM tray close command not supported by this kernel\n")); +#endif +} + +/* + * Toggle tray. + * + * Written by Benjamin Schwenk <benjaminschwenk@yahoo.de> and + * Sybren Stuvel <sybren@thirdtower.com> + * + * Not supported by older kernels because it might use + * CloseTray(). + * + */ +static void toggle_tray(int fd) +{ + struct timeval time_start, time_stop; + int time_elapsed; + +#ifdef CDROMCLOSETRAY + /* Try to open the CDROM tray and measure the time therefor + * needed. In my experience the function needs less than 0.05 + * seconds if the tray was already open, and at least 1.5 seconds + * if it was closed. */ + gettimeofday(&time_start, NULL); + + /* Send the CDROMEJECT command to the device. */ + if (ioctl(fd, CDROMEJECT, 0) < 0) + err(EXIT_FAILURE, _("CD-ROM eject command failed")); + + /* Get the second timestamp, to measure the time needed to open + * the tray. */ + gettimeofday(&time_stop, NULL); + + time_elapsed = (time_stop.tv_sec * 1000000 + time_stop.tv_usec) - + (time_start.tv_sec * 1000000 + time_start.tv_usec); + + /* If the tray "opened" too fast, we can be nearly sure, that it + * was already open. In this case, close it now. Else the tray was + * closed before. This would mean that we are done. */ + if (time_elapsed < TRAY_WAS_ALREADY_OPEN_USECS) + close_tray(fd); +#else + warnx(_("CD-ROM tray toggle command not supported by this kernel")); +#endif + +} + +/* + * Select Speed of CD-ROM drive. + * Thanks to Roland Krivanek (krivanek@fmph.uniba.sk) + * http://dmpc.dbp.fmph.uniba.sk/~krivanek/cdrom_speed/ + */ +static void select_speed(int fd, int speed) +{ +#ifdef CDROM_SELECT_SPEED + if (ioctl(fd, CDROM_SELECT_SPEED, speed) != 0) + err(EXIT_FAILURE, _("CD-ROM select speed command failed")); +#else + warnx(_("CD-ROM select speed command not supported by this kernel")); +#endif +} + +/* + * Read Speed of CD-ROM drive. From Linux 2.6.13, the current speed + * is correctly reported + */ +static int read_speed(const char *devname) +{ + int drive_number = -1; + char *name; + FILE *f; + + f = fopen(_PATH_PROC_CDROMINFO, "r"); + if (!f) + err(EXIT_FAILURE, _("%s: open failed"), _PATH_PROC_CDROMINFO); + + name = rindex(devname, '/') + 1; + + while (!feof(f)) { + char line[512]; + char *str; + + if (!fgets(line, sizeof(line), f)) + break; + + /* find drive number in line "drive name" */ + if (drive_number == -1) { + if (strncmp(line, "drive name:", 11) == 0) { + str = strtok(&line[11], "\t "); + drive_number = 0; + while (strncmp(name, str, strlen(name)) != 0) { + drive_number++; + str = strtok(NULL, "\t "); + if (!str) + errx(EXIT_FAILURE, + _("%s: failed to finding CD-ROM name"), + _PATH_PROC_CDROMINFO); + } + } + /* find line "drive speed" and read the correct speed */ + } else { + if (strncmp(line, "drive speed:", 12) == 0) { + int i; + char *str; + + str = strtok(&line[12], "\t "); + for (i = 1; i < drive_number; i++) + str = strtok(NULL, "\t "); + + if (!str) + errx(EXIT_FAILURE, + _("%s: failed to read speed"), + _PATH_PROC_CDROMINFO); + return atoi(str); + } + } + } + + errx(EXIT_FAILURE, _("failed to read speed")); +} + +/* + * List Speed of CD-ROM drive. + */ +static void list_speeds(const char *name, int fd) +{ +#ifdef CDROM_SELECT_SPEED + int max_speed, curr_speed = 0, prev_speed; + + select_speed(fd, 0); + max_speed = read_speed(name); + + while (curr_speed < max_speed) { + prev_speed = curr_speed; + select_speed(fd, prev_speed + 1); + curr_speed = read_speed(name); + if (curr_speed > prev_speed) + printf("%d ", curr_speed); + else + curr_speed = prev_speed + 1; + } + + printf("\n"); +#else + warnx(_("CD-ROM select speed command not supported by this kernel")); +#endif +} + +/* + * Eject using CDROMEJECT ioctl. Return 1 if successful, 0 otherwise. + */ +static int eject_cdrom(int fd) +{ +#if defined(CDROMEJECT) + return ioctl(fd, CDROMEJECT) == 0; +#elif defined(CDIOCEJECT) + return ioctl(fd, CDIOCEJECT) == 0; +#else + warnx(_("CD-ROM eject unsupported")); +#endif +} + +/* + * Eject using SCSI SG_IO commands. Return 1 if successful, 0 otherwise. + */ +static int eject_scsi(int fd) +{ + int status, k; + sg_io_hdr_t io_hdr; + unsigned char allowRmBlk[6] = {ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0}; + unsigned char startStop1Blk[6] = {START_STOP, 0, 0, 0, 1, 0}; + unsigned char startStop2Blk[6] = {START_STOP, 0, 0, 0, 2, 0}; + unsigned char inqBuff[2]; + unsigned char sense_buffer[32]; + + if ((ioctl(fd, SG_GET_VERSION_NUM, &k) < 0) || (k < 30000)) { + verbose(_("not an sg device, or old sg driver")); + return 0; + } + + memset(&io_hdr, 0, sizeof(sg_io_hdr_t)); + io_hdr.interface_id = 'S'; + io_hdr.cmd_len = 6; + io_hdr.mx_sb_len = sizeof(sense_buffer); + io_hdr.dxfer_direction = SG_DXFER_NONE; + io_hdr.dxfer_len = 0; + io_hdr.dxferp = inqBuff; + io_hdr.sbp = sense_buffer; + io_hdr.timeout = 10000; + + io_hdr.cmdp = allowRmBlk; + status = ioctl(fd, SG_IO, (void *)&io_hdr); + if (status < 0) + return 0; + + io_hdr.cmdp = startStop1Blk; + status = ioctl(fd, SG_IO, (void *)&io_hdr); + if (status < 0) + return 0; + + io_hdr.cmdp = startStop2Blk; + status = ioctl(fd, SG_IO, (void *)&io_hdr); + if (status < 0) + return 0; + + /* force kernel to reread partition table when new disc inserted */ + status = ioctl(fd, BLKRRPART); + return 1; +} + +/* + * Eject using FDEJECT ioctl. Return 1 if successful, 0 otherwise. + */ +static int eject_floppy(int fd) +{ + return ioctl(fd, FDEJECT) >= 0; +} + + +/* + * Rewind and eject using tape ioctl. Return 1 if successful, 0 otherwise. + */ +static int eject_tape(int fd) +{ + struct mtop op = { .mt_op = MTOFFL, .mt_count = 0 }; + + return ioctl(fd, MTIOCTOP, &op) >= 0; +} + + +/* umount a device. */ +static void umount_one(const char *name) +{ + int status; + + if (!name) + return; + + verbose(_("%s: unmounting"), name); + + switch (fork()) { + case 0: /* child */ + if (setgid(getgid()) < 0) + err(EXIT_FAILURE, _("cannot set group id")); + + if (setuid(getuid()) < 0) + err(EXIT_FAILURE, _("eject: cannot set user id")); + + if (p_option) + execl("/bin/umount", "/bin/umount", name, "-n", NULL); + else + execl("/bin/umount", "/bin/umount", name, NULL); + + errx(EXIT_FAILURE, _("unable to exec /bin/umount of `%s'"), name); + + case -1: + warn( _("unable to fork")); + break; + + default: /* parent */ + wait(&status); + if (WIFEXITED(status) == 0) + errx(EXIT_FAILURE, + _("unmount of `%s' did not exit normally"), name); + + if (WEXITSTATUS(status) != 0) + errx(EXIT_FAILURE, _("unmount of `%s' failed\n"), name); + break; + } +} + +/* Open a device file. */ +static int open_device(const char *name) +{ + int fd = open(name, O_RDWR|O_NONBLOCK); + + if (fd < 0) + fd = open(name, O_RDONLY|O_NONBLOCK); + if (fd == -1) + errx(EXIT_FAILURE, _("%s: open failed"), name); + return fd; +} + +/* + * See if device has been mounted by looking in mount table. If so, set + * device name and mount point name, and return 1, otherwise return 0. + */ +static int device_get_mountpoint(char **devname, char **mnt) +{ + struct libmnt_fs *fs; + int rc; + + *mnt = NULL; + + if (!mtab) { + mtab = mnt_new_table(); + if (!mtab) + err(EXIT_FAILURE, _("failed to initialize libmount table")); + + cache = mnt_new_cache(); + mnt_table_set_cache(mtab, cache); + + if (p_option) + rc = mnt_table_parse_file(mtab, _PATH_PROC_MOUNTINFO); + else + rc = mnt_table_parse_mtab(mtab, NULL); + if (rc) + err(EXIT_FAILURE, _("failed to parse mount table")); + } + + fs = mnt_table_find_source(mtab, *devname, MNT_ITER_BACKWARD); + if (!fs) { + /* maybe 'devname' is mountpoint rather than a real device */ + fs = mnt_table_find_target(mtab, *devname, MNT_ITER_BACKWARD); + if (fs) { + free(*devname); + *devname = xstrdup(mnt_fs_get_source(fs)); + } + } + + if (fs) { + *mnt = xstrdup(mnt_fs_get_target(fs)); + /* We'll call umount(), so remove the filesystem from the table + * to avoid duplicate results in the next device_get_mountpoint() + * call */ + mnt_free_fs(fs); + } + return *mnt ? 0 : -1; +} + +static char *get_disk_devname(const char *device) +{ + struct stat st; + dev_t diskno = 0; + char diskname[128]; + + if (stat(device, &st) != 0) + return NULL; + + /* get whole-disk devno */ + if (sysfs_devno_to_wholedisk(st.st_rdev, diskname, + sizeof(diskname), &diskno) != 0) + return NULL; + + return st.st_rdev == diskno ? NULL : find_device(diskname); +} + +static void umount_partitions(const char *disk) +{ + struct sysfs_cxt cxt = UL_SYSFSCXT_EMPTY; + dev_t devno; + DIR *dir = NULL; + struct dirent *d; + + devno = sysfs_devname_to_devno(disk, NULL); + if (sysfs_init(&cxt, devno, NULL) != 0) + return; + + /* open /sys/block/<wholedisk> */ + if (!(dir = sysfs_opendir(&cxt, NULL))) + goto done; + + /* scan for partition subdirs */ + while ((d = readdir(dir))) { + if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, "..")) + continue; + + if (sysfs_is_partition_dirent(dir, d, disk)) { + char *mnt = NULL; + char *dev = find_device(d->d_name); + + if (dev && device_get_mountpoint(&dev, &mnt) == 0) { + verbose(_("%s: mounted at %s"), dev, mnt); + umount_one(mnt); + } + free(dev); + } + } + +done: + if (dir) + closedir(dir); + sysfs_deinit(&cxt); +} + +static int is_hotpluggable_subsystem(const char *name) +{ + size_t i; + + for (i = 0; i < ARRAY_SIZE(hotplug_subsystems); i++) + if (strcmp(name, hotplug_subsystems[i]) == 0) + return 1; + + return 0; +} + +#define SUBSYSTEM_LINKNAME "/subsystem" + +/* + * For example: + * + * chain: /sys/dev/block/../../devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2/ \ + * 1-1.2:1.0/host65/target65:0:0/65:0:0:0/block/sdb + * + * The function check if <chain>/subsystem symlink exists, if yes then returns + * basename of the readlink result, and remove the last subdirectory from the + * <chain> path. + */ +static char *get_subsystem(char *chain, char *buf, size_t bufsz) +{ + size_t len; + char *p; + + if (!chain || !*chain) + return NULL; + + len = strlen(chain); + if (len + sizeof(SUBSYSTEM_LINKNAME) > PATH_MAX) + return NULL; + + do { + ssize_t sz; + + /* append "/subsystem" to the path */ + memcpy(chain + len, SUBSYSTEM_LINKNAME, sizeof(SUBSYSTEM_LINKNAME)); + + /* try if subsystem symlink exists */ + sz = readlink(chain, buf, bufsz); + + /* remove last subsystem from chain */ + chain[len] = '\0'; + p = strrchr(chain, '/'); + if (p) { + *p = '\0'; + len = p - chain; + } + + if (sz > 0) { + /* we found symlink to subsystem, return basename */ + buf[sz] = '\0'; + return basename(buf); + } + + } while (p); + + return NULL; +} + +static int is_hotpluggable(const char* device) +{ + struct sysfs_cxt cxt = UL_SYSFSCXT_EMPTY; + char devchain[PATH_MAX]; + char subbuf[PATH_MAX]; + dev_t devno; + int rc = 0; + ssize_t sz; + char *sub; + + devno = sysfs_devname_to_devno(device, NULL); + if (sysfs_init(&cxt, devno, NULL) != 0) + return 0; + + /* check /sys/dev/block/<maj>:<min>/removable attribute */ + if (sysfs_read_int(&cxt, "removable", &rc) == 0 && rc == 1) { + verbose(_("%s: is removable device"), device); + goto done; + } + + /* read /sys/dev/block/<maj>:<min> symlink */ + sz = sysfs_readlink(&cxt, NULL, devchain, sizeof(devchain)); + if (sz <= 0 || sz + sizeof(_PATH_SYS_DEVBLOCK "/") > sizeof(devchain)) + goto done; + + devchain[sz++] = '\0'; + + /* create absolute patch from the link */ + memmove(devchain + sizeof(_PATH_SYS_DEVBLOCK "/") - 1, devchain, sz); + memcpy(devchain, _PATH_SYS_DEVBLOCK "/", + sizeof(_PATH_SYS_DEVBLOCK "/") - 1); + + while ((sub = get_subsystem(devchain, subbuf, sizeof(subbuf)))) { + rc = is_hotpluggable_subsystem(sub); + if (rc) { + verbose(_("%s: connected by hotplug subsystem: %s"), + device, sub); + break; + } + } + +done: + sysfs_deinit(&cxt); + return rc; +} + + +/* handle -x option */ +void set_device_speed(char *name) +{ + int fd; + + if (!x_option) + return; + + if (x_arg == 0) + verbose(_("setting CD-ROM speed to auto")); + else + verbose(_("setting CD-ROM speed to %ldX"), x_arg); + + fd = open_device(name); + select_speed(fd, x_arg); + exit(EXIT_SUCCESS); +} + + +/* main program */ +int main(int argc, char **argv) +{ + char *device = NULL; + char *disk = NULL; + char *mountpoint = NULL; + int worked = 0; /* set to 1 when successfully ejected */ + int fd; /* file descriptor for device */ + + setlocale(LC_ALL,""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + + /* parse the command line arguments */ + parse_args(argc, argv, &device); + + /* handle -d option */ + if (d_option) { + info(_("default device: `%s'"), EJECT_DEFAULT_DEVICE); + return EXIT_SUCCESS; + } + + if (!device) { + device = mnt_resolve_path(EJECT_DEFAULT_DEVICE, NULL); + verbose(_("using default device `%s'"), device); + } else { + char *p; + + if (device[strlen(device)-1] == '/') + device[strlen(device)-1] = '\0'; + + /* figure out full device or mount point name */ + p = find_device(device); + free(device); + + device = mnt_resolve_path(p, NULL); + free(p); + } + + if (!device) + errx(EXIT_FAILURE, _("%s: unable to find device"), device); + + verbose(_("device name is `%s'"), device); + + device_get_mountpoint(&device, &mountpoint); + if (mountpoint) + verbose(_("%s: mounted at %s"), device, mountpoint); + else + verbose(_("%s: not mounted"), device); + + disk = get_disk_devname(device); + if (disk) { + verbose(_("%s: disc device: %s (disk device will be used for eject)"), device, disk); + free(device); + device = disk; + disk = NULL; + } else + verbose(_("%s: is whole-disk device"), device); + + if (F_option == 0 && is_hotpluggable(device) == 0) + errx(EXIT_FAILURE, _("%s: is not hot-pluggable device"), device); + + /* handle -n option */ + if (n_option) { + info(_("device is `%s'"), device); + verbose(_("exiting due to -n/--noop option")); + return EXIT_SUCCESS; + } + + /* handle -i option */ + if (i_option) { + fd = open_device(device); + manual_eject(fd, i_arg); + return EXIT_SUCCESS; + } + + /* handle -a option */ + if (a_option) { + if (a_arg) + verbose(_("%s: enabling auto-eject mode"), device); + else + verbose(_("%s: disabling auto-eject mode"), device); + fd = open_device(device); + auto_eject(fd, a_arg); + return EXIT_SUCCESS; + } + + /* handle -t option */ + if (t_option) { + verbose(_("%s: closing tray"), device); + fd = open_device(device); + close_tray(fd); + set_device_speed(device); + return EXIT_SUCCESS; + } + + /* handle -T option */ + if (T_option) { + verbose(_("%s: toggling tray"), device); + fd = open_device(device); + toggle_tray(fd); + set_device_speed(device); + return EXIT_SUCCESS; + } + + /* handle -X option */ + if (X_option) { + verbose(_("%s: listing CD-ROM speed"), device); + fd = open_device(device); + list_speeds(device, fd); + return EXIT_SUCCESS; + } + + /* handle -x option only */ + if (!c_option) + set_device_speed(device); + + + /* if it is a multipartition device, unmount any other partitions on + the device */ + if (m_option != 1) { + if (mountpoint) + umount_one(mountpoint); /* usually whole-disk */ + umount_partitions(device); + } + + /* handle -c option */ + if (c_option) { + verbose(_("%s: selecting CD-ROM disc #%ld"), device, c_arg); + fd = open_device(device); + changer_select(fd, c_arg); + set_device_speed(device); + return EXIT_SUCCESS; + } + + /* if user did not specify type of eject, try all four methods */ + if (r_option + s_option + f_option + q_option == 0) + r_option = s_option = f_option = q_option = 1; + + /* open device */ + fd = open_device(device); + + /* try various methods of ejecting until it works */ + if (r_option) { + verbose(_("%s: trying to eject using CD-ROM eject command"), device); + worked = eject_cdrom(fd); + verbose(worked ? _("CD-ROM eject command succeeded") : + _("CD-ROM eject command failed")); + } + + if (s_option && !worked) { + verbose(_("%s: trying to eject using SCSI commands"), device); + worked = eject_scsi(fd); + verbose(worked ? _("SCSI eject succeeded") : + _("SCSI eject failed")); + } + + if (f_option && !worked) { + verbose(_("%s: trying to eject using floppy eject command"), device); + worked = eject_floppy(fd); + verbose(worked ? _("floppy eject command succeeded") : + _("floppy eject command failed")); + } + + if (q_option && !worked) { + verbose(_("%s: trying to eject using tape offline command"), device); + worked = eject_tape(fd); + verbose(worked ? _("tape offline command succeeded") : + _("tape offline command failed")); + } + + if (!worked) + errx(EXIT_FAILURE, _("unable to eject")); + + /* cleanup */ + close(fd); + free(device); + free(mountpoint); + + mnt_free_table(mtab); + mnt_free_cache(cache); + + return EXIT_SUCCESS; +} diff --git a/tests/commands.sh.in b/tests/commands.sh.in index 1ce112a52..b01ebc729 100644 --- a/tests/commands.sh.in +++ b/tests/commands.sh.in @@ -62,6 +62,7 @@ TS_CMD_NAMEI=${TS_CMD_NAMEI-"$top_builddir/misc-utils/namei"} TS_CMD_LOOK=${TS_CMD_LOOK-"$top_builddir/misc-utils/look"} TS_CMD_CAL=${TS_CMD_CAL-"$top_builddir/misc-utils/cal"} TS_CMD_SCRIPT=${TS_CMD_SCRIPT-"$top_builddir/term-utils/script"} +TS_CMD_EJECT=${TS_CMD_EJECT-"$top_builddir/sys-utils/eject"} TS_CMD_HWCLOCK=${TS_CMD_HWCLOCK-"$top_builddir/hwclock/hwclock"} diff --git a/tests/expected/eject/umount b/tests/expected/eject/umount new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/tests/expected/eject/umount diff --git a/tests/expected/eject/umount-by-disk b/tests/expected/eject/umount-by-disk new file mode 100644 index 000000000..35821117c --- /dev/null +++ b/tests/expected/eject/umount-by-disk @@ -0,0 +1 @@ +Success diff --git a/tests/expected/eject/umount-by-disk-mounted b/tests/expected/eject/umount-by-disk-mounted new file mode 100644 index 000000000..35821117c --- /dev/null +++ b/tests/expected/eject/umount-by-disk-mounted @@ -0,0 +1 @@ +Success diff --git a/tests/expected/eject/umount-by-disk-mounted-partition b/tests/expected/eject/umount-by-disk-mounted-partition new file mode 100644 index 000000000..2a99ba0b4 --- /dev/null +++ b/tests/expected/eject/umount-by-disk-mounted-partition @@ -0,0 +1,2 @@ +Create partitions +Success diff --git a/tests/expected/eject/umount-by-partition b/tests/expected/eject/umount-by-partition new file mode 100644 index 000000000..2a99ba0b4 --- /dev/null +++ b/tests/expected/eject/umount-by-partition @@ -0,0 +1,2 @@ +Create partitions +Success diff --git a/tests/expected/eject/umount-by-partition-mounted b/tests/expected/eject/umount-by-partition-mounted new file mode 100644 index 000000000..2a99ba0b4 --- /dev/null +++ b/tests/expected/eject/umount-by-partition-mounted @@ -0,0 +1,2 @@ +Create partitions +Success diff --git a/tests/ts/eject/umount b/tests/ts/eject/umount new file mode 100755 index 000000000..3081c1f18 --- /dev/null +++ b/tests/ts/eject/umount @@ -0,0 +1,111 @@ +#!/bin/bash + +TS_TOPDIR="$(dirname $0)/../.." +TS_DESC="umount" + +. $TS_TOPDIR/functions.sh +ts_init "$*" +ts_skip_nonroot + +# +# Note that eject --force is required because scsi_debug is +# not removable device. +# + +modprobe --dry-run --quiet scsi_debug +[ "$?" == 0 ] || ts_skip "missing scsi_debug module" + +rmmod scsi_debug &> /dev/null + +function init_device { + modprobe scsi_debug dev_size_mb=100 + [ "$?" == 0 ] || ts_die "Cannot init device" + + sleep 3 + + DEVNAME=$(grep scsi_debug /sys/block/*/device/model | awk -F '/' '{print $4}') + [ "x${DEVNAME}" == "x" ] && ts_die "Cannot find device" + + echo "/dev/${DEVNAME}" + +} + +function init_partitions { + local dev=$1 + + ts_log "Create partitions" + $TS_CMD_FDISK $dev >> /dev/null 2>&1 <<EOF +n +p +1 + ++50M +n +p +2 + + +p +w +EOF + sleep 1 + mkfs.ext2 -q ${dev}1 + mkfs.ext2 -q ${dev}2 +} + +function deinit_device { + sleep 3 + rmmod scsi_debug +} + + +ts_init_subtest "by-disk" +DEVICE=$(init_device) +$TS_CMD_EJECT --force $DEVICE && ts_log "Success" +deinit_device +ts_finalize_subtest + +ts_init_subtest "by-disk-mounted" +DEVICE=$(init_device) +mkfs.ext2 -q -F $DEVICE +mkdir -p $TS_MOUNTPOINT +mount $DEVICE $TS_MOUNTPOINT +sleep 1 +$TS_CMD_EJECT --force $DEVICE && ts_log "Success" +deinit_device +ts_finalize_subtest + + +ts_init_subtest "by-disk-mounted-partition" +DEVICE=$(init_device) +init_partitions $DEVICE +mkdir -p ${TS_MOUNTPOINT}1 +mkdir -p ${TS_MOUNTPOINT}2 +mount ${DEVICE}1 ${TS_MOUNTPOINT}1 +mount ${DEVICE}2 ${TS_MOUNTPOINT}2 +$TS_CMD_EJECT --force $DEVICE && ts_log "Success" +deinit_device +ts_finalize_subtest + + +ts_init_subtest "by-partition" +DEVICE=$(init_device) +init_partitions $DEVICE +$TS_CMD_EJECT --force ${DEVICE}1 && ts_log "Success" +deinit_device +ts_finalize_subtest + + +ts_init_subtest "by-partition-mounted" +DEVICE=$(init_device) +init_partitions $DEVICE +mkdir -p ${TS_MOUNTPOINT}1 +mkdir -p ${TS_MOUNTPOINT}2 +mount ${DEVICE}1 ${TS_MOUNTPOINT}1 +mount ${DEVICE}2 ${TS_MOUNTPOINT}2 +$TS_CMD_EJECT --force ${DEVICE}1 && ts_log "Success" +deinit_device +ts_finalize_subtest + + +ts_finalize |