SCSI drive spinup after file descriptor is closed

78 Views Asked by At

I have a program where a spindown is required of a drive which is not mounted or used in any other way.

I noticed that the drive autoamtically gets a spin up after I close the filedescriptor.

I have not found any information why this is, is there any way to disable this?

Here is a short program to test it yourself. Any help or pointers would be appreciated

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <scsi/sg.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    sg_io_hdr_t io_hdr;
    const unsigned char     stopcmdblk[6]        =     { 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00 };

    int fd = open(argv[1], O_RDWR);
    if (fd == -1) {
        perror("couldn't open device");
        exit(1);
    }

    memset(&io_hdr, 0, sizeof(sg_io_hdr_t));
    io_hdr.interface_id = 'S';
    io_hdr.cmd_len = 6;
    io_hdr.mx_sb_len = 32;
    io_hdr.dxfer_direction = SG_DXFER_NONE;
    io_hdr.dxfer_len = 0;
    io_hdr.dxferp = NULL;
    io_hdr.cmdp = malloc(6);
    io_hdr.sbp = calloc(32, 1);

    memcpy(io_hdr.cmdp, stopcmdblk, 6);

    errno = 0;
    int ret = ioctl(fd, SG_IO, &io_hdr);
    if (ret < 0) { 
        perror("ioctl error");
        exit(1);
    }

    if ((io_hdr.info & SG_INFO_OK_MASK) != SG_INFO_OK) {
        printf("SCSI err\n");
        exit(1);
    }

    printf("finished spindown\n");

    sleep(30);

    printf("close file now\n");

    close(fd);
    printf("file closed\n");

    exit(0);

}
1

There are 1 best solutions below

5
On

I guess the system wants to write some metadata to disk when the file is closed. For example, the file size - it seems pointless to update the file size after each write call. So it's updated on the close call.

I think you need the sync system call. There is also a fsync variant that works for just one file; however, it's not about your file descriptor; you want to remove the drive, so all file descriptors should be taken care of.