/* Linux specific backend for cdwrite. */

#include <stdio.h>
#include <stdarg.h>
#include <sys/file.h>
#include <sys/errno.h>
#include "cdwrite.h"

#if 0
#include "/usr/src/linux/drivers/block/blk.h"
#include "/usr/src/linux/drivers/scsi/scsi.h"
#endif

#define SG_SET_TIMEOUT 0x2201  /* set timeout *(int *)arg==timeout */
#define SG_GET_TIMEOUT 0x2202  /* get timeout return timeout */

#define SG_DEFAULT_TIMEOUT 6000 /* 1 minute timeout */
#define SG_DEFAULT_RETRIES 1

#define SG_MAX_QUEUE 4 /* maximum outstanding request, arbitrary, may be
                          changed if sufficient DMA buffer room available */

void set_timeout(int fd, unsigned long timeout)
{
  if (ioctl(fd, SG_SET_TIMEOUT, SG_SET_TIMEOUT, &timeout) < 0) {
    perror ("ioctl SG_SET_TIMEOUT");
    exit(5);
  }
}


int
send_request( int fd, const char *note,
	     int *reply_len, struct sg_reply *rep, int nbytes, ...) {
   va_list args;
   struct sg_request sg_request;
   int i;
   int result;
   int expected_size;

   bzero (&sg_request, sizeof(sg_request));
   sg_request.header.pack_len = sizeof(struct sg_header) + 10;
   sg_request.header.reply_len = *reply_len + sizeof(struct sg_header);
   sg_request.header.pack_id = pack_id++;
   sg_request.header.result = 0;

   va_start(args, nbytes);
   for (i = 0; i < nbytes; i++ ) {
      sg_request.bytes[i] = va_arg(args,unsigned int);
   }
   va_end (args);

   expected_size = sizeof(struct sg_header) + nbytes;
   if ((result = write( fd, &sg_request, expected_size)) < 0) {
      perror ("write_track: write");
      return -1;
   }
   else if (result != expected_size) {
      fprintf (stderr, "send_request %s wrote %d bytes, expected to write %d.\n",
	       note ? "<no note>" : note, result, expected_size);
   }
   *reply_len = read (fd, rep, sizeof(struct sg_reply));
   /* if (note) print_reply(note,*reply_len,rep); */
   if (auto_request_sense) {
      auto_request_sense = 0;
      quiet_request_sense( fd, 0, note, reply_len, rep);
      auto_request_sense = 1;
   }

   return 0;
}
