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