1 /* vi: set sw=4 ts=4: */
3 * eject implementation for busybox
5 * Copyright (C) 2004 Peter Willis <psyphreak@phreaker.net>
6 * Copyright (C) 2005 Tito Ragusa <farmatito@tiscali.it>
8 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
12 * This is a simple hack of eject based on something Erik posted in #uclibc.
13 * Most of the dirty work blatantly ripped off from cat.c =)
16 #include <sys/mount.h>
18 /* Must be after libbb.h: they need size_t */
21 #include <scsi/scsi.h>
23 /* various defines swiped from linux/cdrom.h */
24 #define CDROMCLOSETRAY 0x5319 /* pendant of CDROMEJECT */
25 #define CDROMEJECT 0x5309 /* Ejects the cdrom media */
26 #define CDROM_DRIVE_STATUS 0x5326 /* Get tray position, etc. */
27 /* drive status possibilities returned by CDROM_DRIVE_STATUS ioctl */
28 #define CDS_TRAY_OPEN 2
32 /* Code taken from the original eject (http://eject.sourceforge.net/),
33 * refactored it a bit for busybox (ne-bb@nicoerfurth.de) */
35 static void eject_scsi(const char *dev)
37 static const char sg_commands[3][6] = {
38 { ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0 },
39 { START_STOP, 0, 0, 0, 1, 0 },
40 { START_STOP, 0, 0, 0, 2, 0 }
44 unsigned char sense_buffer[32];
45 unsigned char inqBuff[2];
48 if ((ioctl(dev_fd, SG_GET_VERSION_NUM, &i) < 0) || (i < 30000))
49 bb_error_msg_and_die("not a sg device or old sg driver");
51 memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
52 io_hdr.interface_id = 'S';
54 io_hdr.mx_sb_len = sizeof(sense_buffer);
55 io_hdr.dxfer_direction = SG_DXFER_NONE;
56 /* io_hdr.dxfer_len = 0; */
57 io_hdr.dxferp = inqBuff;
58 io_hdr.sbp = sense_buffer;
59 io_hdr.timeout = 2000;
61 for (i = 0; i < 3; i++) {
62 io_hdr.cmdp = (void *)sg_commands[i];
63 ioctl_or_perror_and_die(dev_fd, SG_IO, (void *)&io_hdr, "%s", dev);
66 /* force kernel to reread partition table when new disc is inserted */
67 ioctl(dev_fd, BLKRRPART);
74 static void eject_cdrom(unsigned flags, const char *dev)
78 if (flags & FLAG_CLOSE
79 || ((flags & FLAG_SMART) && ioctl(dev_fd, CDROM_DRIVE_STATUS) == CDS_TRAY_OPEN)
84 ioctl_or_perror_and_die(dev_fd, cmd, NULL, "%s", dev);
87 int eject_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
88 int eject_main(int argc UNUSED_PARAM, char **argv)
93 opt_complementary = "?1:t--T:T--t";
94 flags = getopt32(argv, "tT" IF_FEATURE_EJECT_SCSI("s"));
95 device = argv[optind] ? argv[optind] : "/dev/cdrom";
97 /* We used to do "umount <device>" here, but it was buggy
98 if something was mounted OVER cdrom and
99 if cdrom is mounted many times.
101 This works equally well (or better):
107 xmove_fd(xopen_nonblocking(device), dev_fd);
109 if (ENABLE_FEATURE_EJECT_SCSI && (flags & FLAG_SCSI))
112 eject_cdrom(flags, device);
114 if (ENABLE_FEATURE_CLEAN_UP)