int ca_open(phastream_t *as, char *name, int rate, int framesize, ph_audio_cbk cbk) {
	int errInput, errOutput;
	
	ca_dev *cadev = (ca_dev *) calloc(1, sizeof(ca_dev));

	DBG_DYNA_AUDIO_DRV("phad_coreaudio: ca_open: Opening device %s with rate: %d, framesize: %d, and callback: %p\n",
		  name, rate, framesize, cbk);

	cadev->cbk = cbk;

	as->drvinfo = cadev;

	parse_device(cadev, name);

	as->actual_rate = rate;
	errInput = init_input_device(as, rate, 1, 16); //FIXME: channels and format should be given by phapi
	errOutput = init_output_device(as, rate, 1, 16);

	if (errOutput < 0)
	{
		DBG_DYNA_AUDIO_DRV("phad_coreaudio: could not init output device");
		clean_input_device(as);
		return -PH_NORESOURCES;
	}

	DBG_DYNA_AUDIO_DRV("**CoreAudio: actual_rate: %d, clock_rate: %d\n", as->actual_rate, rate);

	return 0;
}
Beispiel #2
0
static int
parse_db(FILE *f, pcidb_hdl_t *hdl)
{
	char buf[1024];
	pcidb_vendor_t *v = NULL;
	pcidb_device_t *d = NULL;
	pcidb_parse_t state = PDB_VENDOR;

	for (;;) {
		errno = 0;
		if (readline(f, buf, sizeof (buf)) != 0) {
			if (errno != 0)
				return (-1);
			else
				return (0);
		}

newstate:
		switch (state) {
		case PDB_VENDOR:
			v = parse_vendor(buf, hdl);
			if (v == NULL)
				return (NULL);
			state = PDB_DEVICE;
			continue;
		case PDB_DEVICE:
			if (buf[0] != '\t') {
				state = PDB_VENDOR;
				goto newstate;
			}

			if (buf[1] == '\t') {
				state = PDB_SUBDEV;
				goto newstate;
			}

			assert(v != NULL);
			d = parse_device(buf, v);
			if (d == NULL)
				return (NULL);
			continue;
		case PDB_SUBDEV:
			if (buf[0] != '\t') {
				state = PDB_VENDOR;
				goto newstate;
			}

			if (buf[0] == '\t' && buf[1] != '\t') {
				state = PDB_DEVICE;
				goto newstate;
			}

			assert(buf[0] == '\t' && buf[1] == '\t');
			assert(d != NULL);
			(void) parse_subdev(buf, d);
		}
	}
}
Beispiel #3
0
//
// parse_device
//   Get the devices that described in a root of json file
//
int parse_device(Json::Value &value)
{
    switch (value.type()) {
    case Json::nullValue:
        break;
    case Json::arrayValue:
    {
        // Travel the elements in array
        int size = value.size();
        for (int index = 0; index < size; ++index)
            parse_device(value[index]);        
    } break;
    case Json::objectValue:
    {
        // Create device instance according device type
        if (value[DEVICE_NAME] == Json::nullValue)
            dbg_print("WARNING: Should to specify the name for device\n");
        // Should specify a device type in json elements
        if (value[DEVICE_TYPE] == Json::nullValue) {
            printf("ERROR: Need to specify the device type for device\n");
            break;
        }

        dbg_print("INFO: Got device [%s]\n",
                  value[DEVICE_NAME].asString().c_str());
        // Create device instance according device type
        if (create_device_map[value[DEVICE_TYPE].asString()] != NULL)
            (*create_device_map[value[DEVICE_TYPE].asString()])(value);
        else
            dbg_print("INFO: Not the function to create a %s instance\n",
                      value[DEVICE_TYPE].asString().data());
    } break;
    default:
        break;
    }

    return 0;
}
Beispiel #4
0
int read_char_commands(int argc, char *argv[], char msgs[MAX_MSGS][BUFFER])
{
  int i, cmd, arg;
  arg = 0;
  cmd = 0;
  for(i=1; argv[i] != NULL; i+=arg){
    if(argv[i][0] == '-'){
      arg = 1;
      switch(argv[i][1]){
        case 'd':
          if((i + 1) >= argc){
            fprintf(stderr, "option -d needs an extra parameter\n");
            return -1;
          }

          parse_device(argv[i + 1]);

          printf("setting device name to %s and baud rate to %d\n",
              device, baud_rate);
          break;
        case 'r':
          strcpy(msgs[cmd++], "*RST?");
          break;
        case 'c':strcpy(msgs[cmd], "*CLS?");
                 break;
        case 'p':
                 if(argv[i][2] == '?' || !argv[i+1] || argv[i+1][0] == '-'){
                   strcpy(msgs[cmd++], "POWER?");
                 }else{
                   sprintf(msgs[cmd++], "POWER %s", argv[i+1]);
                   arg = 2;
                 }
                 break;
        case 'f':
                 if(argv[i][2] == '?' || !argv[i+1] || argv[i+1][0] == '-'){
                   strcpy(msgs[cmd++], "FREQUENCY?");
                 }else {
                   arg = 2;
                   sprintf(msgs[cmd++], "FREQUENCY %s", argv[i+1]);
                 }
                 break;
        case 'o': if(argv[i][2] == '?' || !argv[i+1] || argv[i+1][0] == '-'){
                    strcpy(msgs[cmd++], "OUTPUT?");
                  }else {
                    sprintf(msgs[cmd++], "OUTPUT %s", argv[i+1]);
                    arg = 2;
                  }
                  break;
        case 'e':
                  strcpy(msgs[cmd++], "*ESR?");
                  strcpy(msgs[cmd++], "SYST:ERR?");
                  break;
        case 's': 
                  strcpy(msgs[cmd++], "FREQUENCY?");
                  strcpy(msgs[cmd++], "POWER?");
                  strcpy(msgs[cmd++], "OUTPUT?");
                  strcpy(msgs[cmd++], "*ESR?");
                  strcpy(msgs[cmd++], "SYST:ERR?");
                  break;
        default:
                  strcpy(msgs[cmd++], "*IDN?");
                  break;
      }

    }
  }
  return cmd;
}
Beispiel #5
0
int main(int argc, char *argv[]){

  char *temp;// = "/dev/ttyMI1";
  //int baud_rate;// = 9600;

  FILE *cfPtr;
  int i, max_cmd, error_query = 0;
  struct timeval timeout = {3, 0};//3 seconds
  int retval;
  fd_set rd_serial_data_fds;

  char buffer[BUFFER], file_name[50], msgs[MAX_MSGS][BUFFER];
  int len = 0, fd = -1;

  temp = getenv("DEVICE");
  if(temp != NULL){
    parse_device(temp);
  }

#if 0
  temp = getenv("BAUD_RATE");
  if(temp != NULL){
    baud_rate = atoi(temp);
  } else {        
    baud_rate = DEFAULT_BAUD;
  }
  for(i=0; baud_rate != speed_table[i].x_speed && speed_table[i].x_speed > 0; i++){}
  if(speed_table[i].x_speed == 0){
    printf("Read baud rate = %d using getenv() is invalid, default is used\n", baud_rate);
    baud_rate = DEFAULT_BAUD;
  }

  if((fd = start_serial(device, baud_rate)) < 0){
    printf("Application failed while opening or setting the attributes of a serial device: device = %s, baud_rate = %d\n", device, baud_rate);
    close(fd);
    return 0;
  }
#endif

  memset(buffer, 0x00, BUFFER); max_cmd = 0;
  if(argc == 1){
    printf("\nTo get started enter -h as an argument to display help commands: i.e. %s -h (then press enter)\n", argv[0]);
    strcpy(msgs[0], "*IDN?");//if no arguments then requet device id
    max_cmd = 1;
  }else if(!strcmp(argv[1], "help") || !strcmp(argv[1], "-h")){
    print_help(argv[0]);
    return 0;

  } else if (!strcmp(argv[1], "config")){
    if(argv[2] != NULL){
      strcpy(file_name, argv[2]);
    } else {
      printf("The configuration file name is not specified\n");
      return 0;
    }
    if((cfPtr = fopen(file_name, "r")) == NULL){
      fprintf(stderr, "error: config file fopen(%s, ): %s\n", file_name, strerror(errno));
      return -1;
    }
    printf("Reading commands from the configuration file defined as %s\n", file_name);
    while(fgets(buffer, BUFFER, cfPtr) != NULL){
      //printf("String read: %s\n",buffer);
      if(buffer[0] != '#'){//not a comment
        if(max_cmd == MAX_MSGS){
          printf("The number of commands read are greater than the defined possible No. = %d\n", MAX_MSGS);
          break;
        }
        strcpy(msgs[max_cmd], buffer);//, strlen(buffer)-1);
        msgs[max_cmd][strlen(buffer)-1] = '\0';//remove '\n'
        max_cmd++;
      }
      memset(buffer, 0x00, strlen(buffer));
    }

    fclose(cfPtr);//finished reading from a file
  }else if(argv[1][0] == '-'){
    //printf("reading char commands ...\n");
    max_cmd = read_char_commands(argc, argv, msgs);
    //printf("Finished reading, max_cmd = %d\n", max_cmd);
  }else {
    //printf("reading full commands ...\n");
    max_cmd = read_full_commands(argc, argv, msgs);
    //printf("Finished reading, max_cmd = %d\n", max_cmd);
  }

  for(i = 0; (baud_rate > speed_table[i].x_speed) && (speed_table[i].x_speed != 0); i++);

  if(speed_table[i].x_speed == 0){
    printf("baud rate = %d is invalid, the default is used\n", baud_rate);
    baud_rate = DEFAULT_BAUD;
  } else if (baud_rate != speed_table[i].x_speed){
    printf("warning: approximating requested speed of %d to %d\n", baud_rate, speed_table[i].x_speed);
    baud_rate = speed_table[i].x_speed;
  }

#if 0
  printf("\ndevice is %s, and the baud_rate is %d\n\n", device, baud_rate);
  for(i=0; i < max_cmd; i++){printf("command: msgs[%d] = %s\n", i, msgs[i]);}
  return 0;
#endif

  if((fd = start_serial(device, baud_rate)) < 0){
    printf("Failed during opening and setting the attributes of a serial device: \
        device = %s, baud_rate = %d\n", device, baud_rate);
    close(fd);
    //free_msgs_buffer(msgs);
    return -1;
  }
Beispiel #6
0
int assemble(struct _asm_context *asm_context)
{
  char token[TOKENLEN];
  int token_type;

  while(1)
  {
    token_type = tokens_get(asm_context, token, TOKENLEN);
#ifdef DEBUG
    printf("%d: <%d> %s\n", asm_context->line, token_type, token);
#endif
    if (token_type == TOKEN_EOF) break;

    if (token_type == TOKEN_EOL)
    {
      if (asm_context->macros.stack_ptr == 0) { asm_context->line++; }
    }
      else
    if (token_type == TOKEN_LABEL)
    {
      int param_count_temp;
      if (macros_lookup(&asm_context->macros, token, &param_count_temp) != NULL)
      {
        print_already_defined(asm_context, token);
        return -1;
      }

      if (symbols_append(&asm_context->symbols, token, asm_context->address / asm_context->bytes_per_address) == -1)
      {
        return -1;
      }
    }
      else
    if (token_type == TOKEN_POUND || IS_TOKEN(token,'.'))
    {
      token_type = tokens_get(asm_context, token, TOKENLEN);
#ifdef DEBUG
    printf("%d: <%d> %s\n", asm_context->line, token_type, token);
#endif
      if (token_type == TOKEN_EOF) break;

      if (strcasecmp(token, "define") == 0)
      {
        if (macros_parse(asm_context, IS_DEFINE) != 0) return -1;
      }
        else
      if (strcasecmp(token, "ifdef") == 0)
      {
        parse_ifdef(asm_context, 0);
      }
        else
      if (strcasecmp(token, "ifndef") == 0)
      {
        parse_ifdef(asm_context, 1);
      }
        else
      if (strcasecmp(token, "if") == 0)
      {
        parse_if(asm_context);
      }
        else
      if (strcasecmp(token, "endif") == 0)
      {
        if (asm_context->ifdef_count < 1)
        {
          printf("Error: unmatched .endif at %s:%d\n", asm_context->filename, asm_context->ifdef_count);
          return -1;
        }
        return 0;
      }
        else
      if (strcasecmp(token, "else") == 0)
      {
        if (asm_context->ifdef_count < 1)
        {
          printf("Error: unmatched .else at %s:%d\n", asm_context->filename, asm_context->ifdef_count);
          return -1;
        }
        return 2;
      }
        else
      if (strcasecmp(token, "include") == 0)
      {
        if (parse_include(asm_context) != 0) return -1;
      }
        else
      if (strcasecmp(token, "binfile") == 0)
      {
        if (parse_binfile(asm_context) != 0) return -1;
      }
        else
      if (strcasecmp(token, "code") == 0)
      {
        asm_context->segment = SEGMENT_CODE;
      }
        else
      if (strcasecmp(token, "bss") == 0)
      {
        asm_context->segment = SEGMENT_BSS;
      }
        else
      if (strcasecmp(token, "msp430_cpu4") == 0)
      {
        asm_context->msp430_cpu4 = 1;
      }
        else
      if (strcasecmp(token, "macro") == 0)
      {
        if (macros_parse(asm_context, IS_MACRO) != 0) return -1;
      }
        else
      if (strcasecmp(token, "pragma") == 0)
      {
        if (parse_pragma(asm_context) != 0) return -1;
      }
        else
      if (strcasecmp(token, "device") == 0)
      {
        if (parse_device(asm_context) != 0) return -1;
      }
        else
      if (strcasecmp(token, "set") == 0)
      {
        if (parse_set(asm_context) != 0) return -1;
      }
        else
      if (strcasecmp(token, "export") == 0)
      {
        if (parse_export(asm_context) != 0) return -1;
      }
        else
      if (strcasecmp(token, "equ") == 0 || strcasecmp(token, "def")==0)
      {
        if (parse_equ(asm_context) != 0) return -1;
      }
        else
      {
        int ret = check_for_directive(asm_context, token);
        if (ret == 2) break;
        if (ret == -1) return -1;
        if (ret != 1)
        {
          printf("Error: Unknown directive '%s' at %s:%d.\n", token, asm_context->filename, asm_context->line);
          return -1;
        }
      }
    }
      else
    if (token_type == TOKEN_STRING)
    {
      int ret = check_for_directive(asm_context, token);
      if (ret == 2) break;
      if (ret == -1) return -1;
      if (ret != 1) 
      {
        int start_address = asm_context->address;
        char token2[TOKENLEN];
        int token_type2;

        token_type2 = tokens_get(asm_context, token2, TOKENLEN);

        if (strcasecmp(token2, "equ") == 0)
        {
          //token_type2 = tokens_get(asm_context, token2, TOKENLEN);
          int ptr = 0;
          int ch = '\n';

          while(1)
          {
            ch = tokens_get_char(asm_context);
            if (ch == EOF || ch == '\n') break;
            if (ch == '*' && ptr > 0 && token2[ptr-1] == '/')
            {
              macros_strip_comment(asm_context);
              ptr--;
              continue;
            }

            token2[ptr++] = ch;
            if (ptr == TOKENLEN-1)
            {
              printf("Internal Error: token overflow at %s:%d.\n", __FILE__, __LINE__);
              return -1;
            }
          }
          token2[ptr] = 0;
          tokens_unget_char(asm_context, ch);
          macros_strip(token2);
          macros_append(asm_context, token, token2, 0);
        }
          else
        {
          tokens_push(asm_context, token2, token_type2);

          ret = asm_context->parse_instruction(asm_context, token);

          if (asm_context->pass == 2 &&
              asm_context->list != NULL &&
              asm_context->include_count == 0)
          {
            asm_context->list_output(asm_context, start_address);
            fprintf(asm_context->list, "\n");
          }

          if (ret < 0) return -1;

          if (asm_context->macros.stack_ptr == 0) { asm_context->line++; }
          asm_context->instruction_count++;

          if (asm_context->address > start_address)
          {
            asm_context->code_count += (asm_context->address - start_address);
          }
        }
      }
    }
      else
    {
      print_error_unexp(token, asm_context);
      return -1;
    }
  }

  if (asm_context->error == 1) { return -1; }

  return 0;
}
Beispiel #7
0
int main (int argc, char **argv)
{
	ssize_t ret_size;
	struct stat st;
	int ret, flags;

	long long this_time, time_total;
	long long part_min, part_max, time_min, time_max;
	double time_sum, time_sum2, time_mdev, time_avg;
	double part_sum, part_sum2, part_mdev, part_avg;

	parse_options(argc, argv);

	if (wsize)
		temp_wsize = wsize;
	else if (size > temp_wsize)
		temp_wsize = size;

	if (size <= 0)
		errx(1, "request size must be greather than zero");

	flags = O_RDONLY;

#if !defined(HAVE_POSIX_FADVICE) && !defined(HAVE_NOCACHE_IO) && \
			defined(HAVE_DIRECT_IO)
	direct |= !cached;
#endif

	if (direct)
#ifdef HAVE_DIRECT_IO
		flags |= O_DIRECT;
#else
		errx(1, "direct I/O not supportted by this platform");
#endif

	if (stat(path, &st))
		err(2, "stat \"%s\" failed", path);

	if (S_ISDIR(st.st_mode) || S_ISREG(st.st_mode)) {
		if (S_ISDIR(st.st_mode))
			st.st_size = offset + temp_wsize;
		parse_device(st.st_dev);
	} else if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) {
		fd = open(path, flags);
		if (fd < 0)
			err(2, "failed to open \"%s\"", path);

		st.st_size = get_device_size(fd, &st);

		fstype = "device";
		device = malloc(32);
		if (!device)
			err(2, "no mem");
		snprintf(device, 32, "%.1f Gb", (double)st.st_size/(1ll<<30));
	} else {
		errx(2, "unsupported destination: \"%s\"", path);
	}

	if (offset + wsize > st.st_size)
		errx(2, "target is too small for this");

	if (!wsize)
		wsize = st.st_size - offset;

	if (size > wsize)
		errx(2, "request size is too big for this target");

	ret = posix_memalign(&buf, sysconf(_SC_PAGE_SIZE), size);
	if (ret)
		errx(2, "buffer allocation failed");
	memset(buf, '*', size);

	if (S_ISDIR(st.st_mode)) {
		char *tmpl = "/ioping.XXXXXX";
		char *temp = malloc(strlen(path) + strlen(tmpl) + 1);

		if (!temp)
			err(2, NULL);
		sprintf(temp, "%s%s", path, tmpl);
		fd = mkstemp(temp);
		if (fd < 0)
			err(2, "failed to create temporary file at \"%s\"", path);
		if (unlink(temp))
			err(2, "unlink \"%s\" failed", temp);
		if (fcntl(fd, F_SETFL, flags)) {
			warn("fcntl failed");
			if (direct)
				errx(2, "please retry without -D");
			errx(2, "it is so sad");
		}

		for (woffset = 0 ; woffset + size <= wsize ; woffset += size) {
			if (pwrite(fd, buf, size, offset + woffset) != size)
				err(2, "write failed");
		}
		if (fsync(fd))
			err(2, "fsync failed");
		free(temp);
	} else if (S_ISREG(st.st_mode)) {
		fd = open(path, flags);
		if (fd < 0)
			err(2, "failed to open \"%s\"", path);
	}

	if (!cached) {
#ifdef HAVE_POSIX_FADVICE
		ret = posix_fadvise(fd, offset, wsize, POSIX_FADV_RANDOM);
		if (ret)
			err(2, "fadvise failed");
#endif
#ifdef HAVE_NOCACHE_IO
		ret = fcntl(fd, F_NOCACHE, 1);
		if (ret)
			err(2, "fcntl nocache failed");
#endif
	}

	srandom(now());

	if (deadline)
		deadline += now();

	set_signal(SIGINT, sig_exit);

	request = 0;
	woffset = 0;

	part_min = time_min = LLONG_MAX;
	part_max = time_max = LLONG_MIN;
	part_sum = time_sum = 0;
	part_sum2 = time_sum2 = 0;
	time_total = now();

	while (!exiting) {
		request++;

		if (randomize)
			woffset = random() % (wsize / size) * size;

#ifdef HAVE_POSIX_FADVICE
		if (!cached) {
			ret = posix_fadvise(fd, offset + woffset, size,
					POSIX_FADV_DONTNEED);
			if (ret)
				err(3, "fadvise failed");
		}
#endif

		this_time = now();
		ret_size = pread(fd, buf, size, offset + woffset);
		if (ret_size < 0 && errno != EINTR)
			err(3, "read failed");
		this_time = now() - this_time;

		part_sum += this_time;
		part_sum2 += this_time * this_time;
		if (this_time < part_min)
			part_min = this_time;
		if (this_time > part_max)
			part_max = this_time;

		if (!quiet)
			printf("%lld bytes from %s (%s %s): request=%d time=%.1f ms\n",
					(long long)ret_size, path, fstype, device,
					request, this_time / 1000.);

		if (period && request % period == 0) {
			part_avg = part_sum / period;
			part_mdev = sqrt(part_sum2 / period - part_avg * part_avg);

			printf("%lld %.0f %lld %.0f\n",
					part_min, part_avg,
					part_max, part_mdev);

			time_sum += part_sum;
			time_sum2 += part_sum2;
			if (part_min < time_min)
				time_min = part_min;
			if (part_max > time_max)
				time_max = part_max;
			part_min = LLONG_MAX;
			part_max = LLONG_MIN;
			part_sum = part_sum2 = 0;
		}

		if (!randomize) {
			woffset += size;
			if (woffset + size > wsize)
				woffset = 0;
		}

		if (exiting)
			break;

		if (count && request >= count)
			break;

		if (deadline && now() + interval >= deadline)
			break;

		usleep(interval);
	}

	time_total = now() - time_total;

	time_sum += part_sum;
	time_sum2 += part_sum2;
	if (part_min < time_min)
		time_min = part_min;
	if (part_max > time_max)
		time_max = part_max;

	time_avg = time_sum / request;
	time_mdev = sqrt(time_sum2 / request - time_avg * time_avg);

	if (!quiet || !period) {
		printf("\n--- %s (%s %s) ioping statistics ---\n",
				path, fstype, device);
		printf("%d requests completed in %.1f ms, "
				"%.0f iops, %.1f mb/s\n",
				request, time_total/1000.,
				request * 1000000. / time_sum,
				(double)request * size / time_sum /
				(1<<20) * 1000000);
		printf("min/avg/max/mdev = %.1f/%.1f/%.1f/%.1f ms\n",
				time_min/1000., time_avg/1000.,
				time_max/1000., time_mdev/1000.);
	}

	return 0;
}
Beispiel #8
0
/*
 * Parse a single keyword and its value.
 */
