1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44#include <sys/mount.h>
45#include "libbb.h"
46#if ENABLE_FEATURE_EJECT_SCSI
47
48# include "fix_u32.h"
49# include <scsi/sg.h>
50# include <scsi/scsi.h>
51#endif
52
53#define dev_fd 3
54
55
56
57
58#if ENABLE_FEATURE_EJECT_SCSI
59static void eject_scsi(const char *dev)
60{
61 static const char sg_commands[3][6] ALIGN1 = {
62 { ALLOW_MEDIUM_REMOVAL, 0, 0, 0, 0, 0 },
63 { START_STOP, 0, 0, 0, 1, 0 },
64 { START_STOP, 0, 0, 0, 2, 0 }
65 };
66
67 unsigned i;
68 unsigned char sense_buffer[32];
69 unsigned char inqBuff[2];
70 sg_io_hdr_t io_hdr;
71
72 if ((ioctl(dev_fd, SG_GET_VERSION_NUM, &i) < 0) || (i < 30000))
73 bb_error_msg_and_die("not a sg device or old sg driver");
74
75 memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
76 io_hdr.interface_id = 'S';
77 io_hdr.cmd_len = 6;
78 io_hdr.mx_sb_len = sizeof(sense_buffer);
79 io_hdr.dxfer_direction = SG_DXFER_NONE;
80
81 io_hdr.dxferp = inqBuff;
82 io_hdr.sbp = sense_buffer;
83 io_hdr.timeout = 2000;
84
85 for (i = 0; i < 3; i++) {
86 io_hdr.cmdp = (void *)sg_commands[i];
87 ioctl_or_perror_and_die(dev_fd, SG_IO, (void *)&io_hdr, "%s", dev);
88 }
89
90
91 ioctl(dev_fd, BLKRRPART);
92}
93#else
94# define eject_scsi(dev) ((void)0)
95#endif
96
97
98#define CDROMCLOSETRAY 0x5319
99#define CDROMEJECT 0x5309
100#define CDROM_DRIVE_STATUS 0x5326
101
102#define CDS_TRAY_OPEN 2
103
104#define FLAG_CLOSE 1
105#define FLAG_SMART 2
106#define FLAG_SCSI 4
107
108static void eject_cdrom(unsigned flags, const char *dev)
109{
110 int cmd = CDROMEJECT;
111
112 if (flags & FLAG_CLOSE
113 || ((flags & FLAG_SMART) && ioctl(dev_fd, CDROM_DRIVE_STATUS) == CDS_TRAY_OPEN)
114 ) {
115 cmd = CDROMCLOSETRAY;
116 }
117
118 ioctl_or_perror_and_die(dev_fd, cmd, NULL, "%s", dev);
119}
120
121int eject_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
122int eject_main(int argc UNUSED_PARAM, char **argv)
123{
124 unsigned flags;
125 const char *device;
126
127 flags = getopt32(argv, "^" "tT"IF_FEATURE_EJECT_SCSI("s")
128 "\0" "?1:t--T:T--t"
129 );
130 device = argv[optind] ? argv[optind] : "/dev/cdrom";
131
132
133
134
135
136
137
138
139
140
141
142 xmove_fd(xopen_nonblocking(device), dev_fd);
143
144 if (ENABLE_FEATURE_EJECT_SCSI && (flags & FLAG_SCSI))
145 eject_scsi(device);
146 else
147 eject_cdrom(flags, device);
148
149 if (ENABLE_FEATURE_CLEAN_UP)
150 close(dev_fd);
151
152 return EXIT_SUCCESS;
153}
154