+sub scsi_inquiry {
+ my($fh, $noerr) = @_;
+
+ my $SG_IO = 0x2285;
+ my $SG_GET_VERSION_NUM = 0x2282;
+
+ my $versionbuf = "\x00" x 8;
+ my $ret = ioctl($fh, $SG_GET_VERSION_NUM, $versionbuf);
+ if (!$ret) {
+ die "scsi ioctl SG_GET_VERSION_NUM failoed - $!\n" if !$noerr;
+ return;
+ }
+ my $version = unpack("I", $versionbuf);
+ if ($version < 30000) {
+ die "scsi generic interface too old\n" if !$noerr;
+ return;
+ }
+
+ my $buf = "\x00" x 36;
+ my $sensebuf = "\x00" x 8;
+ my $cmd = pack("C x3 C x1", 0x12, 36);
+
+ # see /usr/include/scsi/sg.h
+ my $sg_io_hdr_t = "i i C C s I P P P I I i P C C C C S S i I I";
+
+ my $packet = pack(
+ $sg_io_hdr_t, ord('S'), -3, length($cmd), length($sensebuf), 0, length($buf), $buf, $cmd, $sensebuf, 6000
+ );
+
+ $ret = ioctl($fh, $SG_IO, $packet);
+ if (!$ret) {
+ die "scsi ioctl SG_IO failed - $!\n" if !$noerr;
+ return;
+ }
+
+ my @res = unpack($sg_io_hdr_t, $packet);
+ if ($res[17] || $res[18]) {
+ die "scsi ioctl SG_IO status error - $!\n" if !$noerr;
+ return;
+ }
+
+ my $res = {};
+ $res->@{qw(type removable vendor product revision)} = unpack("C C x6 A8 A16 A4", $buf);
+
+ $res->{removable} = $res->{removable} & 128 ? 1 : 0;
+ $res->{type} &= 0x1F;
+
+ return $res;
+}
+
+sub path_is_scsi {
+ my ($path) = @_;
+
+ my $fh = IO::File->new("+<$path") || return;
+ my $res = scsi_inquiry($fh, 1);
+ close($fh);
+
+ return $res;
+}
+
+sub get_scsi_device_type {
+ my ($drive, $storecfg, $machine_version) = @_;
+
+ my $devicetype = 'hd';
+ my $path = '';
+ if (drive_is_cdrom($drive) || drive_is_cloudinit($drive)) {
+ $devicetype = 'cd';
+ } else {
+ if ($drive->{file} =~ m|^/|) {
+ $path = $drive->{file};
+ if (my $info = path_is_scsi($path)) {
+ if ($info->{type} == 0 && $drive->{scsiblock}) {
+ $devicetype = 'block';
+ } elsif ($info->{type} == 1) { # tape
+ $devicetype = 'generic';
+ }
+ }
+ } elsif ($drive->{file} =~ $NEW_DISK_RE){
+ # special syntax cannot be parsed to path
+ return $devicetype;
+ } else {
+ $path = PVE::Storage::path($storecfg, $drive->{file});
+ }
+
+ # for compatibility only, we prefer scsi-hd (#2408, #2355, #2380)
+ if ($path =~ m/^iscsi\:\/\// &&
+ !PVE::QemuServer::Helpers::min_version($machine_version, 4, 1)) {
+ $devicetype = 'generic';
+ }
+ }
+
+ return $devicetype;
+}