static int
parse_keyword(struct archive_read *a, struct mtree *mtree,
    struct archive_entry *entry, struct mtree_option *opt, int *parsed_kws)
{
	char *val, *key;

	key = opt->value;

	if (*key == '\0')
		return (ARCHIVE_OK);

	if (strcmp(key, "nochange") == 0) {
		*parsed_kws |= MTREE_HAS_NOCHANGE;
		return (ARCHIVE_OK);
	}
	if (strcmp(key, "optional") == 0) {
		*parsed_kws |= MTREE_HAS_OPTIONAL;
		return (ARCHIVE_OK);
	}
	if (strcmp(key, "ignore") == 0) {
		/*
		 * The mtree processing is not recursive, so
		 * recursion will only happen for explicitly listed
		 * entries.
		 */
		return (ARCHIVE_OK);
	}

	val = strchr(key, '=');
	if (val == NULL) {
		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
		    "Malformed attribute \"%s\" (%d)", key, key[0]);
		return (ARCHIVE_WARN);
	}

	*val = '\0';
	++val;

	switch (key[0]) {
	case 'c':
		if (strcmp(key, "content") == 0
		    || strcmp(key, "contents") == 0) {
			parse_escapes(val, NULL);
			archive_strcpy(&mtree->contents_name, val);
			break;
		}
		if (strcmp(key, "cksum") == 0)
			break;
	case 'd':
		if (strcmp(key, "device") == 0) {
			*parsed_kws |= MTREE_HAS_DEVICE;
			return parse_device(&a->archive, entry, val);
		}
	case 'f':
		if (strcmp(key, "flags") == 0) {
			*parsed_kws |= MTREE_HAS_FFLAGS;
			archive_entry_copy_fflags_text(entry, val);
			break;
		}
	case 'g':
		if (strcmp(key, "gid") == 0) {
			*parsed_kws |= MTREE_HAS_GID;
			archive_entry_set_gid(entry, mtree_atol10(&val));
			break;
		}
		if (strcmp(key, "gname") == 0) {
			*parsed_kws |= MTREE_HAS_GNAME;
			archive_entry_copy_gname(entry, val);
			break;
		}
	case 'l':
		if (strcmp(key, "link") == 0) {
			archive_entry_copy_symlink(entry, val);
			break;
		}
	case 'm':
		if (strcmp(key, "md5") == 0 || strcmp(key, "md5digest") == 0)
			break;
		if (strcmp(key, "mode") == 0) {
			if (val[0] >= '0' && val[0] <= '9') {
				*parsed_kws |= MTREE_HAS_PERM;
				archive_entry_set_perm(entry,
				    (mode_t)mtree_atol8(&val));
			} else {
				archive_set_error(&a->archive,
				    ARCHIVE_ERRNO_FILE_FORMAT,
				    "Symbolic mode \"%s\" unsupported", val);
				return ARCHIVE_WARN;
			}
			break;
		}
	case 'n':
		if (strcmp(key, "nlink") == 0) {
			*parsed_kws |= MTREE_HAS_NLINK;
			archive_entry_set_nlink(entry,
				(unsigned int)mtree_atol10(&val));
			break;
		}
	case 'r':
		if (strcmp(key, "rmd160") == 0 ||
		    strcmp(key, "rmd160digest") == 0)
			break;
	case 's':
		if (strcmp(key, "sha1") == 0 || strcmp(key, "sha1digest") == 0)
			break;
		if (strcmp(key, "sha256") == 0 ||
		    strcmp(key, "sha256digest") == 0)
			break;
		if (strcmp(key, "sha384") == 0 ||
		    strcmp(key, "sha384digest") == 0)
			break;
		if (strcmp(key, "sha512") == 0 ||
		    strcmp(key, "sha512digest") == 0)
			break;
		if (strcmp(key, "size") == 0) {
			archive_entry_set_size(entry, mtree_atol10(&val));
			break;
		}
	case 't':
		if (strcmp(key, "tags") == 0) {
			/*
			 * Comma delimited list of tags.
			 * Ignore the tags for now, but the interface
			 * should be extended to allow inclusion/exclusion.
			 */
			break;
		}
		if (strcmp(key, "time") == 0) {
			int64_t m;
			int64_t my_time_t_max = get_time_t_max();
			int64_t my_time_t_min = get_time_t_min();
			long ns;

			*parsed_kws |= MTREE_HAS_MTIME;
			m = mtree_atol10(&val);
			/* Replicate an old mtree bug:
			 * 123456789.1 represents 123456789
			 * seconds and 1 nanosecond. */
			if (*val == '.') {
				++val;
				ns = (long)mtree_atol10(&val);
			} else
				ns = 0;
			if (m > my_time_t_max)
				m = my_time_t_max;
			else if (m < my_time_t_min)
				m = my_time_t_min;
			archive_entry_set_mtime(entry, (time_t)m, ns);
			break;
		}
		if (strcmp(key, "type") == 0) {
			switch (val[0]) {
			case 'b':
				if (strcmp(val, "block") == 0) {
					archive_entry_set_filetype(entry, AE_IFBLK);
					break;
				}
			case 'c':
				if (strcmp(val, "char") == 0) {
					archive_entry_set_filetype(entry, AE_IFCHR);
					break;
				}
			case 'd':
				if (strcmp(val, "dir") == 0) {
					archive_entry_set_filetype(entry, AE_IFDIR);
					break;
				}
			case 'f':
				if (strcmp(val, "fifo") == 0) {
					archive_entry_set_filetype(entry, AE_IFIFO);
					break;
				}
				if (strcmp(val, "file") == 0) {
					archive_entry_set_filetype(entry, AE_IFREG);
					break;
				}
			case 'l':
				if (strcmp(val, "link") == 0) {
					archive_entry_set_filetype(entry, AE_IFLNK);
					break;
				}
			default:
				archive_set_error(&a->archive,
				    ARCHIVE_ERRNO_FILE_FORMAT,
				    "Unrecognized file type \"%s\"; assuming \"file\"", val);
				archive_entry_set_filetype(entry, AE_IFREG);
				return (ARCHIVE_WARN);
			}
			*parsed_kws |= MTREE_HAS_TYPE;
			break;
		}
	case 'u':
		if (strcmp(key, "uid") == 0) {
			*parsed_kws |= MTREE_HAS_UID;
			archive_entry_set_uid(entry, mtree_atol10(&val));
			break;
		}
		if (strcmp(key, "uname") == 0) {
			*parsed_kws |= MTREE_HAS_UNAME;
			archive_entry_copy_uname(entry, val);
			break;
		}
	default:
		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
		    "Unrecognized key %s=%s", key, val);
		return (ARCHIVE_WARN);
	}
	return (ARCHIVE_OK);
}
Beispiel #9
0
/*
    open & setup audio device
    return: 1=success 0=fail
*/
static int init(int rate_hz, int channels, int format, int flags)
{
    unsigned int alsa_buffer_time = 500000; /* 0.5 s */
    unsigned int alsa_fragcount = 16;
    int err;
    int block;
    strarg_t device;
    snd_pcm_uframes_t chunk_size;
    snd_pcm_uframes_t bufsize;
    snd_pcm_uframes_t boundary;
    const opt_t subopts[] = {
      {"block", OPT_ARG_BOOL, &block, NULL},
      {"device", OPT_ARG_STR, &device, str_maxlen},
      {NULL}
    };

    char alsa_device[ALSA_DEVICE_SIZE + 1];
    // make sure alsa_device is null-terminated even when using strncpy etc.
    memset(alsa_device, 0, ALSA_DEVICE_SIZE + 1);

    mp_msg(MSGT_AO,MSGL_V,"alsa-init: requested format: %d Hz, %d channels, %x\n", rate_hz,
	channels, format);
    alsa_handler = NULL;
#if SND_LIB_VERSION >= 0x010005
    mp_msg(MSGT_AO,MSGL_V,"alsa-init: using ALSA %s\n", snd_asoundlib_version());
#else
    mp_msg(MSGT_AO,MSGL_V,"alsa-init: compiled for ALSA-%s\n", SND_LIB_VERSION_STR);
#endif

    snd_lib_error_set_handler(alsa_error_handler);

    ao_data.samplerate = rate_hz;
    ao_data.format = format;
    ao_data.channels = channels;

    switch (format)
      {
      case AF_FORMAT_S8:
	alsa_format = SND_PCM_FORMAT_S8;
	break;
      case AF_FORMAT_U8:
	alsa_format = SND_PCM_FORMAT_U8;
	break;
      case AF_FORMAT_U16_LE:
	alsa_format = SND_PCM_FORMAT_U16_LE;
	break;
      case AF_FORMAT_U16_BE:
	alsa_format = SND_PCM_FORMAT_U16_BE;
	break;
      case AF_FORMAT_AC3_LE:
      case AF_FORMAT_S16_LE:
      case AF_FORMAT_IEC61937_LE:
	alsa_format = SND_PCM_FORMAT_S16_LE;
	break;
      case AF_FORMAT_AC3_BE:
      case AF_FORMAT_S16_BE:
      case AF_FORMAT_IEC61937_BE:
	alsa_format = SND_PCM_FORMAT_S16_BE;
	break;
      case AF_FORMAT_U32_LE:
	alsa_format = SND_PCM_FORMAT_U32_LE;
	break;
      case AF_FORMAT_U32_BE:
	alsa_format = SND_PCM_FORMAT_U32_BE;
	break;
      case AF_FORMAT_S32_LE:
	alsa_format = SND_PCM_FORMAT_S32_LE;
	break;
      case AF_FORMAT_S32_BE:
	alsa_format = SND_PCM_FORMAT_S32_BE;
	break;
      case AF_FORMAT_U24_LE:
	alsa_format = SND_PCM_FORMAT_U24_3LE;
	break;
      case AF_FORMAT_U24_BE:
	alsa_format = SND_PCM_FORMAT_U24_3BE;
	break;
      case AF_FORMAT_S24_LE:
	alsa_format = SND_PCM_FORMAT_S24_3LE;
	break;
      case AF_FORMAT_S24_BE:
	alsa_format = SND_PCM_FORMAT_S24_3BE;
	break;
      case AF_FORMAT_FLOAT_LE:
	alsa_format = SND_PCM_FORMAT_FLOAT_LE;
	break;
      case AF_FORMAT_FLOAT_BE:
	alsa_format = SND_PCM_FORMAT_FLOAT_BE;
	break;
      case AF_FORMAT_MU_LAW:
	alsa_format = SND_PCM_FORMAT_MU_LAW;
	break;
      case AF_FORMAT_A_LAW:
	alsa_format = SND_PCM_FORMAT_A_LAW;
	break;

      default:
	alsa_format = SND_PCM_FORMAT_MPEG; //? default should be -1
	break;
      }

    //subdevice parsing
    // set defaults
    block = 1;
    /* switch for spdif
     * sets opening sequence for SPDIF
     * sets also the playback and other switches 'on the fly'
     * while opening the abstract alias for the spdif subdevice
     * 'iec958'
     */
    if (AF_FORMAT_IS_IEC61937(format)) {
	device.str = "iec958";
	mp_msg(MSGT_AO,MSGL_V,"alsa-spdif-init: playing AC3/iec61937/iec958, %i channels\n", channels);
    }
  else
        /* in any case for multichannel playback we should select
         * appropriate device
         */
        switch (channels) {
	case 1:
	case 2:
	  device.str = "default";
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: setup for 1/2 channel(s)\n");
	  break;
	case 4:
	  if (alsa_format == SND_PCM_FORMAT_FLOAT_LE)
	    // hack - use the converter plugin
	    device.str = "plug:surround40";
	  else
	    device.str = "surround40";
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: device set to surround40\n");
	  break;
	case 6:
	  if (alsa_format == SND_PCM_FORMAT_FLOAT_LE)
	    device.str = "plug:surround51";
	  else
	    device.str = "surround51";
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: device set to surround51\n");
	  break;
	case 8:
	  if (alsa_format == SND_PCM_FORMAT_FLOAT_LE)
	    device.str = "plug:surround71";
	  else
	    device.str = "surround71";
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: device set to surround71\n");
	  break;
	default:
	  device.str = "default";
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_ChannelsNotSupported,channels);
        }
    device.len = strlen(device.str);
    if (subopt_parse(ao_subdevice, subopts) != 0) {
        print_help();
        return 0;
    }
    parse_device(alsa_device, device.str, device.len);

    mp_msg(MSGT_AO,MSGL_V,"alsa-init: using device %s\n", alsa_device);

    if (!alsa_handler) {
      int open_mode = block ? 0 : SND_PCM_NONBLOCK;
      int isac3 =  AF_FORMAT_IS_IEC61937(format);
      //modes = 0, SND_PCM_NONBLOCK, SND_PCM_ASYNC
      mp_msg(MSGT_AO,MSGL_V,"alsa-init: opening device in %sblocking mode\n", block ? "" : "non-");
      if ((err = try_open_device(alsa_device, open_mode, isac3)) < 0)
	{
	  if (err != -EBUSY && !block) {
	    mp_msg(MSGT_AO,MSGL_INFO,MSGTR_AO_ALSA_OpenInNonblockModeFailed);
	    if ((err = try_open_device(alsa_device, 0, isac3)) < 0) {
	      mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_PlaybackOpenError, snd_strerror(err));
	      return 0;
	    }
	  } else {
	    mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_PlaybackOpenError, snd_strerror(err));
	    return 0;
	  }
	}

      if ((err = snd_pcm_nonblock(alsa_handler, 0)) < 0) {
         mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_ErrorSetBlockMode, snd_strerror(err));
      } else {
	mp_msg(MSGT_AO,MSGL_V,"alsa-init: device reopened in blocking mode\n");
      }

      snd_pcm_hw_params_alloca(&alsa_hwparams);
      snd_pcm_sw_params_alloca(&alsa_swparams);

      // setting hw-parameters
      if ((err = snd_pcm_hw_params_any(alsa_handler, alsa_hwparams)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetInitialParameters,
		 snd_strerror(err));
	  return 0;
	}

      err = snd_pcm_hw_params_set_access(alsa_handler, alsa_hwparams,
					 SND_PCM_ACCESS_RW_INTERLEAVED);
      if (err < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetAccessType,
	       snd_strerror(err));
	return 0;
      }

      /* workaround for nonsupported formats
	 sets default format to S16_LE if the given formats aren't supported */
      if ((err = snd_pcm_hw_params_test_format(alsa_handler, alsa_hwparams,
                                             alsa_format)) < 0)
      {
         mp_msg(MSGT_AO,MSGL_INFO,
		MSGTR_AO_ALSA_FormatNotSupportedByHardware, af_fmt2str_short(format));
         alsa_format = SND_PCM_FORMAT_S16_LE;
         if (AF_FORMAT_IS_AC3(ao_data.format))
           ao_data.format = AF_FORMAT_AC3_LE;
         else if (AF_FORMAT_IS_IEC61937(ao_data.format))
           ao_data.format = AF_FORMAT_IEC61937_LE;
         else
         ao_data.format = AF_FORMAT_S16_LE;
      }

      if ((err = snd_pcm_hw_params_set_format(alsa_handler, alsa_hwparams,
					      alsa_format)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetFormat,
		 snd_strerror(err));
	  return 0;
	}

      if ((err = snd_pcm_hw_params_set_channels_near(alsa_handler, alsa_hwparams,
						     &ao_data.channels)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetChannels,
		 snd_strerror(err));
	  return 0;
	}

      /* workaround for buggy rate plugin (should be fixed in ALSA 1.0.11)
         prefer our own resampler, since that allows users to choose the resampler,
         even per file if desired */
#if SND_LIB_VERSION >= 0x010009
      if ((err = snd_pcm_hw_params_set_rate_resample(alsa_handler, alsa_hwparams,
						     0)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToDisableResampling,
		 snd_strerror(err));
	  return 0;
	}
#endif

      if ((err = snd_pcm_hw_params_set_rate_near(alsa_handler, alsa_hwparams,
						 &ao_data.samplerate, NULL)) < 0)
        {
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetSamplerate2,
		 snd_strerror(err));
	  return 0;
        }

      bytes_per_sample = af_fmt2bits(ao_data.format) / 8;
      bytes_per_sample *= ao_data.channels;
      ao_data.bps = ao_data.samplerate * bytes_per_sample;

	if ((err = snd_pcm_hw_params_set_buffer_time_near(alsa_handler, alsa_hwparams,
							  &alsa_buffer_time, NULL)) < 0)
	  {
	    mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetBufferTimeNear,
		   snd_strerror(err));
	    return 0;
	  }

	if ((err = snd_pcm_hw_params_set_periods_near(alsa_handler, alsa_hwparams,
						      &alsa_fragcount, NULL)) < 0) {
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetPeriods,
		 snd_strerror(err));
	  return 0;
	}

      /* finally install hardware parameters */
      if ((err = snd_pcm_hw_params(alsa_handler, alsa_hwparams)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetHwParameters,
		 snd_strerror(err));
	  return 0;
	}
      // end setting hw-params


      // gets buffersize for control
      if ((err = snd_pcm_hw_params_get_buffer_size(alsa_hwparams, &bufsize)) < 0)
	{
	  mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetBufferSize, snd_strerror(err));
	  return 0;
	}
      else {
	ao_data.buffersize = bufsize * bytes_per_sample;
	  mp_msg(MSGT_AO,MSGL_V,"alsa-init: got buffersize=%i\n", ao_data.buffersize);
      }

      if ((err = snd_pcm_hw_params_get_period_size(alsa_hwparams, &chunk_size, NULL)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetPeriodSize, snd_strerror(err));
	return 0;
      } else {
	mp_msg(MSGT_AO,MSGL_V,"alsa-init: got period size %li\n", chunk_size);
      }
      ao_data.outburst = chunk_size * bytes_per_sample;

      /* setting software parameters */
      if ((err = snd_pcm_sw_params_current(alsa_handler, alsa_swparams)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetSwParameters,
	       snd_strerror(err));
	return 0;
      }
#if SND_LIB_VERSION >= 0x000901
      if ((err = snd_pcm_sw_params_get_boundary(alsa_swparams, &boundary)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetBoundary,
	       snd_strerror(err));
	return 0;
      }
#else
      boundary = 0x7fffffff;
#endif
      /* start playing when one period has been written */
      if ((err = snd_pcm_sw_params_set_start_threshold(alsa_handler, alsa_swparams, chunk_size)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetStartThreshold,
	       snd_strerror(err));
	return 0;
      }
      /* disable underrun reporting */
      if ((err = snd_pcm_sw_params_set_stop_threshold(alsa_handler, alsa_swparams, boundary)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetStopThreshold,
	       snd_strerror(err));
	return 0;
      }
#if SND_LIB_VERSION >= 0x000901
      /* play silence when there is an underrun */
      if ((err = snd_pcm_sw_params_set_silence_size(alsa_handler, alsa_swparams, boundary)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToSetSilenceSize,
	       snd_strerror(err));
	return 0;
      }
#endif
      if ((err = snd_pcm_sw_params(alsa_handler, alsa_swparams)) < 0) {
	mp_msg(MSGT_AO,MSGL_ERR,MSGTR_AO_ALSA_UnableToGetSwParameters,
	       snd_strerror(err));
	return 0;
      }
      /* end setting sw-params */

      mp_msg(MSGT_AO,MSGL_V,"alsa: %d Hz/%d channels/%d bpf/%d bytes buffer/%s\n",
	     ao_data.samplerate, ao_data.channels, (int)bytes_per_sample, ao_data.buffersize,
	     snd_pcm_format_description(alsa_format));

    } // end switch alsa_handler (spdif)
    alsa_can_pause = snd_pcm_hw_params_can_pause(alsa_hwparams);
    return 1;
} // end init
Beispiel #10
0
int main (int argc, char **argv)
{
    ssize_t ret_size;
    struct stat st;
    int ret, flags;

    int part_request;
    long long this_time;
    double part_min, part_max, time_min, time_max;
    double time_sum, time_sum2, time_mdev, time_avg;
    double part_sum, part_sum2, part_mdev, part_avg;
    long long time_now, time_next, period_deadline;

    setvbuf(stdout, NULL, _IOLBF, 0);

    parse_options(argc, argv);

    interval_ts.tv_sec = interval / 1000000;
    interval_ts.tv_nsec = (interval % 1000000) * 1000;

    if (!size)
        size = default_size;

    if (size <= 0)
        errx(1, "request size must be greather than zero");

#ifdef MAX_RW_COUNT
    if (size > MAX_RW_COUNT)
        warnx("this platform supports requests %u bytes at most",
              MAX_RW_COUNT);
#endif

    if (wsize)
        temp_wsize = wsize;
    else if (size > temp_wsize)
        temp_wsize = size;

    flags = O_RDONLY;

#if !defined(HAVE_POSIX_FADVICE) && !defined(HAVE_NOCACHE_IO)
# if defined(HAVE_DIRECT_IO)
    direct |= !cached;
# else
    if (!cached && !write_test) {
        warnx("non-cached read I/O not supported by this platform");
        warnx("you can use write I/O to get reliable results");
        cached = 1;
    }
# endif
#endif

    if (write_test) {
        flags = O_RDWR;
        make_request = do_pwrite;
    }

    if (async)
        aio_setup();

    if (direct)
#ifdef HAVE_DIRECT_IO
        flags |= O_DIRECT;
#else
        errx(1, "direct I/O not supported by this platform");
#endif

#ifdef __MINGW32__
    flags |= O_BINARY;
#endif

    if (stat(path, &st))
        err(2, "stat \"%s\" failed", path);

    if (!S_ISDIR(st.st_mode) && write_test && write_test < 3)
        errx(2, "think twice, then use -WWW to shred this target");

    if (S_ISDIR(st.st_mode) || S_ISREG(st.st_mode)) {
        if (S_ISDIR(st.st_mode))
            st.st_size = offset + temp_wsize;
        parse_device(st.st_dev);
    } else if (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)) {
        fd = open(path, flags);
        if (fd < 0)
            err(2, "failed to open \"%s\"", path);

        if (get_device_size(fd, &st)) {
            if (!S_ISCHR(st.st_mode))
                err(2, "block get size ioctl failed");
            st.st_size = offset + temp_wsize;
            fstype = "character";
            device = "device";
        } else {
            device_size = st.st_size;
            fstype = "block";
            device = "device ";
        }

        if (!cached && write_test && fdatasync(fd)) {
            warnx("fdatasync not supported by \"%s\", "
                  "enable cached requests", path);
            cached = 1;
        }
    } else {
        errx(2, "unsupported destination: \"%s\"", path);
    }

    if (wsize > st.st_size || offset > st.st_size - wsize)
        errx(2, "target is too small for this");

    if (!wsize)
        wsize = st.st_size - offset;

    if (size > wsize)
        errx(2, "request size is too big for this target");

    ret = posix_memalign(&buf, 0x1000, size);
    if (ret)
        errx(2, "buffer allocation failed");

    random_memory(buf, size);

    if (S_ISDIR(st.st_mode)) {
        fd = create_temp(path, "ioping.tmp");
        if (fd < 0)
            err(2, "failed to create temporary file at \"%s\"", path);
        if (keep_file) {
            if (fstat(fd, &st))
                err(2, "fstat at \"%s\" failed", path);
            if (st.st_size >= offset + wsize)
#ifndef __MINGW32__
                if (st.st_blocks >= (st.st_size + 511) / 512)
#endif
                    goto skip_preparation;
        }
        for (woffset = 0 ; woffset < wsize ; woffset += ret_size) {
            ret_size = size;
            if (woffset + ret_size > wsize)
                ret_size = wsize - woffset;
            if (woffset)
                random_memory(buf, ret_size);
            ret_size = pwrite(fd, buf, ret_size, offset + woffset);
            if (ret_size <= 0)
                err(2, "preparation write failed");
        }
skip_preparation:
        if (fsync(fd))
            err(2, "fsync failed");
    } else if (S_ISREG(st.st_mode)) {
        fd = open(path, flags);
        if (fd < 0)
            err(2, "failed to open \"%s\"", path);
    }

    if (!cached) {
#ifdef HAVE_POSIX_FADVICE
        ret = posix_fadvise(fd, offset, wsize, POSIX_FADV_RANDOM);
        if (ret)
            err(2, "fadvise failed");
#endif
#ifdef HAVE_NOCACHE_IO
        ret = fcntl(fd, F_NOCACHE, 1);
        if (ret)
            err(2, "fcntl nocache failed");
#endif
    }

    srandom(now());

    if (deadline)
        deadline += now();

    set_signal();

    request = 0;
    woffset = 0;

    part_request = 0;
    part_min = time_min = LLONG_MAX;
    part_max = time_max = LLONG_MIN;
    part_sum = time_sum = 0;
    part_sum2 = time_sum2 = 0;

    time_now = now();
    period_deadline = time_now + period_time;

    while (!exiting) {
        request++;
        part_request++;

        if (randomize)
            woffset = random() % (wsize / size) * size;

#ifdef HAVE_POSIX_FADVICE
        if (!cached) {
            ret = posix_fadvise(fd, offset + woffset, size,
                                POSIX_FADV_DONTNEED);
            if (ret)
                err(3, "fadvise failed");
        }
#endif

        if (write_test)
            shake_memory(buf, size);

        this_time = now();

        ret_size = make_request(fd, buf, size, offset + woffset);
        if (ret_size < 0) {
            if (errno != EINTR)
                err(3, "request failed");
        } else if (ret_size < size)
            warnx("request returned less than expected: %zu", ret_size);
        else if (ret_size > size)
            errx(3, "request returned more than expected: %zu", ret_size);

        time_now = now();
        this_time = time_now - this_time;
        time_next = time_now + interval;

        part_sum += this_time;
        part_sum2 += this_time * this_time;
        if (this_time < part_min)
            part_min = this_time;
        if (this_time > part_max)
            part_max = this_time;

        if (!quiet) {
            print_size(ret_size);
            printf(" %s %s (%s %s", write_test ? "to" : "from",
                   path, fstype, device);
            if (device_size)
                print_size(device_size);
            printf("): request=%d time=", request);
            print_time(this_time);
            printf("\n");
        }

        if ((period_request && (part_request >= period_request)) ||
                (period_time && (time_next >= period_deadline))) {
            part_avg = part_sum / part_request;
            part_mdev = sqrt(part_sum2 / part_request - part_avg * part_avg);

            printf("%d %.0f %.0f %.0f %.0f %.0f %.0f %.0f\n",
                   part_request, part_sum,
                   1000000. * part_request / part_sum,
                   1000000. * part_request * size / part_sum,
                   part_min, part_avg,
                   part_max, part_mdev);

            time_sum += part_sum;
            time_sum2 += part_sum2;
            if (part_min < time_min)
                time_min = part_min;
            if (part_max > time_max)
                time_max = part_max;
            part_min = LLONG_MAX;
            part_max = LLONG_MIN;
            part_sum = part_sum2 = 0;
            part_request = 0;

            period_deadline = time_now + period_time;
        }

        if (!randomize) {
            woffset += size;
            if (woffset + size > wsize)
                woffset = 0;
        }

        if (exiting)
            break;

        if (stop_at_request && request >= stop_at_request)
            break;

        if (deadline && time_next >= deadline)
            break;

        if (interval)
            nanosleep(&interval_ts, NULL);
    }

    time_sum += part_sum;
    time_sum2 += part_sum2;
    if (part_min < time_min)
        time_min = part_min;
    if (part_max > time_max)
        time_max = part_max;

    time_avg = time_sum / request;
    time_mdev = sqrt(time_sum2 / request - time_avg * time_avg);

    if (batch_mode) {
        printf("%d %.0f %.0f %.0f %.0f %.0f %.0f %.0f\n",
               request, time_sum,
               1000000. * request / time_sum,
               1000000. * request * size / time_sum,
               time_min, time_avg,
               time_max, time_mdev);
    } else if (!quiet || (!period_time && !period_request)) {
        printf("\n--- %s (%s %s", path, fstype, device);
        if (device_size)
            print_size(device_size);
        printf(") ioping statistics ---\n");
        print_int(request);
        printf(" requests completed in ");
        print_time(time_sum);
        printf(", ");
        print_size((long long)request * size);
        printf(" %s, ", write_test ? "written" : "read");
        print_int(1000000. * request / time_sum);
        printf(" iops, ");
        print_size(1000000. * request * size / time_sum);
        printf("/s\n");
        printf("min/avg/max/mdev = ");
        print_time(time_min);
        printf(" / ");
        print_time(time_avg);
        printf(" / ");
        print_time(time_max);
        printf(" / ");
        print_time(time_mdev);
        printf("\n");
    }

    return 0;
}
Beispiel #11
0
int main(int argc, char *argv[])
{
    unsigned char buffer[4096] = {0};
    int bufferLen = 0;
    int bytesReceived = 0;
    int bytesWritten = 0;
    int timer = 0;
    unsigned int deviceId[3];
    Command command;
    int extra = -1;
    
    if (argc < 3)
    {
        print_error("Usage: insteon deviceId [on|off|status|temp_ambient]\n");
        return 1;
    }

    // Parse arguments
    parse_device(argv[1], deviceId);
    command = parse_command(argv[2]);
    if (argc > 3)
        extra = parse_extra(argv[3]);

    if (command < 0)
    {
        print_error("Invalid command name!\n");
        return 1;
    }

    print_debug("*****************\n");
    print_debug("Device: %s\n", argv[1]);
    print_debug("Command: %s\n", argv[2]);
    if (argc > 3)
        print_debug("Extra: %s\n", argv[3]);
    print_debug("*****************\n");

    if (acquire_lock())
    {
        print_error("Timeout while acquiring lock!\n");
        return 1;
    }
    
    print_debug("Opening comport\n");

    if(OpenComport(comport, 19200))
    {
        print_error("Can not open comport\n");
        release_lock();
        return 1;
    }
    
    // Send command
    bytesWritten = send_command(deviceId, command, extra);
    if (bytesWritten < 0)
    {
        print_error("Invalid command or internal error!\n");
        goto return_error;
    }

    // Wait for response
    while(1)
    {
        bytesReceived = PollComport(16, buffer + bufferLen, 4095);
        //print_debug("br=%d bl=%d  ", bytesReceived, bufferLen);
        bufferLen += bytesReceived;
        //print_debug("br=%d bl=%d\n", bytesReceived, bufferLen);
        if(bytesReceived > 0)
        {
            int i;
            timer = 0;
            print_debug("received %i bytes: (%i total)", bytesReceived, bufferLen);
            for(i=0; i < bufferLen; i++)
            {
                print_debug("%02X ", buffer[i]);
            }
            print_debug("\n");

            if (bufferLen > bytesWritten)
            {
                unsigned int ack = *(buffer + bytesWritten);
                unsigned char* message = buffer + bytesWritten + 1;
                int messageLen = bufferLen - bytesWritten - 1;
                
                if (ack != CMD_ACK)
                {
                    print_error("Message not acknowledged!\n");
                    goto return_error;
                }
                
                if (messageLen > 1)
                {
                    if (message[0] == CMD_PREFIX)
                    {
                        if (message[1] == CMD_INSTEON_STD_RECEIVED)
                        {
                            if (messageLen >= 11)
                            {
                                static int resultCounter = 0;
                                
                                print_debug("Insteon standard message received!\n");
                                if(parse_message(command, message))
                                {
                                    goto return_error;
                                }
                                
                                if(command == CMD_TEMP_GET_SETPOINT && resultCounter == 0 && extra == 3)
                                {
                                    resultCounter++;
                                    bufferLen -= 11;
                                }
                                else
                                {
                                    goto return_success;
                                }
                            }
                        }
                        else if (message[1] == CMD_INSTEON_EXT_RECEIVED)
                        {
                            if (messageLen >= 25)
                            {
                                print_debug("Insteon extended message received!\n");
                                if(parse_message(command, message))
                                {
                                    goto return_error;
                                }
                                goto return_success;
                            }
                        }
                        else if (message[1] == CMD_X10_RECEIVED)
                        {
                            if (messageLen >= 4)
                            {
                                print_debug("X10 message received!\n");
                                if(parse_message(command, message))
                                {
                                    goto return_error;
                                }
                                goto return_success;
                            }
                        }
                        else
                        {
                            print_error("Unexpected message received! '");
                            for(i=0; i < messageLen; i++)
                            {
                                print_error("%02X ", message[i]);
                            }
                            print_error("'\n");
                            goto return_error;
                        }
                    }
                    else
                    {
                        print_error("Unexpected message header received! '");
                        for(i=0; i < messageLen; i++)
                        {
                            print_error("%02X ", message[i]);
                        }
                        print_error("'\n");
                        goto return_error;
                    }
                }
            }
        }

        usleep(250);
        timer++;
        if (timer > 4000)
        {
            print_error("Timeout while waiting for bytes!\n");
            goto return_error;
        }
    }

return_success:
    CloseComport(16);
    release_lock();
    return 0;
return_error:
    CloseComport(16);
    release_lock();
    return 1;
}
Beispiel #12
0
/*
 * This routine is called from preenlib the first time. It is then
 * recursively called through preen_subdev.
 *
 * The argument passed in (uname) starts with the special device from
 * /etc/vfstab. Recursive calls pass in the underlying physical device
 * names.
 */
void
preen_build_devs(
	char		*uname,		/* name of metadevice */
	struct dk_cinfo	*dkiop,		/* associated controller info */
	void		*dp		/* magic info */
)
{
	char		*setname = NULL;
	char		*tname = NULL;
	mdsetname_t	*sp;
	mdname_t	*namep;		/* metadevice name */
	mdnamelist_t	*nlp = NULL;	/* list of real devices */
	mdnamelist_t	*p;
	devid_nmlist_t	*nm_list = NULL;
	md_error_t	status = mdnullerror;
	md_error_t	*ep = &status;
	int		ep_valid = 0;	/* does ep contain a real error */
	struct stat	statb;
	static int	md_major = -1;
	side_t		sideno;

	/*
	 * The rest of the code in this library can't work within a
	 * non-global zone so we just return the top level metadevice back
	 * to be fscked.
	 */
	if (getzoneid() != GLOBAL_ZONEID) {
		preen_addunit(dp, dkiop->dki_dname, NULL, NULL,
		    dkiop->dki_unit);
		return;
	}

	if (stat(uname, &statb) != 0)
		return;

	if (md_major == -1 &&
		get_major_from_n2m(MD_MODULE, &md_major) != 0)
		return;

	/*
	 * If the path passed in is not a metadevice, then add that
	 * device to the list (preen_addunit) since it has to be a
	 * physical device.
	 */

	if (major(statb.st_rdev) != md_major) {
		preen_addunit(dp, dkiop->dki_dname, NULL, NULL,
		    dkiop->dki_unit);
		return;
	}
	/*
	 * Bind to the cluster library
	 */

	if (sdssc_bind_library() == SDSSC_ERROR)
		return;

	if (md_init_daemon("fsck", ep) != 0) {
		ep_valid = 1;
		goto out;
	}

	/*
	 * parse the path name to get the diskset name.
	 */
	parse_device(NULL, uname, &tname, &setname);
	Free(tname);
	if ((sp = metasetname(setname, ep)) == NULL) {
		ep_valid = 1;
		goto out;
	}

	/* check for ownership */
	if (meta_check_ownership(sp, ep) != 0) {
		/*
		 * Don't own the set but we are here implies
		 * that this is a clustered proxy device. Simply add
		 * the unit.
		 */
		preen_addunit(dp, dkiop->dki_dname, NULL, NULL,
		    dkiop->dki_unit);
		ep_valid = 1;
		goto out;
	}

	/*
	 * get list of underlying physical devices.
	 */
	if ((namep = metaname(&sp, uname, UNKNOWN, ep)) == NULL) {
		ep_valid = 1;
		goto out;
	}

	if (namep->dev == NODEV64) {
		goto out;
	}

	if (meta_getdevs(sp, namep, &nlp, ep) != 0) {
		ep_valid = 1;
		goto out;
	}

	if ((sideno = getmyside(sp, ep)) == MD_SIDEWILD) {
		ep_valid = 1;
		goto out;
	}

	/* gather and add the underlying devs */
	for (p = nlp; (p != NULL); p = p->next) {
		mdname_t	*devnp = p->namep;
		int		fd;
		struct dk_cinfo	cinfo;
		ddi_devid_t	md_did;
		char		*devname;
		char		*minor_name = NULL;
		char		mname[MAXPATHLEN];

		/*
		 * we don't want to use the rname anymore because
		 * that may have changed. Use the device id information
		 * to find the correct ctd name and open based on that.
		 * If there isn't a devid or we have a did device, then
		 * use the rname. In clustering, it's corrected for us.
		 * If no devid it's at least worth a try.
		 */
		if (((md_did = meta_getdidbykey(sp->setno, sideno,
		    devnp->key, ep)) == NULL) || ((minor_name =
		    meta_getdidminorbykey(sp->setno, sideno,
		    devnp->key, ep)) == NULL)) {
			devname = devnp->rname;
			if (md_did)
				Free(md_did);
		} else {
			if (strstr(minor_name, ",raw") == NULL) {
				(void) snprintf(mname, MAXPATHLEN, "%s,raw",
				    minor_name);
			} else {
				(void) snprintf(mname, MAXPATHLEN, "%s",
				    minor_name);
			}

			/*
			 * We need to make sure we call this with a specific
			 * mname (raw mname) so that we get the exact slice
			 * with the given device id. Otherwise we could try
			 * to open a slice that doesn't really exist.
			 */
			if (meta_deviceid_to_nmlist("/dev", md_did,
			    mname, &nm_list) != 0) {
				(void) mdsyserror(ep, errno, devnp->rname);
				ep_valid = 1;
				Free(md_did);
				Free(minor_name);
				goto out;
			}
			devname = Strdup(nm_list->devname);
			Free(md_did);
			Free(minor_name);
			devid_free_nmlist(nm_list);
		}
		/* get device name and (real) cinfo */
		if ((fd = open(devname, O_RDONLY, 0)) < 0) {
			(void) mdsyserror(ep, errno, devname);
			ep_valid = 1;
			/*
			 * We need to scan all sub devices even if some fail
			 * since exit here would end up in not finishing fsck
			 * on all devices and prevent us from going into
			 * multiuser mode.
			 */
			continue;
		}

		if (ioctl(fd, DKIOCINFO, &cinfo) != 0) {
			(void) mdsyserror(ep, errno, devname);
			(void) close(fd);
			ep_valid = 1;
			/* Continue here too. See comment from before */
			continue;
		}
		(void) close(fd);	/* sd/ssd bug */

		/*
		 * preen_subdev fails when the device name has been
		 * resolved to the physical layer. Hence it is added
		 * to preen_addunit.
		 */
		if (preen_subdev(devname, &cinfo, dp) != 0) {
			preen_addunit(dp, cinfo.dki_dname, NULL, NULL,
			    cinfo.dki_unit);
		}
	}

	/* cleanup, if we fail, just add this composite device to the list */
out:
	if (setname != NULL)
		Free(setname);
	if (ep_valid != 0) {
		mde_perror(&status, "");
		mdclrerror(&status);
	}
	metafreenamelist(nlp);
}