Пример #1
0
int main(void)
{
    dprint(123);
    dprint(123.0);
    return 0;
}
Пример #2
0
static void
setalt(Dev *d, int ifcid, int altid)
{
	if(usbcmd(d, Rh2d|Rstd|Riface, Rsetiface, altid, ifcid, nil, 0) < 0)
		dprint(2, "%s: setalt ifc %d alt %d: %r\n", argv0, ifcid, altid);
}
Пример #3
0
void
usage(void)
{
    dprint("usage: sam [-d] [-t samterm] [-s sam name] -r machine\n");
    exits("usage");
}
Пример #4
0
/* Ok, the only reason for not merging this with mutt_copy_header()
 * below is to avoid creating a HEADER structure in message_handler().
 * Also, this one will wrap headers much more aggressively than the other one.
 */
int
mutt_copy_hdr (FILE *in, FILE *out, LOFF_T off_start, LOFF_T off_end, int flags,
	       const char *prefix)
{
  int from = 0;
  int this_is_from;
  int ignore = 0;
  char buf[LONG_STRING]; /* should be long enough to get most fields in one pass */
  char *nl;
  LIST *t;
  char **headers;
  int hdr_count;
  int x;
  char *this_one = NULL;
  size_t this_one_len = 0;
  int error;

  if (ftello (in) != off_start)
    fseeko (in, off_start, 0);

  buf[0] = '\n';
  buf[1] = 0;

  if ((flags & (CH_REORDER | CH_WEED | CH_MIME | CH_DECODE | CH_PREFIX | CH_WEED_DELIVERED)) == 0)
  {
    /* Without these flags to complicate things
     * we can do a more efficient line to line copying
     */
    while (ftello (in) < off_end)
    {
      nl = strchr (buf, '\n');

      if ((fgets (buf, sizeof (buf), in)) == NULL)
	break;

      /* Is it the begining of a header? */
      if (nl && buf[0] != ' ' && buf[0] != '\t')
      {
	ignore = 1;
	if (!from && mutt_strncmp ("From ", buf, 5) == 0)
	{
	  if ((flags & CH_FROM) == 0)
	    continue;
	  from = 1;
	}
	else if (flags & (CH_NOQFROM) &&
			ascii_strncasecmp (">From ", buf, 6) == 0)
		continue;

	else if (buf[0] == '\n' || (buf[0] == '\r' && buf[1] == '\n'))
	  break; /* end of header */

	if ((flags & (CH_UPDATE | CH_XMIT | CH_NOSTATUS)) &&
	    (ascii_strncasecmp ("Status:", buf, 7) == 0 ||
	     ascii_strncasecmp ("X-Status:", buf, 9) == 0))
	  continue;
	if ((flags & (CH_UPDATE_LEN | CH_XMIT | CH_NOLEN)) &&
	    (ascii_strncasecmp ("Content-Length:", buf, 15) == 0 ||
	     ascii_strncasecmp ("Lines:", buf, 6) == 0))
	  continue;
	if ((flags & CH_UPDATE_REFS) &&
	    ascii_strncasecmp ("References:", buf, 11) == 0)
	  continue;
	if ((flags & CH_UPDATE_IRT) &&
	    ascii_strncasecmp ("In-Reply-To:", buf, 12) == 0)
	  continue;
	ignore = 0;
      }

      if (!ignore && fputs (buf, out) == EOF)
	return (-1);
    }
    return 0;
  }

  hdr_count = 1;
  x = 0;
  error = FALSE;

  /* We are going to read and collect the headers in an array
   * so we are able to do re-ordering.
   * First count the number of entries in the array
   */
  if (flags & CH_REORDER)
  {
    for (t = HeaderOrderList; t; t = t->next)
    {
      dprint(3, (debugfile, "Reorder list: %s\n", t->data));
      hdr_count++;
    }
  }

  dprint (1, (debugfile, "WEED is %s\n", (flags & CH_WEED) ? "Set" : "Not"));

  headers = safe_calloc (hdr_count, sizeof (char *));

  /* Read all the headers into the array */
  while (ftello (in) < off_end)
  {
    nl = strchr (buf, '\n');

    /* Read a line */
    if ((fgets (buf, sizeof (buf), in)) == NULL)
      break;

    /* Is it the begining of a header? */
    if (nl && buf[0] != ' ' && buf[0] != '\t')
    {
      /* Do we have anything pending? */
      if (this_one)
      {
	if (flags & CH_DECODE) 
	{
	  if (!address_header_decode (&this_one))
	    rfc2047_decode (&this_one);
	  this_one_len = mutt_strlen (this_one);
	}

	if (!headers[x])
	  headers[x] = this_one;
	else 
	{
	  int hlen = mutt_strlen (headers[x]);

	  safe_realloc (&headers[x], hlen + this_one_len + sizeof (char));
	  strcat (headers[x] + hlen, this_one); /* __STRCAT_CHECKED__ */
	  FREE (&this_one);
	}

	this_one = NULL;
      }

      ignore = 1;
      this_is_from = 0;
      if (!from && mutt_strncmp ("From ", buf, 5) == 0)
      {
	if ((flags & CH_FROM) == 0)
	  continue;
	this_is_from = from = 1;
      }
      else if (buf[0] == '\n' || (buf[0] == '\r' && buf[1] == '\n'))
	break; /* end of header */

      /* note: CH_FROM takes precedence over header weeding. */
      if (!((flags & CH_FROM) && (flags & CH_FORCE_FROM) && this_is_from) &&
	  (flags & CH_WEED) &&
	  mutt_matches_ignore (buf, Ignore) &&
	  !mutt_matches_ignore (buf, UnIgnore))
	continue;
      if ((flags & CH_WEED_DELIVERED) &&
	  ascii_strncasecmp ("Delivered-To:", buf, 13) == 0)
	continue;
      if ((flags & (CH_UPDATE | CH_XMIT | CH_NOSTATUS)) &&
	  (ascii_strncasecmp ("Status:", buf, 7) == 0 ||
	   ascii_strncasecmp ("X-Status:", buf, 9) == 0))
	continue;
      if ((flags & (CH_UPDATE_LEN | CH_XMIT | CH_NOLEN)) &&
	  (ascii_strncasecmp ("Content-Length:", buf, 15) == 0 ||
	   ascii_strncasecmp ("Lines:", buf, 6) == 0))
	continue;
      if ((flags & CH_MIME) &&
	  ((ascii_strncasecmp ("content-", buf, 8) == 0 &&
	    (ascii_strncasecmp ("transfer-encoding:", buf + 8, 18) == 0 ||
	     ascii_strncasecmp ("type:", buf + 8, 5) == 0)) ||
	   ascii_strncasecmp ("mime-version:", buf, 13) == 0))
	continue;
      if ((flags & CH_UPDATE_REFS) &&
	  ascii_strncasecmp ("References:", buf, 11) == 0)
	continue;
      if ((flags & CH_UPDATE_IRT) &&
	  ascii_strncasecmp ("In-Reply-To:", buf, 12) == 0)
	continue;

      /* Find x -- the array entry where this header is to be saved */
      if (flags & CH_REORDER)
      {
	for (t = HeaderOrderList, x = 0 ; (t) ; t = t->next, x++)
	{
	  if (!ascii_strncasecmp (buf, t->data, mutt_strlen (t->data)))
	  {
	    dprint(2, (debugfile, "Reorder: %s matches %s\n", t->data, buf));
	    break;
	  }
	}
      }

      ignore = 0;
    } /* If beginning of header */

    if (!ignore)
    {
      dprint (2, (debugfile, "Reorder: x = %d; hdr_count = %d\n", x, hdr_count));
      if (!this_one) {
	this_one = safe_strdup (buf);
	this_one_len = mutt_strlen (this_one);
      } else {
	int blen = mutt_strlen (buf);

	safe_realloc (&this_one, this_one_len + blen + sizeof (char));
	strcat (this_one + this_one_len, buf); /* __STRCAT_CHECKED__ */
	this_one_len += blen;
      }
    }
  } /* while (ftello (in) < off_end) */

  /* Do we have anything pending?  -- XXX, same code as in above in the loop. */
  if (this_one)
  {
    if (flags & CH_DECODE) 
    {
      if (!address_header_decode (&this_one))
	rfc2047_decode (&this_one);
    }
    
    if (!headers[x])
      headers[x] = this_one;
    else 
    {
      int hlen = mutt_strlen (headers[x]);

      safe_realloc (&headers[x], hlen + this_one_len + sizeof (char));
      strcat (headers[x] + hlen, this_one); /* __STRCAT_CHECKED__ */
      FREE (&this_one);
    }

    this_one = NULL;
  }

  /* Now output the headers in order */
  for (x = 0; x < hdr_count; x++)
  {
    if (headers[x])
    {
#if 0
      if (flags & CH_DECODE)
	rfc2047_decode (&headers[x]);
#endif

      /* We couldn't do the prefixing when reading because RFC 2047
       * decoding may have concatenated lines.
       */
      
      if (flags & (CH_DECODE|CH_PREFIX))
      {
	if (mutt_write_one_header (out, 0, headers[x], 
				   flags & CH_PREFIX ? prefix : 0, mutt_term_width (Wrap), flags) == -1)
	{
	  error = TRUE;
	  break;
	}
      }
      else
      {      
	if (fputs (headers[x], out) == EOF)
	{
	  error = TRUE;
	  break;
	}
      }
    }
  }

  /* Free in a separate loop to be sure that all headers are freed
   * in case of error. */
  for (x = 0; x < hdr_count; x++)
    FREE (&headers[x]);
  FREE (&headers);

  if (error)
    return (-1);
  return (0);
}
Пример #5
0
static void fill_sha512(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_sha512 *vh = hdr_priv(hdr);
	struct fio_sha512_ctx sha512_ctx = {
		.buf = vh->sha512,
	};

	fio_sha512_init(&sha512_ctx);
	fio_sha512_update(&sha512_ctx, p, len);
}

static void fill_sha256(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_sha256 *vh = hdr_priv(hdr);
	struct fio_sha256_ctx sha256_ctx = {
		.buf = vh->sha256,
	};

	fio_sha256_init(&sha256_ctx);
	fio_sha256_update(&sha256_ctx, p, len);
}

static void fill_sha1(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_sha1 *vh = hdr_priv(hdr);
	struct fio_sha1_ctx sha1_ctx = {
		.H = vh->sha1,
	};

	fio_sha1_init(&sha1_ctx);
	fio_sha1_update(&sha1_ctx, p, len);
}

static void fill_crc7(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc7 *vh = hdr_priv(hdr);

	vh->crc7 = fio_crc7(p, len);
}

static void fill_crc16(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc16 *vh = hdr_priv(hdr);

	vh->crc16 = fio_crc16(p, len);
}

static void fill_crc32(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc32 *vh = hdr_priv(hdr);

	vh->crc32 = fio_crc32(p, len);
}

static void fill_crc32c(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc32 *vh = hdr_priv(hdr);

	vh->crc32 = fio_crc32c(p, len);
}

static void fill_crc64(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_crc64 *vh = hdr_priv(hdr);

	vh->crc64 = fio_crc64(p, len);
}

static void fill_md5(struct verify_header *hdr, void *p, unsigned int len)
{
	struct vhdr_md5 *vh = hdr_priv(hdr);
	struct fio_md5_ctx md5_ctx = {
		.hash = (uint32_t *) vh->md5_digest,
	};

	fio_md5_init(&md5_ctx);
	fio_md5_update(&md5_ctx, p, len);
}

static void populate_hdr(struct thread_data *td, struct io_u *io_u,
			 struct verify_header *hdr, unsigned int header_num,
			 unsigned int header_len)
{
	unsigned int data_len;
	void *data, *p;

	p = (void *) hdr;

	hdr->magic = FIO_HDR_MAGIC;
	hdr->verify_type = td->o.verify;
	hdr->len = header_len;
	hdr->rand_seed = io_u->rand_seed;
	hdr->crc32 = fio_crc32c(p, offsetof(struct verify_header, crc32));

	data_len = header_len - hdr_size(hdr);

	data = p + hdr_size(hdr);
	switch (td->o.verify) {
	case VERIFY_MD5:
		dprint(FD_VERIFY, "fill md5 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_md5(hdr, data, data_len);
		break;
	case VERIFY_CRC64:
		dprint(FD_VERIFY, "fill crc64 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc64(hdr, data, data_len);
		break;
	case VERIFY_CRC32C:
	case VERIFY_CRC32C_INTEL:
		dprint(FD_VERIFY, "fill crc32c io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc32c(hdr, data, data_len);
		break;
	case VERIFY_CRC32:
		dprint(FD_VERIFY, "fill crc32 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc32(hdr, data, data_len);
		break;
	case VERIFY_CRC16:
		dprint(FD_VERIFY, "fill crc16 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc16(hdr, data, data_len);
		break;
	case VERIFY_CRC7:
		dprint(FD_VERIFY, "fill crc7 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_crc7(hdr, data, data_len);
		break;
	case VERIFY_SHA256:
		dprint(FD_VERIFY, "fill sha256 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_sha256(hdr, data, data_len);
		break;
	case VERIFY_SHA512:
		dprint(FD_VERIFY, "fill sha512 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_sha512(hdr, data, data_len);
		break;
	case VERIFY_META:
		dprint(FD_VERIFY, "fill meta io_u %p, len %u\n",
						io_u, hdr->len);
		fill_meta(hdr, td, io_u, header_num);
		break;
	case VERIFY_SHA1:
		dprint(FD_VERIFY, "fill sha1 io_u %p, len %u\n",
						io_u, hdr->len);
		fill_sha1(hdr, data, data_len);
		break;
	case VERIFY_PATTERN:
		/* nothing to do here */
		break;
	default:
		log_err("fio: bad verify type: %d\n", td->o.verify);
		assert(0);
	}
	if (td->o.verify_offset)
		memswp(p, p + td->o.verify_offset, hdr_size(hdr));
}

/*
 * fill body of io_u->buf with random data and add a header with the
 * checksum of choice
 */
void populate_verify_io_u(struct thread_data *td, struct io_u *io_u)
{
	if (td->o.verify == VERIFY_NULL)
		return;

	fill_pattern_headers(td, io_u, 0, 0);
}

int get_next_verify(struct thread_data *td, struct io_u *io_u)
{
	struct io_piece *ipo = NULL;

	/*
	 * this io_u is from a requeue, we already filled the offsets
	 */
	if (io_u->file)
		return 0;

	if (!RB_EMPTY_ROOT(&td->io_hist_tree)) {
		struct rb_node *n = rb_first(&td->io_hist_tree);

		ipo = rb_entry(n, struct io_piece, rb_node);
		rb_erase(n, &td->io_hist_tree);
		assert(ipo->flags & IP_F_ONRB);
		ipo->flags &= ~IP_F_ONRB;
	} else if (!flist_empty(&td->io_hist_list)) {
		ipo = flist_entry(td->io_hist_list.next, struct io_piece, list);
		flist_del(&ipo->list);
		assert(ipo->flags & IP_F_ONLIST);
		ipo->flags &= ~IP_F_ONLIST;
	}

	if (ipo) {
		td->io_hist_len--;

		io_u->offset = ipo->offset;
		io_u->buflen = ipo->len;
		io_u->file = ipo->file;
		io_u->flags |= IO_U_F_VER_LIST;

		if (ipo->flags & IP_F_TRIMMED)
			io_u->flags |= IO_U_F_TRIMMED;

		if (!fio_file_open(io_u->file)) {
			int r = td_io_open_file(td, io_u->file);

			if (r) {
				dprint(FD_VERIFY, "failed file %s open\n",
						io_u->file->file_name);
				return 1;
			}
		}

		get_file(ipo->file);
		assert(fio_file_open(io_u->file));
		io_u->ddir = DDIR_READ;
		io_u->xfer_buf = io_u->buf;
		io_u->xfer_buflen = io_u->buflen;

		remove_trim_entry(td, ipo);
		free(ipo);
		dprint(FD_VERIFY, "get_next_verify: ret io_u %p\n", io_u);
		return 0;
	}

	dprint(FD_VERIFY, "get_next_verify: empty\n");
	return 1;
}

void fio_verify_init(struct thread_data *td)
{
	if (td->o.verify == VERIFY_CRC32C_INTEL ||
	    td->o.verify == VERIFY_CRC32C) {
		crc32c_intel_probe();
	}
}

static void *verify_async_thread(void *data)
{
	struct thread_data *td = data;
	struct io_u *io_u;
	int ret = 0;

	if (td->o.verify_cpumask_set &&
	    fio_setaffinity(td->pid, td->o.verify_cpumask)) {
		log_err("fio: failed setting verify thread affinity\n");
		goto done;
	}

	do {
		FLIST_HEAD(list);

		read_barrier();
		if (td->verify_thread_exit)
			break;

		pthread_mutex_lock(&td->io_u_lock);

		while (flist_empty(&td->verify_list) &&
		       !td->verify_thread_exit) {
			ret = pthread_cond_wait(&td->verify_cond,
							&td->io_u_lock);
			if (ret) {
				pthread_mutex_unlock(&td->io_u_lock);
				break;
			}
		}

		flist_splice_init(&td->verify_list, &list);
		pthread_mutex_unlock(&td->io_u_lock);

		if (flist_empty(&list))
			continue;

		while (!flist_empty(&list)) {
			io_u = flist_entry(list.next, struct io_u, verify_list);
			flist_del(&io_u->verify_list);

			ret = verify_io_u(td, io_u);
			put_io_u(td, io_u);
			if (!ret)
				continue;
			if (td_non_fatal_error(td, ERROR_TYPE_VERIFY_BIT, ret)) {
				update_error_count(td, ret);
				td_clear_error(td);
				ret = 0;
			}
		}
	} while (!ret);

	if (ret) {
		td_verror(td, ret, "async_verify");
		if (td->o.verify_fatal)
			td->terminate = 1;
	}

done:
	pthread_mutex_lock(&td->io_u_lock);
	td->nr_verify_threads--;
	pthread_mutex_unlock(&td->io_u_lock);

	pthread_cond_signal(&td->free_cond);
	return NULL;
}

int verify_async_init(struct thread_data *td)
{
	int i, ret;
	pthread_attr_t attr;

	pthread_attr_init(&attr);
	pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);

	td->verify_thread_exit = 0;

	td->verify_threads = malloc(sizeof(pthread_t) * td->o.verify_async);
	for (i = 0; i < td->o.verify_async; i++) {
		ret = pthread_create(&td->verify_threads[i], &attr,
					verify_async_thread, td);
		if (ret) {
			log_err("fio: async verify creation failed: %s\n",
					strerror(ret));
			break;
		}
		ret = pthread_detach(td->verify_threads[i]);
		if (ret) {
			log_err("fio: async verify thread detach failed: %s\n",
					strerror(ret));
			break;
		}
		td->nr_verify_threads++;
	}

	pthread_attr_destroy(&attr);

	if (i != td->o.verify_async) {
		log_err("fio: only %d verify threads started, exiting\n", i);
		td->verify_thread_exit = 1;
		write_barrier();
		pthread_cond_broadcast(&td->verify_cond);
		return 1;
	}

	return 0;
}
Пример #6
0
/*
 * Leaves f->fd open on success, caller must close
 */
static int extend_file(struct thread_data *td, struct fio_file *f)
{
	int r, new_layout = 0, unlink_file = 0, flags;
	unsigned long long left;
	unsigned int bs;
	char *b = NULL;

	if (read_only) {
		log_err("fio: refusing extend of file due to read-only\n");
		return 0;
	}

	/*
	 * check if we need to lay the file out complete again. fio
	 * does that for operations involving reads, or for writes
	 * where overwrite is set
	 */
	if (td_read(td) ||
	   (td_write(td) && td->o.overwrite && !td->o.file_append) ||
	    (td_write(td) && td->io_ops->flags & FIO_NOEXTEND))
		new_layout = 1;
	if (td_write(td) && !td->o.overwrite && !td->o.file_append)
		unlink_file = 1;

	if (unlink_file || new_layout) {
		dprint(FD_FILE, "layout unlink %s\n", f->file_name);
		if ((unlink(f->file_name) < 0) && (errno != ENOENT)) {
			td_verror(td, errno, "unlink");
			return 1;
		}
	}

	flags = O_WRONLY | O_CREAT;
	if (new_layout)
		flags |= O_TRUNC;

	dprint(FD_FILE, "open file %s, flags %x\n", f->file_name, flags);
	f->fd = open(f->file_name, flags, 0644);
	if (f->fd < 0) {
		td_verror(td, errno, "open");
		return 1;
	}

#ifdef CONFIG_POSIX_FALLOCATE
	if (!td->o.fill_device) {
		switch (td->o.fallocate_mode) {
		case FIO_FALLOCATE_NONE:
			break;
		case FIO_FALLOCATE_POSIX:
			dprint(FD_FILE, "posix_fallocate file %s size %llu\n",
				 f->file_name,
				 (unsigned long long) f->real_file_size);

			r = posix_fallocate(f->fd, 0, f->real_file_size);
			if (r > 0) {
				log_err("fio: posix_fallocate fails: %s\n",
						strerror(r));
			}
			break;
#ifdef CONFIG_LINUX_FALLOCATE
		case FIO_FALLOCATE_KEEP_SIZE:
			dprint(FD_FILE,
				"fallocate(FALLOC_FL_KEEP_SIZE) "
				"file %s size %llu\n", f->file_name,
				(unsigned long long) f->real_file_size);

			r = fallocate(f->fd, FALLOC_FL_KEEP_SIZE, 0,
					f->real_file_size);
			if (r != 0)
				td_verror(td, errno, "fallocate");

			break;
#endif /* CONFIG_LINUX_FALLOCATE */
		default:
			log_err("fio: unknown fallocate mode: %d\n",
				td->o.fallocate_mode);
			assert(0);
		}
	}
#endif /* CONFIG_POSIX_FALLOCATE */

	if (!new_layout)
		goto done;

	/*
	 * The size will be -1ULL when fill_device is used, so don't truncate
	 * or fallocate this file, just write it
	 */
	if (!td->o.fill_device) {
		dprint(FD_FILE, "truncate file %s, size %llu\n", f->file_name,
					(unsigned long long) f->real_file_size);
		if (ftruncate(f->fd, f->real_file_size) == -1) {
			if (errno != EFBIG) {
				td_verror(td, errno, "ftruncate");
				goto err;
			}
		}
	}

	b = malloc(td->o.max_bs[DDIR_WRITE]);

	left = f->real_file_size;
	while (left && !td->terminate) {
		bs = td->o.max_bs[DDIR_WRITE];
		if (bs > left)
			bs = left;

		fill_io_buffer(td, b, bs, bs);

		r = write(f->fd, b, bs);

		if (r > 0) {
			left -= r;
			continue;
		} else {
			if (r < 0) {
				int __e = errno;

				if (__e == ENOSPC) {
					if (td->o.fill_device)
						break;
					log_info("fio: ENOSPC on laying out "
						 "file, stopping\n");
					break;
				}
				td_verror(td, errno, "write");
			} else
				td_verror(td, EIO, "write");

			break;
		}
	}

	if (td->terminate) {
		dprint(FD_FILE, "terminate unlink %s\n", f->file_name);
		unlink(f->file_name);
	} else if (td->o.create_fsync) {
		if (fsync(f->fd) < 0) {
			td_verror(td, errno, "fsync");
			goto err;
		}
	}
	if (td->o.fill_device && !td_write(td)) {
		fio_file_clear_size_known(f);
		if (td_io_get_file_size(td, f))
			goto err;
		if (f->io_size > f->real_file_size)
			f->io_size = f->real_file_size;
	}

	free(b);
done:
	return 0;
err:
	close(f->fd);
	f->fd = -1;
	if (b)
		free(b);
	return 1;
}
Пример #7
0
int safe_rename (const char *src, const char *target)
{
  struct stat ssb, tsb;

  if (!src || !target)
    return -1;

  if (link (src, target) != 0)
  {

    /*
     * Coda does not allow cross-directory links, but tells
     * us it's a cross-filesystem linking attempt.
     * 
     * However, the Coda rename call is allegedly safe to use.
     * 
     * With other file systems, rename should just fail when 
     * the files reside on different file systems, so it's safe
     * to try it here.
     *
     */
    
    dprint (1, (debugfile, "safe_rename: link (%s, %s) failed: %s (%d)\n", src, target, strerror (errno), errno));

    /*
     * FUSE may return ENOSYS. VFAT may return EPERM. FreeBSD's
     * msdosfs may return EOPNOTSUPP.  ENOTSUP can also appear.
     */
    if (errno == EXDEV || errno == ENOSYS || errno == EPERM
#ifdef ENOTSUP
	|| errno == ENOTSUP
#endif
#ifdef EOPNOTSUPP
	|| errno == EOPNOTSUPP
#endif
	)
    {
      dprint (1, (debugfile, "safe_rename: trying rename...\n"));
      if (rename (src, target) == -1) 
      {
	dprint (1, (debugfile, "safe_rename: rename (%s, %s) failed: %s (%d)\n", src, target, strerror (errno), errno));
	return -1;
      }
      dprint (1, (debugfile, "safe_rename: rename succeeded.\n"));
    
      return 0;
    }

    return -1;
  }

  /*
   * Stat both links and check if they are equal.
   */
  
  if (lstat (src, &ssb) == -1)
  {
    dprint (1, (debugfile, "safe_rename: can't stat %s: %s (%d)\n",
		src, strerror (errno), errno));
    return -1;
  }
  
  if (lstat (target, &tsb) == -1)
  {
    dprint (1, (debugfile, "safe_rename: can't stat %s: %s (%d)\n",
		src, strerror (errno), errno));
    return -1;
  }

  /* 
   * pretend that the link failed because the target file
   * did already exist.
   */

  if (compare_stat (&ssb, &tsb) == -1)
  {
    dprint (1, (debugfile, "safe_rename: stat blocks for %s and %s diverge; pretending EEXIST.\n", src, target));
    errno = EEXIST;
    return -1;
  }

  /*
   * Unlink the original link.  Should we really ignore the return
   * value here? XXX
   */

  if (unlink (src) == -1) 
  {
    dprint (1, (debugfile, "safe_rename: unlink (%s) failed: %s (%d)\n",
		src, strerror (errno), errno));
  }
  

  return 0;
}
Пример #8
0
void
main(void)
{
	uint32 nrftx = 0, nrxuf = 0;
	int i = 0;
	static __xdata Rcall c;
	uint8 state = Idle;
	uint8 waitflag = 0, clearflag = 0;
	uint8 laststate, lastflag, lastMARCSTATE;
	
	laststate = state;
	lastflag = flag;
	lastMARCSTATE = MARCSTATE;

	memset(&curcall, 0, sizeof curcall);

	SLEEP &= ~SLEEP_OSC_PD;
	await(SLEEP & SLEEP_XOSC_S);
	
	CLKCON = (CLKCON & ~(CLKCON_CLKSPD | CLKCON_OSC)) | CLKSPD_DIV_1;
	await(!(CLKCON & CLKCON_OSC));

	SLEEP |= SLEEP_OSC_PD;
	await(SLEEP & SLEEP_XOSC_S);

	P1DIR |= LEDBITS;

	printinit();
	srvinit();
	rfinit();

	GREEN = RED = 0;
 	
	// Enables interrupts. (Go go go)
	EA = 1;
	
	wdinit();

	dprint("pingrf started.\n");

	srvrx();
	for(;;){
		wdreset();

		if(flag&Fpanic){
			GREEN = 0;
			RED = 0;

			for(;;){
				RED ^= 1;
				sleep(1000);
				/* TODO: reset */
			}
		}
		
		if((flag&clearflag) != 0)
			flag &= ~(flag&clearflag);

		switch(state){
		case Idle:
			if(peekcall()->type == Nop)
				break;

			nextcall(&c);
			waitflag = clearflag = 0;
			call(&c, &state, &waitflag, &clearflag);

			break;

		case Reply:
			reply(&c);
			state = Replying;
			break;

		case Replying:
			if(flag&Ftxcall){
				flag &= ~Ftxcall;
				state = Idle;
			}
//			GREEN=1;
			break;

		default:
			if((flag&waitflag) != 0){
				waitflag = flag&waitflag;
				flag &= ~waitflag;
				call(&c, &state, &waitflag, &clearflag);
			}
/*
			if((flag&waitflag)==waitflag){
				flag &= ~waitflag;
				call(&c, &state, &waitflag, &clearflag);
			}
*/
			break;
		}

		#ifdef DEBUG
		if((i++%100000 == 0) || (flag != lastflag || state != laststate | lastMARCSTATE != MARCSTATE)){
//__critical {
			wdreset();
			switch(state){
			case Idle: 
				dprint("idle"); break;
			case Replying: 
			case Reply:
				dprint("replying %d", c.type); 
				break;
			default: 
				dprint("handling(%d) %d", state, c.type);; 
				break;
			}

			lastflag = flag;
			laststate = state;
			lastMARCSTATE = MARCSTATE;

			dprint(" flag=");
			printflag(flag);
			dprint(" waitflag=");
			printflag(waitflag);
			dprint(" radio=%s\n", strmarcstate(lastMARCSTATE));

//			dprint(" flag=%F waitflag=%F radio=%S\n", flag, waitflag, lastMARCSTATE);
//
//			putchar('.');
//			putchar('\n');
			
//}
		}
		#endif
	}
}
/*
 * Send out one complete FPDU. Used for fixed sized packets like
 * Read Requests or zero length SENDs, WRITEs, READ.responses.
 * Also used for pushing an FPDU hdr only.
 */
static inline int siw_tx_ctrl(struct siw_iwarp_tx *c_tx, struct socket *s,
			      int flags)
{
	struct msghdr msg = {.msg_flags = flags};
	struct kvec iov = {
		.iov_base = (char *)&c_tx->pkt.ctrl + c_tx->ctrl_sent,
		.iov_len = c_tx->ctrl_len - c_tx->ctrl_sent};

	int rv = kernel_sendmsg(s, &msg, &iov, 1,
				c_tx->ctrl_len - c_tx->ctrl_sent);

	dprint(DBG_TX, " (QP%d): op=%d, %d of %d sent (%d)\n",
		TX_QPID(c_tx), c_tx->pkt.ctrl.opcode,
		c_tx->ctrl_sent + rv, c_tx->ctrl_len, rv);

	if (rv >= 0) {
		c_tx->ctrl_sent += rv;

		if (c_tx->ctrl_sent == c_tx->ctrl_len) {
			siw_dprint_hdr(&c_tx->pkt.hdr, TX_QPID(c_tx),
					"CTRL sent");
			if (!(flags & MSG_MORE))
				c_tx->new_tcpseg = 1;
			rv = 0;
		} else if (c_tx->ctrl_sent < c_tx->ctrl_len)
			rv = -EAGAIN;
		else
			BUG();
	}
	return rv;
}

/*
 * 0copy TCP transmit interface.
 *
 * Push page array page by page or in one shot.
 * Pushing the whole page array requires the inner do_tcp_sendpages
 * function to be exported by the kernel.
 */
static int siw_tcp_sendpages(struct socket *s, struct page **page,
			     int offset, size_t size)
{
	int rv = 0;

#ifdef SIW_SENDPAGES_EXPORT
	struct sock *sk = s->sk;

	if (!(sk->sk_route_caps & NETIF_F_SG) ||
	    !(sk->sk_route_caps & NETIF_F_ALL_CSUM)) {
		/* FIXME:
		 * This should also be handled in a
		 * loop
		 */
		return -EFAULT;
	}

	lock_sock(sk);
	TCP_CHECK_TIMER(sk);

	/*
	 * just return what sendpages has return
	 */
	rv = do_tcp_sendpages(sk, page, offset, size, MSG_MORE|MSG_DONTWAIT);

	TCP_CHECK_TIMER(sk);
	release_sock(sk);
	if (rv == -EAGAIN)
		rv = 0;
#else
	/*
	 * If do_tcp_sendpages() function is not exported
	 * push page by page
	 */
	size_t todo = size;
	int i;

	for (i = 0; size > 0; i++) {
		size_t bytes = min_t(size_t, PAGE_SIZE - offset, size);

		rv = s->ops->sendpage(s, page[i], offset, bytes,
				      MSG_MORE|MSG_DONTWAIT);
		if (rv <= 0)
			break;

		size -= rv;

		if (rv != bytes)
			break;

		offset = 0;
	}
	if (rv >= 0 || rv == -EAGAIN)
		rv = todo - size;
#endif
	return rv;
}
Пример #10
0
/*
 * Return an io_u to be processed. Gets a buflen and offset, sets direction,
 * etc. The returned io_u is fully ready to be prepped and submitted.
 */
struct io_u *get_io_u(struct thread_data *td)
{
	struct fio_file *f;
	struct io_u *io_u;
	int do_scramble = 0;

	io_u = __get_io_u(td);
	if (!io_u) {
		dprint(FD_IO, "__get_io_u failed\n");
		return NULL;
	}

	if (check_get_verify(td, io_u))
		goto out;
	if (check_get_trim(td, io_u))
		goto out;

	/*
	 * from a requeue, io_u already setup
	 */
	if (io_u->file)
		goto out;

	/*
	 * If using an iolog, grab next piece if any available.
	 */
	if (td->flags & TD_F_READ_IOLOG) {
		if (read_iolog_get(td, io_u))
			goto err_put;
	} else if (set_io_u_file(td, io_u)) {
		dprint(FD_IO, "io_u %p, setting file failed\n", io_u);
		goto err_put;
	}

	f = io_u->file;
	assert(fio_file_open(f));

	if (ddir_rw(io_u->ddir)) {
		if (!io_u->buflen && !(td->io_ops->flags & FIO_NOIO)) {
			dprint(FD_IO, "get_io_u: zero buflen on %p\n", io_u);
			goto err_put;
		}

		f->last_start = io_u->offset;
		f->last_pos = io_u->offset + io_u->buflen;

		if (io_u->ddir == DDIR_WRITE) {
			if (td->flags & TD_F_REFILL_BUFFERS) {
				io_u_fill_buffer(td, io_u,
					io_u->xfer_buflen, io_u->xfer_buflen);
			} else if (td->flags & TD_F_SCRAMBLE_BUFFERS)
				do_scramble = 1;
			if (td->flags & TD_F_VER_NONE) {
				populate_verify_io_u(td, io_u);
				do_scramble = 0;
			}
		} else if (io_u->ddir == DDIR_READ) {
			/*
			 * Reset the buf_filled parameters so next time if the
			 * buffer is used for writes it is refilled.
			 */
			io_u->buf_filled_len = 0;
		}
	}

	/*
	 * Set io data pointers.
	 */
	io_u->xfer_buf = io_u->buf;
	io_u->xfer_buflen = io_u->buflen;

out:
	assert(io_u->file);
	if (!td_io_prep(td, io_u)) {
		if (!td->o.disable_slat)
			fio_gettime(&io_u->start_time, NULL);
		if (do_scramble)
			small_content_scramble(io_u);
		return io_u;
	}
err_put:
	dprint(FD_IO, "get_io_u failed\n");
	put_io_u(td, io_u);
	return NULL;
}
Пример #11
0
/*
 * Called to complete min_events number of io for the async engines.
 */
int io_u_queued_complete(struct thread_data *td, int min_evts,
			 uint64_t *bytes)
{
	struct io_completion_data icd;
	struct timespec *tvp = NULL;
	int ret;
	struct timespec ts = { .tv_sec = 0, .tv_nsec = 0, };

	dprint(FD_IO, "io_u_queued_completed: min=%d\n", min_evts);

	if (!min_evts)
		tvp = &ts;

	ret = td_io_getevents(td, min_evts, td->o.iodepth_batch_complete, tvp);
	if (ret < 0) {
		td_verror(td, -ret, "td_io_getevents");
		return ret;
	} else if (!ret)
		return ret;

	init_icd(td, &icd, ret);
	ios_completed(td, &icd);
	if (icd.error) {
		td_verror(td, icd.error, "io_u_queued_complete");
		return -1;
	}

	if (bytes) {
		int ddir;

		for (ddir = DDIR_READ; ddir < DDIR_RWDIR_CNT; ddir++)
			bytes[ddir] += icd.bytes_done[ddir];
	}

	return 0;
}

/*
 * Call when io_u is really queued, to update the submission latency.
 */
void io_u_queued(struct thread_data *td, struct io_u *io_u)
{
	if (!td->o.disable_slat) {
		unsigned long slat_time;

		slat_time = utime_since(&io_u->start_time, &io_u->issue_time);
		add_slat_sample(td, io_u->ddir, slat_time, io_u->xfer_buflen);
	}
}

void fill_io_buffer(struct thread_data *td, void *buf, unsigned int min_write,
		    unsigned int max_bs)
{
	if (!td->o.zero_buffers) {
		unsigned int perc = td->o.compress_percentage;

		if (perc) {
			unsigned int seg = min_write;

			seg = min(min_write, td->o.compress_chunk);
			if (!seg)
				seg = min_write;

			fill_random_buf_percentage(&td->buf_state, buf,
						perc, seg, max_bs);
		} else
			fill_random_buf(&td->buf_state, buf, max_bs);
	} else
		memset(buf, 0, max_bs);
}

/*
 * "randomly" fill the buffer contents
 */
void io_u_fill_buffer(struct thread_data *td, struct io_u *io_u,
		      unsigned int min_write, unsigned int max_bs)
{
	io_u->buf_filled_len = 0;
	fill_io_buffer(td, io_u->buf, min_write, max_bs);
}
Пример #12
0
/*----------------------------------------------------------------------
        Read a character from keyboard with timeout
 Input:  none

 Result: Returns command read via read_char
         Times out and returns a null command every so often

  Calculates the timeout for the read, and does a few other house keeping 
things.  The duration of the timeout is set in pine.c.
  ----------------------------------------------------------------------*/
UCS
read_command(char **utf8str)
{
    int tm = 0, more_freq_timeo;
    UCS ucs;
    long dtime; 
    static unsigned char utf8buf[7];
    unsigned char *newdestp;

    /*
     * timeo is the mail-check-interval. What we want to do (ignoring the
     * messages_queued part) is timeout more often than timeo but only
     * check for new mail every timeo or so seconds. The reason we want to
     * timeout more often is so that we will have a chance to catch the user
     * in an idle period where we can do a check_point(). Otherwise, with
     * a default mail-check-interval, we are almost always calling newmail
     * right after the user presses a key, making it the worst possible
     * time to do a checkpoint.
     */

    more_freq_timeo = MIN(get_input_timeout(), IDLE_TIMEOUT);
    if(more_freq_timeo == 0)
      more_freq_timeo = IDLE_TIMEOUT;

    cancel_busy_cue(-1);
    tm = (messages_queued(&dtime) > 1) ? (int)dtime : more_freq_timeo;

    if(utf8str)
      *utf8str = NULL;

    ucs = read_char(tm);
    if(ucs != NO_OP_COMMAND && ucs != NO_OP_IDLE && ucs != KEY_RESIZE)
      zero_new_mail_count();

#ifdef	BACKGROUND_POST
    /*
     * Any expired children to report on?
     */
    if(ps_global->post && ps_global->post->pid == 0){
	int   winner = 0;

	if(ps_global->post->status < 0){
	    q_status_message(SM_ORDER | SM_DING, 3, 3, "Abysmal failure!");
	}
	else{
	    (void) pine_send_status(ps_global->post->status,
				    ps_global->post->fcc, tmp_20k_buf, SIZEOF_20KBUF,
				    &winner);
	    q_status_message(SM_ORDER | (winner ? 0 : SM_DING), 3, 3,
			     tmp_20k_buf);

	}

	if(!winner)
	  q_status_message(SM_ORDER, 0, 3,
	  "Re-send via \"Compose\" then \"Yes\" to \"Continue INTERRUPTED?\"");

	if(ps_global->post->fcc)
	  fs_give((void **) &ps_global->post->fcc);

	fs_give((void **) &ps_global->post);
    }
#endif

    /*
     * The character we get from read_char() is a UCS-4 char. Or it could be a special
     * value like KEY_UP or NO_OP_IDLE or something similar. From here on out
     * we're going to operate with UTF-8 internally. This is the point where we
     * convert the UCS-4 input (actually whatever sort of input the user is typing
     * was converted to UCS-4 first) to UTF-8. It's easy in this read_command
     * case because if user types a non-ascii character as a command it's going to be
     * an error. All commands are ascii. In order to present a reasonable error
     * message we pass back the UTF-8 string to the caller.
     */
    if(ucs >= 0x80 && ucs < KEY_BASE){
	/*
	 * User typed a character that is non-ascii. Convert it to
	 * UTF-8.
	 */
	memset(utf8buf, 0, sizeof(utf8buf));
	newdestp = utf8_put(utf8buf, (unsigned long) ucs);
	if(newdestp - utf8buf > 1){	/* this should happen */
	    if(utf8str)
	      *utf8str = (char *) utf8buf;

	    dprint((9, "Read command: looks like user typed non-ascii command 0x%x %s: returning KEY_UTF8\n", ucs, pretty_command(ucs)));
	    ucs = KEY_UTF8;
	}
	else{
	    dprint((9, "Read command: looks like user typed unknown, non-ascii command 0x%x %s: returning KEY_UNKNOWN\n", ucs, pretty_command(ucs)));
	    ucs = KEY_UNKNOWN;	/* best we can do, shouldn't happen */
	}
    }
    else{
	dprint((9, "Read command returning: 0x%x %s\n", ucs, pretty_command(ucs)));
    }

    return(ucs);
}
Пример #13
0
int
optionally_enter(char *utf8string, int y_base, int x_base, int utf8string_size,
		 char *utf8prompt, ESCKEY_S *escape_list, HelpType help, int *flags)
{
    UCS           *string = NULL, ucs;
    size_t         string_size;
    UCS           *s2;
    UCS           *saved_original = NULL;
    char          *candidate;
    UCS           *kill_buffer = NULL;
    UCS           *k, *kb;
    int            field_pos;		/* offset into array dline.vl */
    int            i, j, return_v, cols, prompt_width, too_thin,
                   real_y_base, km_popped, passwd;
    char         **help_text;
    long	   fkey_table[12];
    struct	   key_menu *km;
    bitmap_t	   bitmap;
    COLOR_PAIR    *lastc = NULL, *promptc = NULL;
    struct variable *vars = ps_global->vars;
    struct display_line dline;
#ifdef	_WINDOWS
    int		   cursor_shown;
#endif

    dprint((5, "=== optionally_enter called ===\n"));
    dprint((9, "utf8string:\"%s\"  y:%d  x:%d  length: %d append: %d\n",
               utf8string ? utf8string : "",
	       x_base, y_base, utf8string_size,
	       (flags && *flags & OE_APPEND_CURRENT)));
    dprint((9, "passwd:%d   utf8prompt:\"%s\"   label:\"%s\"\n",
	       (flags && *flags & OE_PASSWD_NOAST) ? 10 :
		   (flags && *flags & OE_PASSWD) ? 1 : 0,
	       utf8prompt ? utf8prompt : "",
	       (escape_list && escape_list[0].ch != -1 && escape_list[0].label)
		 ? escape_list[0].label: ""));

    if(!ps_global->ttyo)
      return(pre_screen_config_opt_enter(utf8string, utf8string_size, utf8prompt,
					 escape_list, help, flags));

#ifdef _WINDOWS
    if (mswin_usedialog ())
      return(win_dialog_opt_enter(utf8string, utf8string_size, utf8prompt,
				  escape_list, help, flags));
#endif


    /*
     * Utf8string comes in as UTF-8. We'll convert it to a UCS-4 array and operate on
     * that array, then convert it back before returning. Utf8string_size is the size
     * of the utf8string array but that doesn't help us much for the array we need to
     * operate on here. We'll just allocate a big array and then cut it off when
     * sending it back.
     *
     * This should come before the specialized calls above but those aren't
     * converted to use UCS-4 yet.
     */
    string = utf8_to_ucs4_cpystr(utf8string);
    dline.vused = ucs4_strlen(string);

    string_size = (2 * MAX(utf8string_size,dline.vused) + 100);
    fs_resize((void **) &string, string_size * sizeof(UCS));

    suspend_busy_cue();
    cols         = ps_global->ttyo->screen_cols;
    prompt_width = utf8_width(utf8prompt);
    too_thin   = 0;
    km_popped  = 0;
    if(y_base > 0)
      real_y_base = y_base;
    else{
        real_y_base = y_base + ps_global->ttyo->screen_rows;
	real_y_base = MAX(real_y_base, 0);
    }

    flush_ordered_messages();
    mark_status_dirty();

    if(flags && *flags & OE_APPEND_CURRENT) /* save a copy in case of cancel */
      saved_original = ucs4_cpystr(string);

    /*
     * build the function key mapping table, skipping predefined keys...
     */
    memset(fkey_table, NO_OP_COMMAND, 12 * sizeof(long));
    for(i = 0, j = 0; escape_list && escape_list[i].ch != -1 && i+j < 12; i++){
	if(i+j == OE_HELP_KEY)
	  j++;

	if(i+j == OE_CANCEL_KEY)
	  j++;

	if(i+j == OE_ENTER_KEY)
	  j++;

	fkey_table[i+j] = escape_list[i].ch;
    }

    /* assumption that HelpType is char **  */
    help_text = help;
    if(help_text){			/*---- Show help text -----*/
	int width = ps_global->ttyo->screen_cols - x_base;

	if(FOOTER_ROWS(ps_global) == 1){
	    km_popped++;
	    FOOTER_ROWS(ps_global) = 3;
	    clearfooter(ps_global);

	    y_base = -3;
	    real_y_base = y_base + ps_global->ttyo->screen_rows;
	}

	for(j = 0; j < 2 && help_text[j]; j++){
	    MoveCursor(real_y_base + 1 + j, x_base);
	    CleartoEOLN();

	    if(width < utf8_width(help_text[j])){
		char *tmp = cpystr(help_text[j]);
		(void) utf8_truncate(tmp, width);
		PutLine0(real_y_base + 1 + j, x_base, tmp);
		fs_give((void **) &tmp);
	    }
	    else
	      PutLine0(real_y_base + 1 + j, x_base, help_text[j]);
	}
    }
    else{
	clrbitmap(bitmap);
	clrbitmap((km = &oe_keymenu)->bitmap);		/* force formatting */
	if(!(flags && (*flags) & OE_DISALLOW_HELP))
	  setbitn(OE_HELP_KEY, bitmap);

	setbitn(OE_ENTER_KEY, bitmap);
	if(!(flags && (*flags) & OE_DISALLOW_CANCEL))
	  setbitn(OE_CANCEL_KEY, bitmap);

	setbitn(OE_CTRL_T_KEY, bitmap);

        /*---- Show the usual possible keys ----*/
	for(i=0,j=0; escape_list && escape_list[i].ch != -1 && i+j < 12; i++){
	    if(i+j == OE_HELP_KEY)
	      j++;

	    if(i+j == OE_CANCEL_KEY)
	      j++;

	    if(i+j == OE_ENTER_KEY)
	      j++;

	    oe_keymenu.keys[i+j].label = escape_list[i].label;
	    oe_keymenu.keys[i+j].name = escape_list[i].name;
	    setbitn(i+j, bitmap);
	}

	for(i = i+j; i < 12; i++)
	  if(!(i == OE_HELP_KEY || i == OE_ENTER_KEY || i == OE_CANCEL_KEY))
	    oe_keymenu.keys[i].name = NULL;

	draw_keymenu(km, bitmap, cols, 1-FOOTER_ROWS(ps_global), 0, FirstMenu);
    }
    
    if(pico_usingcolor() && VAR_PROMPT_FORE_COLOR &&
       VAR_PROMPT_BACK_COLOR &&
       pico_is_good_color(VAR_PROMPT_FORE_COLOR) &&
       pico_is_good_color(VAR_PROMPT_BACK_COLOR)){
	lastc = pico_get_cur_color();
	if(lastc){
	    promptc = new_color_pair(VAR_PROMPT_FORE_COLOR,
				     VAR_PROMPT_BACK_COLOR);
	    (void)pico_set_colorp(promptc, PSC_NONE);
	}
    }
    else
      StartInverse();

    /*
     * if display length isn't wide enough to support input,
     * shorten up the prompt...
     */
    if((dline.dwid = cols - (x_base + prompt_width)) < MIN_OPT_ENT_WIDTH){
	char *p;
	unsigned got_width;

	/*
	 * Scoot prompt pointer forward at least (MIN_OPT_ENT_WIDTH - dline.dwid) screencells.
	 */
	p = utf8_count_forw_width(utf8prompt, MIN_OPT_ENT_WIDTH-dline.dwid, &got_width);
	if(got_width < MIN_OPT_ENT_WIDTH-dline.dwid)
	  p = utf8_count_forw_width(utf8prompt, MIN_OPT_ENT_WIDTH+1-dline.dwid, &got_width);

	if(p){
	    prompt_width = utf8_width(p);
	    dline.dwid =  cols - (x_base + prompt_width);
	    utf8prompt = p;
	}
    }

    /*
     * How many UCS-4 characters will we need to make up the width dwid? It could be
     * unlimited because of zero-width characters, I suppose, but realistically it
     * isn't going to be much more than dwid.
     */
    dline.dlen = 2 * dline.dwid + 100;

    dline.dl    = (UCS *) fs_get(dline.dlen * sizeof(UCS));
    dline.olddl = (UCS *) fs_get(dline.dlen * sizeof(UCS));
    memset(dline.dl,    0, dline.dlen * sizeof(UCS));
    memset(dline.olddl, 0, dline.dlen * sizeof(UCS));

    dline.movecursor = MoveCursor;
    dline.writechar  = Writewchar;

    dline.row   = real_y_base;
    dline.col   = x_base + prompt_width;

    dline.vl    = string;
    dline.vlen  = --string_size;		/* -1 for terminating zero */
    dline.vbase = field_pos = 0;

#ifdef	_WINDOWS
    cursor_shown = mswin_showcaret(1);
#endif
    
    PutLine0(real_y_base, x_base, utf8prompt);

    /*
     * If appending, position field_pos at end of input.
     */
    if(flags && *flags & OE_APPEND_CURRENT)
      while(string[field_pos])
	field_pos++;

    passwd = (flags && *flags & OE_PASSWD_NOAST) ? 10 :
              (flags && *flags & OE_PASSWD)       ?  1 : 0;
    line_paint(field_pos, &dline, &passwd);

    /*----------------------------------------------------------------------
      The main loop
	loops until someone sets the return_v.
      ----------------------------------------------------------------------*/
    return_v = -10;

    while(return_v == -10) {

#ifdef	MOUSE
	mouse_in_content(KEY_MOUSE, -1, -1, 0x5, 0);
	register_mfunc(mouse_in_content, 
		       real_y_base, x_base + prompt_width,
		       real_y_base, ps_global->ttyo->screen_cols);
#endif
#ifdef	_WINDOWS
	mswin_allowpaste(MSWIN_PASTE_LINE);
	g_mc_row = real_y_base;
	g_mc_col = x_base + prompt_width;
	mswin_mousetrackcallback(pcpine_oe_cursor);
#endif

	/* Timeout 10 min to keep imap mail stream alive */
	ps_global->conceal_sensitive_debugging = passwd ? 1 : 0;
        ucs = read_char(600);
	ps_global->conceal_sensitive_debugging = 0;

#ifdef	MOUSE
	clear_mfunc(mouse_in_content);
#endif
#ifdef	_WINDOWS
	mswin_allowpaste(MSWIN_PASTE_DISABLE);
	mswin_mousetrackcallback(NULL);
#endif

	/*
	 * Don't want to intercept all characters if typing in passwd.
	 * We select an ad hoc set that we will catch and let the rest
	 * through.  We would have caught the set below in the big switch
	 * but we skip the switch instead.  Still catch things like ^K,
	 * DELETE, ^C, RETURN.
	 */
	if(passwd)
	  switch(ucs){
            case ctrl('F'):  
	    case KEY_RIGHT:
            case ctrl('B'):
	    case KEY_LEFT:
            case ctrl('U'):
            case ctrl('A'):
	    case KEY_HOME:
            case ctrl('E'):
	    case KEY_END:
	    case TAB:
	      goto ok_for_passwd;
	  }

        if(too_thin && ucs != KEY_RESIZE && ucs != ctrl('Z') && ucs != ctrl('C'))
          goto bleep;

	switch(ucs){

	    /*--------------- KEY RIGHT ---------------*/
          case ctrl('F'):  
	  case KEY_RIGHT:
	    if(field_pos >= string_size || string[field_pos] == '\0')
              goto bleep;

	    line_paint(++field_pos, &dline, &passwd);
	    break;

	    /*--------------- KEY LEFT ---------------*/
          case ctrl('B'):
	  case KEY_LEFT:
	    if(field_pos <= 0)
	      goto bleep;

	    line_paint(--field_pos, &dline, &passwd);
	    break;

          /*-------------------- WORD SKIP --------------------*/
	  case ctrl('@'):
	    /*
	     * Note: read_char *can* return NO_OP_COMMAND which is
	     * the def'd with the same value as ^@ (NULL), BUT since
	     * read_char has a big timeout (>25 secs) it won't.
	     */

	    /* skip thru current word */
	    while(string[field_pos]
		  && isalnum((unsigned char) string[field_pos]))
	      field_pos++;

	    /* skip thru current white space to next word */
	    while(string[field_pos]
		  && !isalnum((unsigned char) string[field_pos]))
	      field_pos++;

	    line_paint(field_pos, &dline, &passwd);
	    break;

          /*--------------------  RETURN --------------------*/
	  case PF4:
	    if(F_OFF(F_USE_FK,ps_global)) goto bleep;
	  case ctrl('J'): 
	  case ctrl('M'): 
	    return_v = 0;
	    break;

          /*-------------------- Destructive backspace --------------------*/
	  case '\177': /* DEL */
	  case ctrl('H'):
            /*   Try and do this with by telling the terminal to delete a
                 a character. If that fails, then repaint the rest of the
                 line, acheiving the same much less efficiently
             */
	    if(field_pos <= 0)
	      goto bleep;

	    field_pos--;
	    /* drop thru to pull line back ... */

          /*-------------------- Delete char --------------------*/
	  case ctrl('D'): 
	  case KEY_DEL: 
            if(field_pos >= string_size || !string[field_pos])
	      goto bleep;

	    dline.vused--;
	    for(s2 = &string[field_pos]; *s2 != 0; s2++)
	      *s2 = s2[1];

	    *s2 = 0;			/* Copy last NULL */
	    line_paint(field_pos, &dline, &passwd);
	    if(flags)		/* record change if requested  */
	      *flags |= OE_USER_MODIFIED;

	    break;

            /*--------------- Kill line -----------------*/
          case ctrl('K'):
            if(kill_buffer != NULL)
              fs_give((void **) &kill_buffer);

	    if(field_pos != 0 || string[0]){
		if(!passwd && F_ON(F_DEL_FROM_DOT, ps_global))
		  dline.vused -= ucs4_strlen(&string[i = field_pos]);
		else
		  dline.vused = i = 0;

		kill_buffer = ucs4_cpystr(&string[field_pos = i]);
		string[field_pos] = '\0';
		line_paint(field_pos, &dline, &passwd);
		if(flags)		/* record change if requested  */
		  *flags |= OE_USER_MODIFIED;
	    }

            break;

            /*------------------- Undelete line --------------------*/
          case ctrl('U'):
            if(kill_buffer == NULL)
              goto bleep;

            /* Make string so it will fit */
            kb = ucs4_cpystr(kill_buffer);
            if(ucs4_strlen(kb) + ucs4_strlen(string) > string_size) 
                kb[string_size - ucs4_strlen(string)] = '\0';
                       
            if(string[field_pos] == '\0') {
                /*--- adding to the end of the string ----*/
                for(k = kb; *k; k++)
		  string[field_pos++] = *k;

                string[field_pos] = '\0';
            }
	    else{
		int shift;

		shift = ucs4_strlen(kb);

		/* shift field_pos ... end to right */
		for(k = &string[field_pos] + ucs4_strlen(&string[field_pos]);
		    k >= &string[field_pos]; k--)
		  *(k+shift) = *k;

                for(k = kb; *k; k++)
		  string[field_pos++] = *k;
            }

	    if(*kb && flags)		/* record change if requested  */
	      *flags |= OE_USER_MODIFIED;

	    dline.vused = ucs4_strlen(string);
            fs_give((void **) &kb);
	    line_paint(field_pos, &dline, &passwd);
            break;
            
	    /*-------------------- Interrupt --------------------*/
	  case ctrl('C'): /* ^C */ 
	    if(F_ON(F_USE_FK,ps_global) || (flags && ((*flags) & OE_DISALLOW_CANCEL)))
	      goto bleep;

	    goto cancel;

	  case PF2:
	    if(F_OFF(F_USE_FK,ps_global) || (flags && ((*flags) & OE_DISALLOW_CANCEL)))
	      goto bleep;

	  cancel:
	    return_v = 1;
	    if(saved_original){
		for(i = 0; saved_original[i]; i++)
		  string[i] = saved_original[i];

		string[i] = 0;
	    }

	    break;

          case ctrl('A'):
	  case KEY_HOME:
            /*-------------------- Start of line -------------*/
	    line_paint(field_pos = 0, &dline, &passwd);
            break;

          case ctrl('E'):
	  case KEY_END:
            /*-------------------- End of line ---------------*/
	    line_paint(field_pos = dline.vused, &dline, &passwd);
            break;

	    /*-------------------- Help --------------------*/
	  case ctrl('G') : 
	  case PF1:
	    if(flags && ((*flags) & OE_DISALLOW_HELP))
	      goto bleep;
	    else if(FOOTER_ROWS(ps_global) == 1 && km_popped == 0){
		km_popped++;
		FOOTER_ROWS(ps_global) = 3;
		clearfooter(ps_global);
		if(lastc)
		  (void)pico_set_colorp(lastc, PSC_NONE);
		else
		  EndInverse();

		draw_keymenu(km, bitmap, cols, 1-FOOTER_ROWS(ps_global),
			     0, FirstMenu);

		if(promptc)
		  (void)pico_set_colorp(promptc, PSC_NONE);
		else
		  StartInverse();

		mark_keymenu_dirty();
		y_base = -3;
		dline.row = real_y_base = y_base + ps_global->ttyo->screen_rows;
		PutLine0(real_y_base, x_base, utf8prompt);
		memset(dline.dl,    0, dline.dlen * sizeof(UCS));
		memset(dline.olddl, 0, dline.dlen * sizeof(UCS));
		line_paint(field_pos, &dline, &passwd);
		break;
	    }

	    if(FOOTER_ROWS(ps_global) > 1){
		mark_keymenu_dirty();
		return_v = 3;
	    }
	    else
	      goto bleep;

	    break;


#ifdef	MOUSE
			    /* Mouse support untested in pine 5.00 */
	  case KEY_MOUSE :
	    {
	      MOUSEPRESS mp;
	      int w;

	      mouse_get_last (NULL, &mp);

	      switch(mp.button){
		case M_BUTTON_LEFT :			/* position cursor */
		  mp.col -= dline.col;

		  /*
		   * We have to figure out which character is under the cursor.
		   * This is complicated by the fact that characters may
		   * be other than one cell wide.
		   */

		  /* the -1 is for the '<' when text is offscreen left */
		  w = (dline.vbase > 0) ? mp.col-1 : mp.col;

		  if(mp.col <= 0)
		    field_pos = dline.vbase - 1;
		  else{
		    if(dline.vused <= dline.vbase
		       || ucs4_str_width_a_to_b(dline.vl,dline.vbase,dline.vused-1) <= w)
		      field_pos = dline.vused;
		    else{
		      /*
		       * Find index of 1st character that causes the
		       * width to be > w.
		       */
		      for(i = 0;
			  ucs4_str_width_a_to_b(dline.vl,dline.vbase,dline.vbase+i) <= w;
			  i++)
			;

		      field_pos = dline.vbase + i;
		    }
		  }
		  
		  field_pos = MIN(MAX(field_pos, 0), dline.vused);

		  /* just allow line_paint to choose vbase */
		  line_paint(field_pos, &dline, &passwd);
		  break;

		case M_BUTTON_RIGHT :
#ifdef	_WINDOWS

		  /*
		   * Same as M_BUTTON_LEFT except we paste in text after
		   * moving the cursor.
		   */

		  mp.col -= dline.col;

		  /* the -1 is for the '<' when text is offscreen left */
		  w = (dline.vbase > 0) ? mp.col-1 : mp.col;

		  if(mp.col <= 0)
		    field_pos = dline.vbase - 1;
		  else{
		    if(dline.vused <= dline.vbase
		       || ucs4_str_width_a_to_b(dline.vl,dline.vbase,dline.vused-1) <= w)
		      field_pos = dline.vused;
		    else{
		      /*
		       * Find index of 1st character that causes the
		       * width to be > w.
		       */
		      for(i = 0;
			  ucs4_str_width_a_to_b(dline.vl,dline.vbase,dline.vbase+i) <= w;
			  i++)
			;

		      field_pos = dline.vbase + i;
		    }
		  }
		  
		  field_pos = MIN(MAX(field_pos, 0), dline.vused);

		  line_paint(field_pos, &dline, &passwd);

		  mswin_allowpaste(MSWIN_PASTE_LINE);
		  mswin_paste_popup();
		  mswin_allowpaste(MSWIN_PASTE_DISABLE);
		  break;
#endif

		case M_BUTTON_MIDDLE :			/* NO-OP for now */
		default:				/* just ignore */
		  break;
	      }
	    }

	    break;
#endif


          case NO_OP_IDLE:
	    /*
	     * Keep mail stream alive by checking for new mail.
	     * If we're asking for a password in a login prompt
	     * we don't want to check for new_mail because the
	     * new mail check might be what got us here in the first
	     * place (because of a filter trying to save a message).
	     * If we need to wait for the user to come back then
	     * the caller will just have to deal with the failure
	     * to login.
	     */
	    i = -1;
	    if(!ps_global->no_newmail_check_from_optionally_enter)
	      i = new_mail(0, 2, NM_DEFER_SORT);

	    if(sp_expunge_count(ps_global->mail_stream) &&
	       flags && ((*flags) & OE_SEQ_SENSITIVE))
	      goto cancel;

	    if(i < 0){
	      line_paint(field_pos, &dline, &passwd);
	      break;			/* no changes, get on with life */
	    }
	    /* Else fall into redraw */

	    /*-------------------- Redraw --------------------*/
	  case ctrl('L'):
            /*---------------- re size ----------------*/
          case KEY_RESIZE:
            
	    dline.row = real_y_base = y_base > 0 ? y_base :
					 y_base + ps_global->ttyo->screen_rows;
	    if(lastc)
	      (void)pico_set_colorp(lastc, PSC_NONE);
	    else
	      EndInverse();

            ClearScreen();
            redraw_titlebar();
            if(ps_global->redrawer != (void (*)(void))NULL)
              (*ps_global->redrawer)();

            redraw_keymenu();
	    if(promptc)
	      (void)pico_set_colorp(promptc, PSC_NONE);
	    else
	      StartInverse();
            
            PutLine0(real_y_base, x_base, utf8prompt);
            cols     =  ps_global->ttyo->screen_cols;
            too_thin = 0;
            if(cols < x_base + prompt_width + 4){
		Writechar(BELL, 0);
                PutLine0(real_y_base, 0, "Screen's too thin. Ouch!");
                too_thin = 1;
            }
	    else{
		dline.col  = x_base + prompt_width;
		dline.dwid = cols - (x_base + prompt_width);
		dline.dlen = 2 * dline.dwid + 100;
		fs_resize((void **) &dline.dl, (size_t) dline.dlen * sizeof(UCS));
		fs_resize((void **) &dline.olddl, (size_t) dline.dlen * sizeof(UCS));
		memset(dline.dl,    0, dline.dlen * sizeof(UCS));
		memset(dline.olddl, 0, dline.dlen * sizeof(UCS));
		line_paint(field_pos, &dline, &passwd);
            }

            fflush(stdout);

            dprint((9,
                    "optionally_enter  RESIZE new_cols:%d  too_thin: %d\n",
                       cols, too_thin));
            break;

	  case PF3 :		/* input to potentially remap */
	  case PF5 :
	  case PF6 :
	  case PF7 :
	  case PF8 :
	  case PF9 :
	  case PF10 :
	  case PF11 :
	  case PF12 :
	      if(F_ON(F_USE_FK,ps_global)
		 && fkey_table[ucs - PF1] != NO_OP_COMMAND)
		ucs = fkey_table[ucs - PF1]; /* remap function key input */
  
          default:
	    if(escape_list){		/* in the escape key list? */
		for(j=0; escape_list[j].ch != -1; j++){
		    if(escape_list[j].ch == ucs){
			return_v = escape_list[j].rval;
			break;
		    }
		}

		if(return_v != -10)
		  break;
	    }

	    if(ucs < 0x80 && FILTER_THIS((unsigned char) ucs)){
       bleep:
		putc(BELL, stdout);
		continue;
	    }

       ok_for_passwd:
	    /*--- Insert a character -----*/
	    if(dline.vused >= string_size)
	      goto bleep;

	    /*---- extending the length of the string ---*/
	    for(s2 = &string[++dline.vused]; s2 - string > field_pos; s2--)
	      *s2 = *(s2-1);

	    string[field_pos++] = ucs;
	    line_paint(field_pos, &dline, &passwd);
	    if(flags)		/* record change if requested  */
	      *flags |= OE_USER_MODIFIED;
		    
	}   /*---- End of switch on char ----*/
    }

#ifdef	_WINDOWS
    if(!cursor_shown)
      mswin_showcaret(0);
#endif

    if(dline.dl)
      fs_give((void **) &dline.dl);

    if(dline.olddl)
      fs_give((void **) &dline.olddl);

    if(saved_original) 
      fs_give((void **) &saved_original);

    if(kill_buffer)
      fs_give((void **) &kill_buffer);

    /*
     * Change string back into UTF-8.
     */
    candidate = ucs4_to_utf8_cpystr(string);

    if(string) 
      fs_give((void **) &string);

    if(candidate){
	strncpy(utf8string, candidate, utf8string_size);
	utf8string[utf8string_size-1] = '\0';
	fs_give((void **) &candidate);
    }

    if (!(flags && (*flags) & OE_KEEP_TRAILING_SPACE))
      removing_trailing_white_space(utf8string);

    if(lastc){
	(void)pico_set_colorp(lastc, PSC_NONE);
	free_color_pair(&lastc);
	if(promptc)
	  free_color_pair(&promptc);
    }
    else
      EndInverse();

    MoveCursor(real_y_base, x_base); /* Move the cursor to show we're done */
    fflush(stdout);
    resume_busy_cue(0);
    if(km_popped){
	FOOTER_ROWS(ps_global) = 1;
	clearfooter(ps_global);
	ps_global->mangled_body = 1;
    }

    return(return_v);
}
Пример #14
0
static void
loadfont(int n, int s)
{
	char file[256];
	int i, fd, t, deep;
	static char *try[3] = {"", "times/R.", "pelm/"};
	Subfont *f;
	Font *ff;

	try[0] = fname[n];
	for (t = 0; t < 3; t++){
		i = s * mag * charmap[fmap[n]].xheight/0.72;	/* a pixel is 0.72 points */
		if (i < MINSIZE)
			i = MINSIZE;
		dprint(2, "size %d, i %d, mag %g\n", s, i, mag);
		for(; i >= MINSIZE; i--){
			/* if .font file exists, take that */
			snprint(file, sizeof file, "%s/%s%d.font",
				libfont, try[t], i);
			ff = openfont(display, file);
			if(ff != 0){
				fonttab[n][s] = ff;
				dprint(2, "using %s for font %d %d\n", file, n, s);
				return;
			}
			/* else look for a subfont file */
			for (deep = log2[screen->depth]; deep >= 0; deep--){
				snprint(file, sizeof file, "%s/%s%d.%d",
					libfont, try[t], i, deep);
				dprint(2, "trying %s for %d\n", file, i);
				if ((fd = open(file, 0)) >= 0){
					f = readsubfont(display, file, fd, 0);
					if (f == 0) {
						fprint(2, "can't rdsubfontfile %s: %r\n", file);
						exits("rdsubfont");
					}
					close(fd);
					ff = mkfont(f, 0);
					if(ff == 0){
						fprint(2, "can't mkfont %s: %r\n", file);
						exits("rdsubfont");
					}
					fonttab[n][s] = ff;
					dprint(2, "using %s for font %d %d\n", file, n, s);
					return;
				}
			}
		}
	}
	fprint(2, "can't find font %s.%d or substitute, quitting\n", fname[n], s);
	exits("no font");
}

void
loadfontname(int n, char *s)
{
	int i;
	Font *f, *g = 0;

	if (strcmp(s, fname[n]) == 0)
		return;
	if(fname[n] && fname[n][0]){
		if(lastload[n] && strcmp(lastload[n], fname[n]) == 0)
			return;
		strcpy(lastload[n], fname[n]);
	}
	fontlookup(n, s);
	for (i = 0; i < NSIZE; i++)
		if (f = fonttab[n][i]){
			if (f != g) {
				freefont(f);
				g = f;
			}
			fonttab[n][i] = 0;
		}
}

void
allfree(void)
{
	int i;

	for (i=0; i<NFONT; i++)
		loadfontname(i, "??");
}


void
readmapfile(char *file)
{
	Biobuf *fp;
	char *p, cmd[100];

	if ((fp=Bopen(file, OREAD)) == 0){
		fprint(2, "proof: can't open map file %s\n", file);
		exits("urk");
	}
	while((p=Brdline(fp, '\n')) != 0) {
		p[Blinelen(fp)-1] = 0;
		scanstr(p, cmd, 0);
		if(p[0]=='\0' || eq(cmd, "#"))	/* skip comments, empty */
			continue;
		else if(eq(cmd, "xheight"))
			buildxheight(fp);
		else if(eq(cmd, "map"))
			buildmap(fp);
		else if(eq(cmd, "special"))
			buildtroff(p);
		else if(eq(cmd, "troff"))
			buildtroff(p);
		else
			fprint(2, "weird map line %s\n", p);
	}
	Bterm(fp);
}
Пример #15
0
static ADDRESS *mutt_expand_aliases_r (ADDRESS *a, LIST **expn)
{
  ADDRESS *head = NULL, *last = NULL, *t, *w;
  LIST *u;
  char i;
  const char *fqdn;
  
  while (a)
  {
    if (!a->group && !a->personal && a->mailbox && strchr (a->mailbox, '@') == NULL)
    {
      t = mutt_lookup_alias (a->mailbox);

      if (t)
      {	
        i = 0;
        for (u = *expn; u; u = u->next)
	{
	  if (mutt_strcmp (a->mailbox, u->data) == 0) /* alias already found */
	  {
	    dprint (1, (debugfile, "mutt_expand_aliases_r(): loop in alias found for '%s'\n", a->mailbox));
	    i = 1;
	    break;
	  }
	}

        if (!i)
	{
          u = safe_malloc (sizeof (LIST));
          u->data = safe_strdup (a->mailbox);
          u->next = *expn;
          *expn = u;
	  w = rfc822_cpy_adr (t, 0);
	  w = mutt_expand_aliases_r (w, expn);
	  if (head)
	    last->next = w;
	  else
	    head = last = w;
	  while (last && last->next)
	    last = last->next;
        }
	t = a;
	a = a->next;
	t->next = NULL;
	rfc822_free_address (&t);
	continue;
      }
      else
      {
	struct passwd *pw = getpwnam (a->mailbox);

	if (pw)
	{
	  char namebuf[STRING];
	  
	  mutt_gecos_name (namebuf, sizeof (namebuf), pw);
	  mutt_str_replace (&a->personal, namebuf);
	  
#ifdef EXACT_ADDRESS
	  FREE (&a->val);
#endif
	}
      }
    }

    if (head)
    {
      last->next = a;
      last = last->next;
    }
    else
      head = last = a;
    a = a->next;
    last->next = NULL;
  }

  if (option (OPTUSEDOMAIN) && (fqdn = mutt_fqdn(1)))
  {
    /* now qualify all local addresses */
    rfc822_qualify (head, fqdn);
  }

  return (head);
}
/*
 * siw_qp_prepare_tx()
 *
 * Prepare tx state for sending out one fpdu. Builds complete pkt
 * if no user data or only immediate data are present.
 *
 * returns PKT_COMPLETE if complete pkt built, PKT_FRAGMENTED otherwise.
 */
static int siw_qp_prepare_tx(struct siw_iwarp_tx *c_tx)
{
	struct siw_wqe		*wqe = c_tx->wqe;
	u32			*crc = NULL;

	dprint(DBG_TX, "(QP%d):\n", TX_QPID(c_tx));

	switch (wr_type(wqe)) {

	case SIW_WR_RDMA_READ_REQ:
		memcpy(&c_tx->pkt.ctrl,
		       &iwarp_pktinfo[RDMAP_RDMA_READ_REQ].ctrl,
		       sizeof(struct iwarp_ctrl));

		c_tx->pkt.rreq.rsvd = 0;
		c_tx->pkt.rreq.ddp_qn = htonl(RDMAP_UNTAGGED_QN_RDMA_READ);
		c_tx->pkt.rreq.ddp_msn =
			htonl(++c_tx->ddp_msn[RDMAP_UNTAGGED_QN_RDMA_READ]);
		c_tx->pkt.rreq.ddp_mo = 0;
		c_tx->pkt.rreq.sink_stag = htonl(wqe->wr.rread.sge[0].lkey);
		c_tx->pkt.rreq.sink_to =
			cpu_to_be64(wqe->wr.rread.sge[0].addr); /* abs addr! */
		c_tx->pkt.rreq.source_stag = htonl(wqe->wr.rread.rtag);
		c_tx->pkt.rreq.source_to = cpu_to_be64(wqe->wr.rread.raddr);
		c_tx->pkt.rreq.read_size = htonl(wqe->bytes);

		dprint(DBG_TX, ": RREQ: Sink: %x, 0x%016llx\n",
			wqe->wr.rread.sge[0].lkey, wqe->wr.rread.sge[0].addr);

		c_tx->ctrl_len = sizeof(struct iwarp_rdma_rreq);
		crc = &c_tx->pkt.rreq_pkt.crc;
		break;

	case SIW_WR_SEND:
		if (wr_flags(wqe) & IB_SEND_SOLICITED)
			memcpy(&c_tx->pkt.ctrl,
			       &iwarp_pktinfo[RDMAP_SEND_SE].ctrl,
			       sizeof(struct iwarp_ctrl));
		else
			memcpy(&c_tx->pkt.ctrl,
			       &iwarp_pktinfo[RDMAP_SEND].ctrl,
			       sizeof(struct iwarp_ctrl));

		c_tx->pkt.send.ddp_qn = RDMAP_UNTAGGED_QN_SEND;
		c_tx->pkt.send.ddp_msn =
			htonl(++c_tx->ddp_msn[RDMAP_UNTAGGED_QN_SEND]);
		c_tx->pkt.send.ddp_mo = 0;
		c_tx->pkt.send.rsvd = 0;

		c_tx->ctrl_len = sizeof(struct iwarp_send);

		if (!wqe->bytes)
			crc = &c_tx->pkt.send_pkt.crc;
		break;

	case SIW_WR_RDMA_WRITE:
		memcpy(&c_tx->pkt.ctrl, &iwarp_pktinfo[RDMAP_RDMA_WRITE].ctrl,
		       sizeof(struct iwarp_ctrl));

		c_tx->pkt.rwrite.sink_stag = htonl(wqe->wr.write.rtag);
		c_tx->pkt.rwrite.sink_to = cpu_to_be64(wqe->wr.write.raddr);
		c_tx->ctrl_len = sizeof(struct iwarp_rdma_write);

		if (!wqe->bytes)
			crc = &c_tx->pkt.write_pkt.crc;
		break;

	case SIW_WR_RDMA_READ_RESP:
		memcpy(&c_tx->pkt.ctrl,
		       &iwarp_pktinfo[RDMAP_RDMA_READ_RESP].ctrl,
		       sizeof(struct iwarp_ctrl));

		/* NBO */
		c_tx->pkt.rresp.sink_stag = wqe->wr.rresp.rtag;
		c_tx->pkt.rresp.sink_to = cpu_to_be64(wqe->wr.rresp.raddr);

		c_tx->ctrl_len = sizeof(struct iwarp_rdma_rresp);

		dprint(DBG_TX, ": RRESP: Sink: %x, 0x%016llx\n",
			wqe->wr.rresp.rtag, wqe->wr.rresp.raddr);

		if (!wqe->bytes)
			crc = &c_tx->pkt.rresp_pkt.crc;
		break;

	default:
		dprint(DBG_ON, "Unsupported WQE type %d\n", wr_type(wqe));
		BUG();
		break;
	}
	c_tx->ctrl_sent = 0;
	c_tx->sge_idx = 0;
	c_tx->sge_off = 0;
	c_tx->pg_idx = 0;
	c_tx->umem_chunk = NULL;

	/*
	 * Do complete CRC if enabled and short packet
	 */
	if (crc) {
		*crc = 0;
		if (c_tx->crc_enabled) {
			if (siw_crc_txhdr(c_tx) != 0)
				return -EINVAL;
			crypto_hash_final(&c_tx->mpa_crc_hd, (u8 *)crc);
		}
	}
	c_tx->ctrl_len += MPA_CRC_SIZE;

	/*
	 * Allow direct sending out of user buffer if WR is non signalled
	 * and payload is over threshold and no CRC is enabled.
	 * Per RDMA verbs, the application should not change the send buffer
	 * until the work completed. In iWarp, work completion is only
	 * local delivery to TCP. TCP may reuse the buffer for
	 * retransmission. Changing unsent data also breaks the CRC,
	 * if applied.
	 * Inline buffers are already out of user control and can be
	 * send 0copy.
	 */
	if (zcopy_tx &&
	     (!(wr_flags(wqe) & IB_SEND_SIGNALED) || SIW_INLINED_DATA(wqe)) &&
	     wqe->bytes > SENDPAGE_THRESH &&
	     wr_type(wqe) != SIW_WR_RDMA_READ_REQ)
		c_tx->use_sendpage = 1;
	else
		c_tx->use_sendpage = 0;

	return crc == NULL ? PKT_FRAGMENTED : PKT_COMPLETE;
}
Пример #17
0
static int
chanio(Ep *ep, Hostchan *hc, int dir, int pid, void *a, int len)
{
	Ctlr *ctlr;
	int nleft, n, nt, i, maxpkt, npkt;
	uint hcdma, hctsiz;

	ctlr = ep->hp->aux;
	maxpkt = ep->maxpkt;
	npkt = HOWMANY(len, ep->maxpkt);
	if(npkt == 0)
		npkt = 1;

	hc->hcchar = (hc->hcchar & ~Epdir) | dir;
	if(dir == Epin)
		n = ROUND(len, ep->maxpkt);
	else
		n = len;
	hc->hctsiz = n | npkt<<OPktcnt | pid;
	hc->hcdma  = dmaaddr(a);

	nleft = len;
	logstart(ep);
	for(;;){
		hcdma = hc->hcdma;
		hctsiz = hc->hctsiz;
		hc->hctsiz = hctsiz & ~Dopng;
		if(hc->hcchar&Chen){
			dprint("ep%d.%d before chanio hcchar=%8.8ux\n",
				ep->dev->nb, ep->nb, hc->hcchar);
			hc->hcchar |= Chen | Chdis;
			while(hc->hcchar&Chen)
				;
			hc->hcint = Chhltd;
		}
		if((i = hc->hcint) != 0){
			dprint("ep%d.%d before chanio hcint=%8.8ux\n",
				ep->dev->nb, ep->nb, i);
			hc->hcint = i;
		}
		if(hc->hcsplt & Spltena){
			qlock(&ctlr->split);
			sofwait(ctlr, hc - ctlr->regs->hchan);
			if((dwc.regs->hfnum & 1) == 0)
				hc->hcchar &= ~Oddfrm;
			else
				hc->hcchar |= Oddfrm;
		}
		hc->hcchar = (hc->hcchar &~ Chdis) | Chen;
		clog(ep, hc);
wait:
		if(ep->ttype == Tbulk && dir == Epin)
			i = chanwait(ep, ctlr, hc, Chhltd);
		else if(ep->ttype == Tintr && (hc->hcsplt & Spltena))
			i = chanwait(ep, ctlr, hc, Chhltd);
		else
			i = chanwait(ep, ctlr, hc, Chhltd|Nak);
		clog(ep, hc);
		if(hc->hcint != i){
			dprint("chanwait intr %ux->%ux\n", i, hc->hcint);
			if((i = hc->hcint) == 0)
				goto wait;
		}
		hc->hcint = i;

		if(hc->hcsplt & Spltena){
			hc->hcsplt &= ~Compsplt;
			qunlock(&ctlr->split);
		}

		if((i & Xfercomp) == 0 && i != (Chhltd|Ack) && i != Chhltd){
			if(i & Stall)
				error(Estalled);
			if(i & (Nyet|Frmovrun))
				continue;
			if(i & Nak){
				if(ep->ttype == Tintr)
					tsleep(&up->sleep, return0, 0, ep->pollival);
				else
					tsleep(&up->sleep, return0, 0, 1);
				continue;
			}
			logdump(ep);
			print("usbotg: ep%d.%d error intr %8.8ux\n",
				ep->dev->nb, ep->nb, i);
			if(i & ~(Chhltd|Ack))
				error(Eio);
			if(hc->hcdma != hcdma)
				print("usbotg: weird hcdma %ux->%ux intr %ux->%ux\n",
					hcdma, hc->hcdma, i, hc->hcint);
		}
		n = hc->hcdma - hcdma;
		if(n == 0){
			if((hc->hctsiz & Pktcnt) != (hctsiz & Pktcnt))
				break;
			else
				continue;
		}
		if(dir == Epin && ep->ttype == Tbulk){
			nt = (hctsiz & Xfersize) - (hc->hctsiz & Xfersize);
			if(nt != n){
				if(n == ROUND(nt, 4))
					n = nt;
				else
					print("usbotg: intr %8.8ux "
						"dma %8.8ux-%8.8ux "
						"hctsiz %8.8ux-%8.ux\n",
						i, hcdma, hc->hcdma, hctsiz,
						hc->hctsiz);
			}
		}
		if(n > nleft){
			if(n != ROUND(nleft, 4))
				dprint("too much: wanted %d got %d\n",
					len, len - nleft + n);
			n = nleft;
		}
		nleft -= n;
		if(nleft == 0 || (n % maxpkt) != 0)
			break;
		if((i & Xfercomp) && ep->ttype != Tctl)
			break;
		if(dir == Epout)
			dprint("too little: nleft %d hcdma %x->%x hctsiz %x->%x intr %x\n",
				nleft, hcdma, hc->hcdma, hctsiz, hc->hctsiz, i);
	}
	logdump(ep);
	return len - nleft;
}
Пример #18
0
void get_config()
{
    int flag = 0, sflag = 0, i, prt = 0;
    int reprint_screen = 0;
    ulong page;

    popup();
    wait_keyup();
    while(!flag) {
        cprint(POP_Y+1,  POP_X+2, "Configuration:");
        cprint(POP_Y+3,  POP_X+6, "(1) Test Selection");
        cprint(POP_Y+4,  POP_X+6, "(2) Address Range");
        cprint(POP_Y+5,  POP_X+6, "(3) Memory Sizing");
        cprint(POP_Y+6,  POP_X+6, "(4) Error Summary");
        cprint(POP_Y+7,  POP_X+6, "(5) Error Report Mode");
        cprint(POP_Y+8,  POP_X+6, "(6) ECC Mode");
        cprint(POP_Y+9,  POP_X+6, "(7) Restart w/Defaults");
        cprint(POP_Y+10, POP_X+6, "(8) Redraw Screen");
        cprint(POP_Y+11, POP_X+6, "(9) Adv. Options");
        cprint(POP_Y+12,POP_X+6,"(0) Continue");

        /* Wait for key release */
        /* Fooey! This nuts'es up the serial input. */
        sflag = 0;
        switch(get_key()) {
        case 2:
            /* 1 - Test Selection */
            popclear();
            cprint(POP_Y+1, POP_X+2, "Test Selection:");
            cprint(POP_Y+3, POP_X+6, "(1) Default Tests");
            cprint(POP_Y+4, POP_X+6, "(2) Skip Current Test");
            cprint(POP_Y+5, POP_X+6, "(3) Select Test");
            cprint(POP_Y+6, POP_X+6, "(4) Select Bit Fade Test");
            cprint(POP_Y+7, POP_X+6, "(0) Cancel");
            if (v->testsel < 0) {
                cprint(POP_Y+3, POP_X+5, ">");
            } else {
                cprint(POP_Y+5, POP_X+5, ">");
            }
            wait_keyup();
            while (!sflag) {
                switch(get_key()) {
                case 2:
                    /* Default */
                    if (v->testsel == 9) {
                        bail++;
                    }
                    v->testsel = -1;
                    find_ticks();
                    sflag++;
                    cprint(LINE_INFO, COL_TST, "Std");
                    break;
                case 3:
                    /* Skip test */
                    bail++;
                    sflag++;
                    break;
                case 4:
                    /* Select test */
                    popclear();
                    cprint(POP_Y+1, POP_X+3,
                           "Test Selection:");
                    cprint(POP_Y+4, POP_X+5,
                           "Test Number [0-9]: ");
                    i = getval(POP_Y+4, POP_X+24, 0);
                    if (i <= 9) {
                        if (i != v->testsel) {
                            v->pass = -1;
                            v->test = -1;
                        }
                        v->testsel = i;
                    }
                    find_ticks();
                    sflag++;
                    bail++;
                    cprint(LINE_INFO, COL_TST, "#");
                    dprint(LINE_INFO, COL_TST+1, i, 2, 1);
                    break;
                case 5:
                    if (v->testsel != 9) {
                        v->pass = -1;
                        v->test = -1;
                    }
                    v->testsel = 9;
                    find_ticks();
                    sflag++;
                    bail++;
                    cprint(LINE_INFO, COL_TST, "#");
                    dprint(LINE_INFO, COL_TST+1, 9, 2, 1);
                    break;
                case 11:
                case 57:
                    sflag++;
                    break;
                }
            }
            popclear();
            break;
        case 3:
            /* 2 - Address Range */
            popclear();
            cprint(POP_Y+1, POP_X+2, "Test Address Range:");
            cprint(POP_Y+3, POP_X+6, "(1) Set Lower Limit");
            cprint(POP_Y+4, POP_X+6, "(2) Set Upper Limit");
            cprint(POP_Y+5, POP_X+6, "(3) Test All Memory");
            cprint(POP_Y+6, POP_X+6, "(0) Cancel");
            wait_keyup();
            while (!sflag) {
                switch(get_key()) {
                case 2:
                    /* Lower Limit */
                    popclear();
                    cprint(POP_Y+2, POP_X+4,
                           "Lower Limit: ");
                    cprint(POP_Y+4, POP_X+4,
                           "Current: ");
                    aprint(POP_Y+4, POP_X+13, v->plim_lower);
                    cprint(POP_Y+6, POP_X+4,
                           "New: ");
                    page = getval(POP_Y+6, POP_X+9, 12);
                    if (page + 1 <= v->plim_upper) {
                        v->plim_lower = page;
                        bail++;
                    }
                    adj_mem();
                    find_ticks();
                    sflag++;
                    break;
                case 3:
                    /* Upper Limit */
                    popclear();
                    cprint(POP_Y+2, POP_X+4,
                           "Upper Limit: ");
                    cprint(POP_Y+4, POP_X+4,
                           "Current: ");
                    aprint(POP_Y+4, POP_X+13, v->plim_upper);
                    cprint(POP_Y+6, POP_X+4,
                           "New: ");
                    page = getval(POP_Y+6, POP_X+9, 12);
                    if  (page - 1 >= v->plim_lower) {
                        v->plim_upper = page;
                        bail++;
                    }
                    adj_mem();
                    find_ticks();
                    sflag++;
                    break;
                case 4:
                    /* All of memory */
                    v->plim_lower = 0;
                    v->plim_upper = v->pmap[v->msegs - 1].end;
                    bail++;
                    adj_mem();
                    find_ticks();
                    sflag++;
                    break;
                case 11:
                case 57:
                    /* 0/CR - Continue */
                    sflag++;
                    break;
                }
            }
            popclear();
            break;
        case 4:
            /* 3 - Memory Sizing */
            popclear();
            cprint(POP_Y+1, POP_X+2, "Memory Sizing:");
            cprint(POP_Y+3, POP_X+6, "(1) BIOS - Std");
            if (e820_nr) {
                cprint(POP_Y+4, POP_X+6, "(2) BIOS - All");
                cprint(POP_Y+5, POP_X+6, "(3) Probe");
                cprint(POP_Y+6, POP_X+6, "(0) Continue");
                cprint(POP_Y+2+memsz_mode, POP_X+5, ">");
            } else {
                cprint(POP_Y+4, POP_X+6, "(3) Probe");
                cprint(POP_Y+5, POP_X+6, "(0) Cancel");
                if (memsz_mode == SZ_MODE_BIOS) {
                    cprint(POP_Y+3, POP_X+5, ">");
                } else {
                    cprint(POP_Y+4, POP_X+5, ">");
                }
            }
            wait_keyup();
            while (!sflag) {
                switch(get_key()) {
                case 2:
                    memsz_mode = SZ_MODE_BIOS;
                    wait_keyup();
                    restart();
                    break;
                case 3:
                    memsz_mode = SZ_MODE_BIOS_RES;
                    wait_keyup();
                    restart();
                    break;
                case 4:
                    memsz_mode = SZ_MODE_PROBE;
                    wait_keyup();
                    restart();
                    break;
                case 11:
                case 57:
                    /* 0/CR - Continue */
                    sflag++;
                    break;
                }
            }
            popclear();
            break;
        case 5:
            /* 4 - Show error summary */
            popclear();
            for (i=0; tseq[i].msg != NULL; i++) {
                cprint(POP_Y+1+i, POP_X+2, "Test:");
                dprint(POP_Y+1+i, POP_X+8, i, 2, 1);
                cprint(POP_Y+1+i, POP_X+12, "Errors:");
                dprint(POP_Y+1+i, POP_X+20, tseq[i].errors,
                       5, 1);
            }
            wait_keyup();
            while (get_key() == 0);
            popclear();
            break;
        case 6:
            /* 5 - Printing Mode */
            popclear();
            cprint(POP_Y+1, POP_X+2, "Printing Mode:");
            cprint(POP_Y+3, POP_X+6, "(1) Individual Errors");
            cprint(POP_Y+4, POP_X+6, "(2) BadRAM Patterns");
            cprint(POP_Y+5, POP_X+6, "(3) Error Counts Only");
            cprint(POP_Y+6, POP_X+6, "(0) Cancel");
            cprint(POP_Y+3+v->printmode, POP_X+5, ">");
            wait_keyup();
            while (!sflag) {
                switch(get_key()) {
                case 2:
                    /* Separate Addresses */
                    v->printmode=PRINTMODE_ADDRESSES;
                    v->eadr = 0;
                    sflag++;
                    break;
                case 3:
                    /* BadRAM Patterns */
                    v->printmode=PRINTMODE_PATTERNS;
                    sflag++;
                    prt++;
                    break;
                case 4:
                    /* Error Counts Only */
                    v->printmode=PRINTMODE_NONE;
                    sflag++;
                    break;
                case 11:
                case 57:
                    /* 0/CR - Continue */
                    sflag++;
                    break;
                }
            }
            popclear();
            break;
        case 7:
            /* 6 - ECC Polling Mode */
            popclear();
            cprint(POP_Y+1, POP_X+2, "ECC Polling Mode:");
            cprint(POP_Y+3, POP_X+6, "(1) Recommended");
            cprint(POP_Y+4, POP_X+6, "(2) On");
            cprint(POP_Y+5, POP_X+6, "(3) Off");
            cprint(POP_Y+6, POP_X+6, "(0) Cancel");
            wait_keyup();
            while(!sflag) {
                switch(get_key()) {
                case 2:
                    set_ecc_polling(-1);
                    sflag++;
                    break;
                case 3:
                    set_ecc_polling(1);
                    sflag++;
                    break;
                case 4:
                    set_ecc_polling(0);
                    sflag++;
                    break;
                case 11:
                case 57:
                    /* 0/CR - Continue */
                    sflag++;
                    break;
                }
            }
            popclear();
            break;
        case 8:
            wait_keyup();
            restart();
            break;
        case 9:
            reprint_screen = 1;
            flag++;
            break;
        case 10:
            /* 9 - Advanced Options */
            popclear();
            cprint(POP_Y+1, POP_X+2, "Advanced Options:");
            cprint(POP_Y+3, POP_X+6, "(1) Display SPD Info");
            cprint(POP_Y+4, POP_X+6, "(2) Modify Memory Timing");
            cprint(POP_Y+5, POP_X+6, "(0) Cancel");
            wait_keyup();
            while (!sflag) {
                switch(get_key()) {
                case 2:
                    popdown();
                    show_spd();
                    popup();
                    sflag++;
                    break;
                case 3:
                    get_menu();
                    sflag++;
                    break;
                case 11:
                case 57:
                    /* 0/CR - Continue */
                    sflag++;
                    break;
                }
            }
            popclear();
            break;
        case 11:
        case 57:
        case 28:
            /* 0/CR/SP - Continue */
            flag++;
            break;
        }
    }
    popdown();
    if (prt) {
        printpatn();
    }
    if (reprint_screen) {
        tty_print_screen();
    }
}
Пример #19
0
int generic_open_file(struct thread_data *td, struct fio_file *f)
{
	int is_std = 0;
	int flags = 0;
	int from_hash = 0;

	dprint(FD_FILE, "fd open %s\n", f->file_name);

	if (td_trim(td) && f->filetype != FIO_TYPE_BD) {
		log_err("fio: trim only applies to block device\n");
		return 1;
	}

	if (!strcmp(f->file_name, "-")) {
		if (td_rw(td)) {
			log_err("fio: can't read/write to stdin/out\n");
			return 1;
		}
		is_std = 1;

		/*
		 * move output logging to stderr, if we are writing to stdout
		 */
		if (td_write(td))
			f_out = stderr;
	}

	if (td_trim(td))
		goto skip_flags;
	if (td->o.odirect)
		flags |= OS_O_DIRECT;
	if (td->o.oatomic) {
		if (!FIO_O_ATOMIC) {
			td_verror(td, EINVAL, "OS does not support atomic IO");
			return 1;
		}
		flags |= OS_O_DIRECT | FIO_O_ATOMIC;
	}
	if (td->o.sync_io)
		flags |= O_SYNC;
	if (td->o.create_on_open)
		flags |= O_CREAT;
skip_flags:
	if (f->filetype != FIO_TYPE_FILE)
		flags |= FIO_O_NOATIME;

open_again:
	if (td_write(td)) {
		if (!read_only)
			flags |= O_RDWR;

		if (f->filetype == FIO_TYPE_FILE)
			flags |= O_CREAT;

		if (is_std)
			f->fd = dup(STDOUT_FILENO);
		else
			from_hash = file_lookup_open(f, flags);
	} else if (td_read(td)) {
		if (f->filetype == FIO_TYPE_CHAR && !read_only)
			flags |= O_RDWR;
		else
			flags |= O_RDONLY;

		if (is_std)
			f->fd = dup(STDIN_FILENO);
		else
			from_hash = file_lookup_open(f, flags);
	} else { //td trim
		flags |= O_RDWR;
		from_hash = file_lookup_open(f, flags);
	}

	if (f->fd == -1) {
		char buf[FIO_VERROR_SIZE];
		int __e = errno;

		if (__e == EPERM && (flags & FIO_O_NOATIME)) {
			flags &= ~FIO_O_NOATIME;
			goto open_again;
		}
		if (__e == EMFILE && file_close_shadow_fds(td))
			goto open_again;

		snprintf(buf, sizeof(buf), "open(%s)", f->file_name);

		if (__e == EINVAL && (flags & OS_O_DIRECT)) {
			log_err("fio: looks like your file system does not " \
				"support direct=1/buffered=0\n");
		}

		td_verror(td, __e, buf);
	}

	if (!from_hash && f->fd != -1) {
		if (add_file_hash(f)) {
			int fio_unused ret;

			/*
			 * Stash away descriptor for later close. This is to
			 * work-around a "feature" on Linux, where a close of
			 * an fd that has been opened for write will trigger
			 * udev to call blkid to check partitions, fs id, etc.
			 * That pollutes the device cache, which can slow down
			 * unbuffered accesses.
			 */
			if (f->shadow_fd == -1)
				f->shadow_fd = f->fd;
			else {
				/*
			 	 * OK to ignore, we haven't done anything
				 * with it
				 */
				ret = generic_close_file(td, f);
			}
			goto open_again;
		}
	}

	return 0;
}
Пример #20
0
/*=========================================================================*
 *				mixer_close				   	
 *=========================================================================*/
PRIVATE int mixer_close(const message *m_ptr)
{
	dprint("mixer_close\n");

	return OK;
}
Пример #21
0
/* ----------------------------------------------------------------------
   Execute the given mailcap command

  Args: cmd           -- the command to execute
	image_file    -- the file the data is in
	needsterminal -- does this command want to take over the terminal?
  ----*/
void
exec_mailcap_cmd(MCAP_CMD_S *mc_cmd, char *image_file, int needsterminal)
{
#ifdef _WINDOWS
    STARTUPINFO		start_info;
    PROCESS_INFORMATION	proc_info;
    WINHAND		childProcess;
    int			success = 0;
    char               *cmd;
    LPTSTR              image_file_lpt = NULL;
    LPTSTR              cmd_lpt = NULL;

    /* no special handling yet, but could be used to replace '*' hack */
    if(mc_cmd)
      cmd = mc_cmd->command;
    else
      return;

    dprint((9, "run_viewer: command=%s\n", cmd ? cmd : "?")) ;

    if(image_file)
      image_file_lpt = utf8_to_lptstr(image_file);

    /* Set to READONLY so the viewer can't try to edit it and keep it around */
    if(image_file_lpt)
      SetFileAttributes(image_file_lpt, FILE_ATTRIBUTE_READONLY);

    if(*cmd == '*' || (*cmd == '\"' && *(cmd+1) == '*')){
	/*
	 * It has been asked that there be the ability to do an 
	 * "Open With..." on attachments like you can from the
	 * Windows file browser.  After looking into this, it
	 * seems that the only way to do this would be through
	 * an undocumented hack.  Here, we would pass "openas" as
	 * the verb to mswin_shell_exec (also some changes in
	 * mswin_shell_exec).  Since this is the delicate world
	 * of attachment handling, it seems right not to rely on
	 * a hack.  The interface wouldn't be too clean anyways,
	 * as we would have to download the attachment only to
	 * display the "Open With..." dialog.  Go figure, some
	 * things Microsoft just wants to keep to themselves.
	 */

    /*
     * 2/1/2007. No idea when the above comment was written, but it is
     *  documented now at least. The below two urls describe the "openas" verb:
     *
     * http://blogs.msdn.com/oldnewthing/archive/2004/11/26/270710.aspx
     * http://msdn.microsoft.com/library/default.asp?url=/library/en-us/
     *      shellcc/platform/shell/programmersguide/shell_basics/
     *      shell_basics_extending/context.asp
     */
	success = mswin_shell_exec(cmd, &childProcess) == 0;
    }
    else{
	memset(&proc_info, 0, sizeof(proc_info));
	memset(&start_info, 0, sizeof(start_info));
	start_info.dwFlags	    = STARTF_FORCEONFEEDBACK;
	start_info.wShowWindow  = SW_SHOWNORMAL;

	if(cmd)
	  cmd_lpt = utf8_to_lptstr(cmd);

	if(CreateProcess(NULL, cmd_lpt, NULL, NULL, FALSE,
			 CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
			 NULL, NULL, &start_info, &proc_info) == TRUE){
	    q_status_message(SM_ORDER, 0, 4, "VIEWER command completed");
	    dprint ((3, "CreatProcess(%s)  Success.\n",
		    cmd ? cmd : "?"));
	    childProcess = proc_info.hProcess;
	    success = 1;
	}

	if(cmd_lpt)
	  fs_give((void **) &cmd_lpt);
    }

    if(!success){
	int rc = (int) GetLastError();
	if(image_file_lpt)
	  SetFileAttributes(image_file_lpt, FILE_ATTRIBUTE_NORMAL);

	our_unlink(image_file);
	q_status_message2(SM_ORDER, 3, 4, "\007Can't start viewer. %s%s.",
			  (rc == 2 || rc == 3) ? "Viewer not found:  " :
			  (rc == 8) ? "Not enough memory" : "Windows error ",
			  (rc == 2 || rc == 3) ? cmd :
			  (rc == 8) ? "" : int2string(rc));
    }

    if(image_file_lpt)
      fs_give((void **) &image_file_lpt);

#elif	OSX_TARGET

    char   *command = NULL,
	   *result_file = NULL,
	   *p;
    char  **r_file_h;
    PIPE_S *syspipe;
    int     mode;

    if(!mc_cmd)
      return;
    if(mc_cmd->special_handling){
	char *rhost;

	if(mime_os_specific_access())
	  osx_launch_special_handling(mc_cmd, image_file);
	else{
	  q_status_message(SM_ORDER, 0, 4, "VIEWER command cancelled");
	  our_unlink(image_file);
	}
    }
    else {
	char *cmd = mc_cmd->command;
	size_t l;

	l = 32 + strlen(cmd) + (2*strlen(image_file));
	p = command = (char *) fs_get((l+1) * sizeof(char));
	if(!needsterminal)  /* put in background if it doesn't need terminal */
	  *p++ = '(';

	snprintf(p, l+1-(p-command), "%s", cmd);
	p += strlen(p);
	if(!needsterminal){
	    if(p-command+2 < l+1){
		*p++ = ')';
		*p++ = ' ';
		*p++ = '&';
	    }
	}

	if(p-command < l+1)
	  *p++ = '\n';

	if(p-command < l+1)
	  *p   = '\0';

	dprint((9, "exec_mailcap_cmd: command=%s\n",
		   command ? command : "?"));

	mode = PIPE_RESET;
	if(needsterminal == 1)
	  r_file_h = NULL;
	else{
	    mode       |= PIPE_WRITE | PIPE_STDERR;
	    result_file = temp_nam(NULL, "pine_cmd");
	    r_file_h    = &result_file;
	}

	if(syspipe = open_system_pipe(command, r_file_h, NULL, mode, 0, pipe_callback, NULL)){
	    close_system_pipe(&syspipe, NULL, pipe_callback);
	    if(needsterminal == 1)
	      q_status_message(SM_ORDER, 0, 4, "VIEWER command completed");
	    else if(needsterminal == 2)
	      display_output_file(result_file, "VIEWER", " command result", 1);
	    else
	      display_output_file(result_file, "VIEWER", " command launched", 1);
	}
	else
	  q_status_message1(SM_ORDER, 3, 4, "Cannot spawn command : %s", cmd);

	fs_give((void **)&command);
	if(result_file)
	  fs_give((void **)&result_file);
    }
#else
    char   *command = NULL,
	   *result_file = NULL,
	   *p, *cmd, *q, *psef;
    char  **r_file_h;
    PIPE_S *syspipe;
    int     mode;
    size_t  l;

    /* no os-specific command handling */
    if(mc_cmd)
      cmd = mc_cmd->command;
    else
      return;

#ifdef PSEFCMD
    psef = fs_get((60 + strlen(PSEFCMD) + strlen(image_file))*sizeof(char));
    sprintf(psef, "PSEF=`%s | /bin/grep \"%s\" | /bin/grep -v grep`", PSEFCMD, image_file);

    q = fs_get((80 + 2*strlen(psef))*sizeof(char)); /* bigger than 62 */
    sprintf(q, "/bin/sh -c '(%s; while test -n \"$PSEF\" ; do %s ; sleep %d ; done)' ;", psef, psef, ps_global->sleep);
    fs_give((void **) &psef);
#else
    q = cpystr("");
#endif /* PSEFCMD */

    l = 32 + strlen(cmd) + 2*strlen(image_file) + strlen(q);
    p = command = (char *)fs_get((l+1) * sizeof(char));
    if(!needsterminal)  /* put in background if it doesn't need terminal */
      *p++ = '(';
    snprintf(p, l+1-(p-command), "%s ; %s rm -f %s", cmd, q, image_file);
    fs_give((void **)&q);
    command[l] = '\0';
    p += strlen(p);
    if(!needsterminal && (p-command)+5 < l){
	*p++ = ')';
	*p++ = ' ';
	*p++ = '&';
    }

    *p++ = '\n';
    *p   = '\0';

    dprint((9, "exec_mailcap_cmd: command=%s\n",
	   command ? command : "?"));

    mode = PIPE_RESET;
    if(needsterminal == 1)
      r_file_h = NULL;
    else{
	mode       |= PIPE_WRITE | PIPE_STDERR;
	result_file = temp_nam(NULL, "pine_cmd");
	r_file_h    = &result_file;
    }

    if((syspipe = open_system_pipe(command, r_file_h, NULL, mode, 0, pipe_callback, NULL)) != NULL){
	close_system_pipe(&syspipe, NULL, pipe_callback);
	if(needsterminal == 1)
	  q_status_message(SM_ORDER, 0, 4, "VIEWER command completed");
	else if(needsterminal == 2)
	  display_output_file(result_file, "VIEWER", " command result", 1);
	else
	  display_output_file(result_file, "VIEWER", " command launched", 1);
    }
    else
      q_status_message1(SM_ORDER, 3, 4, "Cannot spawn command : %s", cmd);

    fs_give((void **)&command);

    if(result_file)
      fs_give((void **)&result_file);
#endif
}
Пример #22
0
Файл: a_quit.c Проект: wfp5p/elm
int delete_aliases(int newaliases, int prompt)
{
/*
 *	Update aliases by processing deletions.  Prompting is
 *	done as directed by user input and elmrc options.
 *
 *	If "prompt" is false, then no prompting is done.
 *	Otherwise prompting is dependent upon the variable
 *	ask_delete, as set by an elmrc option.  This behavior
 *	makes the 'q' command prompt just like '$', while
 *	retaining the 'Q' command for a quick exit that never
 *	prompts.
 *
 *	Return	1		Aliases were deleted
 * 		newalias	Aliases were not deleted
 *
 *	The return allows the caller to determine if the "newalias"
 *	routine should be run.
 */

	char buffer[SLEN];
	char **list;

	int to_delete = 0, to_keep = 0, i,
		     marked_deleted = 0,
		     ask_questions;
	char answer;

	dprint(1, (debugfile, "\n\n-- leaving aliases --\n\n"));

	if (num_aliases == 0)
	  return(newaliases);	/* nothing changed */

	ask_questions = ((!prompt) ? FALSE : ask_delete);

	/* Determine if deleted messages are really to be deleted */

	/* we need to know how many there are to delete */
	for (i=0; i<num_aliases; i++)
	  if (ison(aliases[i]->status, DELETED))
	    marked_deleted++;

	dprint(6, (debugfile, "Number of aliases marked deleted = %d\n",
	            marked_deleted));

        if(marked_deleted) {
	  if(ask_questions) {
	    if (marked_deleted == 1)
	      strcpy(buffer, catgets(elm_msg_cat, AliasesSet, AliasesDelete,
			"Delete 1 alias?"));
	    else
	      sprintf(buffer, catgets(elm_msg_cat, AliasesSet, AliasesDeletePlural,
			"Delete %d aliases?"), marked_deleted);
	                    
	    answer = enter_yn(buffer, always_delete, LINES-3, FALSE);
	  } else {
	    answer = always_delete;
	  }

	  if(answer) {
	    list = (char **) malloc(marked_deleted*sizeof(*list));
	    for (i = 0; i < num_aliases; i++) {
	      if (ison(aliases[i]->status, DELETED)) {
		list[to_delete] = aliases[i]->alias;
	        dprint(8,(debugfile, "Alias number %d, %s is deletion %d\n",
	               i, list[to_delete], to_delete));
	        to_delete++;
	      }
	      else {
	        to_keep++;
	      }
	    }
	   /*
	    * Formulate message as to number of keeps and deletes.
	    * This is only complex so that the message is good English.
	    */
	    if (to_keep > 0) {
	      curr_alias = 1;		/* Reset current alias */
	      if (to_keep == 1)
		sprintf(buffer, catgets(elm_msg_cat, AliasesSet, AliasesKeepDelete,
			  "[Keeping 1 alias and deleting %d.]"), to_delete);
	      else
		sprintf(buffer, catgets(elm_msg_cat, AliasesSet, AliasesKeepDeletePlural,
			  "[Keeping %d aliases and deleting %d.]"), to_keep, to_delete);
	    }
	    else {
	      curr_alias = 0;		/* No aliases left */
	      sprintf(buffer, catgets(elm_msg_cat, AliasesSet, AliasesDeleteAll,
			  "[Deleting all aliases.]"));
	    }

	    dprint(2, (debugfile, "Action: %s\n", buffer));
	    show_error(buffer);

	    delete_from_alias_text(list, to_delete);

	    free((char *) list);
	  }
	}
	dprint(3, (debugfile, "Aliases deleted: %d\n", to_delete));

	/* If all aliases are to be kept we don't need to do anything
	 * (like run newalias for the deleted messages).
	 */

	if(to_delete == 0) {
	  dprint(3, (debugfile, "Aliases kept as is!\n"));
	  return(newaliases);
	}

	return(1);
}
void proc_inputs(int argc, char * argv[], struct RunArgs * rargs)
{

    size_t nfield = 0;
    int fin_exists = 0;
    int fout_exists = 0;
    char filename[255];
    char filein[255];
    char covfile[255] = "cov.dat";
    double * sqrt_cov = NULL;
    size_t dim = 0;
    
    int ii;
    printf("Processing program inputs: \n");
    for (ii = 1; ii < argc; ii++){
        char * name = bite_string(argv[ii],'=');
        if (strcmp(name,"fileout") == 0){
            fout_exists = 1;
            printf("........filename is %s\n",argv[ii]);
            strcpy(filename,argv[ii]);
        }
        else if (strcmp(name,"filein") == 0){
            fin_exists = 1;
            printf("........Random samples loaded from %s\n",argv[ii]);
            strcpy(filein,argv[ii]);
        }
        else if (strcmp(name,"size") == 0){
            printf("........Size of field is %s\n",argv[ii]);
            nfield = (size_t) atol(argv[ii]);
        }
        else if (strcmp(name,"sqrtcov") == 0){
            printf("........Reading sqrt of covariance from %s\n", argv[ii]);
            strcpy(covfile,argv[ii]);
            sqrt_cov = darray_load(covfile,0);
        }
        else if (strcmp(name,"dim") == 0){
            printf("........Number of dimensions to use %s\n", argv[ii]);
            dim = (size_t) atol(argv[ii]);

        }
        free(name); name = NULL;
    }

    if (nfield == 0){
       printf("Correct func call = ./elliptic1d dim=<number of dims> size=<number of pts> filein=<filein> fileout=<fileout> sqrtcov=<filename>\n");
       exit(1);
    }

    size_t output = (size_t) floor( 0.7 * nfield) ;
    double * xsol = linspace(0.0,1.0,nfield);
    if (sqrt_cov == NULL){
        printf("........Building sqrt\n");
        double * eigs = calloc_double(nfield);
        sqrt_cov = buildCovSqrt(nfield, xsol,eigs, sigsize, corrlength);
        printf("........Saving sqrt\n");
        darray_save(nfield, nfield, sqrt_cov, covfile, 0);
        
        double sumtot = 0.0;
        size_t zz;
        for (zz = 0; zz < (size_t) nfield; zz++){
            sumtot += pow(eigs[nfield-1-zz],2);
        }
        double sum = 0.0;
        for (zz = 0.0; zz < (size_t) nfield; zz++){
            sum += pow(eigs[nfield-1-zz],2);
            if (sum > 0.99 * sumtot){
                break;
            }
        }
        size_t dimmodel = zz;
        double * saveeigs = calloc_double(3*nfield);
        for (zz = 0; zz < (size_t)nfield; zz++){
            saveeigs[zz] = (double) zz;
            saveeigs[zz+nfield] = eigs[nfield-1-zz];
            saveeigs[zz+2*nfield] = eigs[nfield-1-dimmodel];
        }
        printf("dimension = %zu \n",dimmodel);
        darray_save(nfield,3,saveeigs,"eigenvalues.txt",1);
        free(eigs);
        free(saveeigs);
    }

   
    double * perm = NULL;
    double * sol = NULL;
    if (fin_exists == 0){
        perm = darray_val(nfield,1.0);
        double * permout = darray_val(nfield,1.0);
        sol = fullRun(nfield, nfield, perm, permout,NULL);
        free(permout);
    }
    else{
        perm = calloc_double(dim);
        read_data(filein,dim,1,perm);
        dprint(dim, perm);
        double * permout = darray_val(nfield,1.0);
        sol = fullRun(nfield, dim, perm, permout,sqrt_cov);
        free(permout);
    }
    
    if (fout_exists == 1){ // simulate 
        size_t kk,ll;
        size_t nsym = 20;
        double * pt = calloc_double(nfield);
        double * fields = calloc_double(nfield*(nsym+1));
        double * x = linspace(0,1,nfield);
        for (kk = 0; kk < nfield; kk++){
            fields[kk] = x[kk];
        }
        free(x);
        double * sols = calloc_double(nsym);
        for (kk = 0; kk < nsym; kk++){
            for (ll = 0; ll < nfield; ll++){
                pt[ll] = icdf_normal(0.0,1.0,randu());
            }
            //dprint(nfield, pt);
            sol = fullRun(nfield, nfield, pt,fields+(kk+1)*nfield, sqrt_cov);
            sols[kk] = sol[output];
        }
        darray_save(nfield,15,fields,filename,1);
        darray_save(nsym,1,sols,"solshisttrue.txt",1);
        free(sols);
        free(pt);
    }
    rargs->nfield = nfield;
    rargs->dim = dim;
    rargs->sqrt_cov = calloc_double(nfield * nfield);
    rargs->output = output;
    printf("Evaluating at point %G\n",xsol[output]);
    memmove(rargs->sqrt_cov, sqrt_cov, nfield*nfield * sizeof(double));
    
    
    /*
    size_t jj;
    for (jj = 0; jj < nfield; jj++){ perm[jj] = log(perm[jj]-offset); }
    double * p = dconcat_cols(nfield,1,1,xsol,sol);
    double * p2 = dconcat_cols(nfield,2,1,p,perm);
    int success = darray_save(nfield,3,p2,filename,1);
    assert (success == 1);
    free(p); p = NULL;
    free(p2); p2 = NULL;
    */

    
    free(sqrt_cov); sqrt_cov = NULL;
    free(xsol); xsol = NULL;
    free(perm); perm = NULL;
    free(sol); sol = NULL;
}
Пример #24
0
/*
 * format_view_margin - return sane value for vertical margins
 */
int *
format_view_margin(void)
{
    static int margin[2];
    char tmp[100], e[200], *err, lastchar = 0;
    int left = 0, right = 0, leftm = 0, rightm = 0;
    size_t l;

    memset(margin, 0, sizeof(margin));

    /*
     * We initially tried to make sure that the user didn't shoot themselves
     * in the foot by setting this too small. People seem to want to do some
     * strange stuff, so we're going to relax the wild shot detection and
     * let people set what they want, until we get to the point of totally
     * absurd. We've also added the possibility of appending the letter c
     * onto the width. That means treat the value as an absolute column
     * instead of a width. That is, a right margin of 76c means wrap at
     * column 76, whereas right margin of 4 means to wrap at column
     * screen width - 4.
     */
    if(ps_global->VAR_VIEW_MARGIN_LEFT){
	strncpy(tmp, ps_global->VAR_VIEW_MARGIN_LEFT, sizeof(tmp)-1);
	tmp[sizeof(tmp)-1] = '\0';
	removing_leading_and_trailing_white_space(tmp);
	if(tmp[0]){
	    l = strlen(tmp);
	    if(l > 0)
	      lastchar = tmp[l-1];

	    if(lastchar == 'c')
	      tmp[l-1] = '\0';
	    
	    if((err = strtoval(tmp, &left, 0, 0, 0, e, sizeof(e), "Viewer-margin-left")) != NULL){
		leftm = 0;
		dprint((2, "%s\n", err));
	    }
	    else{
		if(lastchar == 'c')
		  leftm = left-1;
		else
		  leftm = left;
		
		leftm = MIN(MAX(0, leftm), ps_global->ttyo->screen_cols);
	    }
	}
    }

    if(ps_global->VAR_VIEW_MARGIN_RIGHT){
	strncpy(tmp, ps_global->VAR_VIEW_MARGIN_RIGHT, sizeof(tmp)-1);
	tmp[sizeof(tmp)-1] = '\0';
	removing_leading_and_trailing_white_space(tmp);
	if(tmp[0]){
	    l = strlen(tmp);
	    if(l > 0)
	      lastchar = tmp[l-1];

	    if(lastchar == 'c')
	      tmp[l-1] = '\0';
	    
	    if((err = strtoval(tmp, &right, 0, 0, 0, e, sizeof(e), "Viewer-margin-right")) != NULL){
		rightm = 0;
		dprint((2, "%s\n", err));
	    }
	    else{
		if(lastchar == 'c')
		  rightm = ps_global->ttyo->screen_cols - right;
		else
		  rightm = right;
		
		rightm = MIN(MAX(0, rightm), ps_global->ttyo->screen_cols);
	    }
	}
    }

    if((rightm > 0 || leftm > 0) && rightm >= 0 && leftm >= 0
       && ps_global->ttyo->screen_cols - rightm - leftm >= 8){
	margin[0] = leftm;
	margin[1] = rightm;
    }

    return(margin);
}
Пример #25
0
static int __handle_option(struct fio_option *o, const char *ptr, void *data,
			   int first, int more, int curr)
{
	int il=0, *ilp;
	fio_fp64_t *flp;
	long long ull, *ullp;
	long ul1, ul2;
	double uf;
	char **cp = NULL;
	int ret = 0, is_time = 0;
	const struct value_pair *vp;
	struct value_pair posval[PARSE_MAX_VP];
	int i, all_skipped = 1;

	dprint(FD_PARSE, "__handle_option=%s, type=%d, ptr=%s\n", o->name,
							o->type, ptr);

	if (!ptr && o->type != FIO_OPT_STR_SET && o->type != FIO_OPT_STR) {
		log_err("Option %s requires an argument\n", o->name);
		return 1;
	}

	switch (o->type) {
	case FIO_OPT_STR:
	case FIO_OPT_STR_MULTI: {
		fio_opt_str_fn *fn = o->cb;

		posval_sort(o, posval);

		ret = 1;
		for (i = 0; i < PARSE_MAX_VP; i++) {
			vp = &posval[i];
			if (!vp->ival || vp->ival[0] == '\0')
				continue;
			all_skipped = 0;
			if (!strncmp(vp->ival, ptr, str_match_len(vp, ptr))) {
				ret = 0;
				if (o->off1)
					val_store(ilp, vp->oval, o->off1, vp->orval, data, o);
				continue;
			}
		}

		if (ret && !all_skipped)
			show_option_values(o);
		else if (fn)
			ret = fn(data, ptr);
		break;
	}
	case FIO_OPT_STR_VAL_TIME:
		is_time = 1;
	case FIO_OPT_INT:
	case FIO_OPT_STR_VAL: {
		fio_opt_str_val_fn *fn = o->cb;
		char tmp[128], *p;

		strncpy(tmp, ptr, sizeof(tmp) - 1);
		p = strchr(tmp, ',');
		if (p)
			*p = '\0';

		if (is_time)
			ret = check_str_time(tmp, &ull, o->is_seconds);
		else
			ret = check_str_bytes(tmp, &ull, data);

		dprint(FD_PARSE, "  ret=%d, out=%llu\n", ret, ull);

		if (ret)
			break;

		if (o->maxval && ull > o->maxval) {
			log_err("max value out of range: %llu"
					" (%u max)\n", ull, o->maxval);
			return 1;
		}
		if (o->minval && ull < o->minval) {
			log_err("min value out of range: %llu"
					" (%u min)\n", ull, o->minval);
			return 1;
		}
		if (o->posval[0].ival) {
			posval_sort(o, posval);

			ret = 1;
			for (i = 0; i < PARSE_MAX_VP; i++) {
				vp = &posval[i];
				if (!vp->ival || vp->ival[0] == '\0')
					continue;
				if (vp->oval == ull) {
					ret = 0;
					break;
				}
			}
			if (ret) {
				log_err("fio: value %llu not allowed:\n", ull);
				show_option_values(o);
				return 1;
			}
		}

		if (fn)
			ret = fn(data, &ull);
		else {
			if (o->type == FIO_OPT_INT) {
				if (first)
					val_store(ilp, ull, o->off1, 0, data, o);
				if (curr == 1) {
					if (o->off2)
						val_store(ilp, ull, o->off2, 0, data, o);
				}
				if (curr == 2) {
					if (o->off3)
						val_store(ilp, ull, o->off3, 0, data, o);
				}
				if (!more) {
					if (curr < 1) {
						if (o->off2)
							val_store(ilp, ull, o->off2, 0, data, o);
					}
					if (curr < 2) {
						if (o->off3)
							val_store(ilp, ull, o->off3, 0, data, o);
					}
				}
			} else {
				if (first)
					val_store(ullp, ull, o->off1, 0, data, o);
				if (!more) {
					if (o->off2)
						val_store(ullp, ull, o->off2, 0, data, o);
				}
			}
		}
		break;
	}
	case FIO_OPT_FLOAT_LIST: {
		char *cp2;

		if (first) {
			/*
			** Initialize precision to 0 and zero out list
			** in case specified list is shorter than default
			*/
			if (o->off2) {
				ul2 = 0;
				ilp = td_var(data, o, o->off2);
				*ilp = ul2;
			}

			flp = td_var(data, o, o->off1);
			for(i = 0; i < o->maxlen; i++)
				flp[i].u.f = 0.0;
		}
		if (curr >= o->maxlen) {
			log_err("the list exceeding max length %d\n",
					o->maxlen);
			return 1;
		}
		if (!str_to_float(ptr, &uf)) {
			log_err("not a floating point value: %s\n", ptr);
			return 1;
		}
		if (uf > o->maxfp) {
			log_err("value out of range: %f"
				" (range max: %f)\n", uf, o->maxfp);
			return 1;
		}
		if (uf < o->minfp) {
			log_err("value out of range: %f"
				" (range min: %f)\n", uf, o->minfp);
			return 1;
		}

		flp = td_var(data, o, o->off1);
		flp[curr].u.f = uf;

		dprint(FD_PARSE, "  out=%f\n", uf);

		/*
		** Calculate precision for output by counting
		** number of digits after period. Find first
		** period in entire remaining list each time
		*/
		cp2 = strchr(ptr, '.');
		if (cp2 != NULL) {
			int len = 0;

			while (*++cp2 != '\0' && *cp2 >= '0' && *cp2 <= '9')
				len++;

			if (o->off2) {
				ilp = td_var(data, o, o->off2);
				if (len > *ilp)
					*ilp = len;
			}
		}

		break;
	}
	case FIO_OPT_STR_STORE: {
		fio_opt_str_fn *fn = o->cb;

		if (!strlen(ptr))
			return 1;

		if (o->off1) {
			cp = td_var(data, o, o->off1);
			*cp = strdup(ptr);
		}

		if (fn)
			ret = fn(data, ptr);
		else if (o->posval[0].ival) {
			posval_sort(o, posval);

			ret = 1;
			for (i = 0; i < PARSE_MAX_VP; i++) {
				vp = &posval[i];
				if (!vp->ival || vp->ival[0] == '\0' || !cp)
					continue;
				all_skipped = 0;
				if (!strncmp(vp->ival, ptr, str_match_len(vp, ptr))) {
					char *rest;

					ret = 0;
					if (vp->cb)
						fn = vp->cb;
					rest = strstr(*cp ?: ptr, ":");
					if (rest) {
						if (*cp)
							*rest = '\0';
						ptr = rest + 1;
					} else
						ptr = NULL;
					break;
				}
			}
		}

		if (!all_skipped) {
			if (ret && !*cp)
				show_option_values(o);
			else if (ret && *cp)
				ret = 0;
			else if (fn && ptr)
				ret = fn(data, ptr);
		}

		break;
	}
Пример #26
0
int backup(Jcr* jcr) {

	fingerchunk_queue = sync_queue_new(-1);
	ContainerUsageMonitor* usage_monitor = container_usage_monitor_new();
	cfl_monitor = cfl_monitor_new(read_cache_size);

	if (simulation_level == SIMULATION_ALL) {
		start_read_trace_phase(jcr);
	} else {
		start_read_phase(jcr);
		start_chunk_phase(jcr);
		start_hash_phase(jcr);
	}
	start_segment_phase(jcr);
	start_filter_phase(jcr);
	start_append_phase(jcr);

	ContainerId seed_id = -1;
	int32_t seed_len = 0;
	FingerChunk* fchunk = NULL;
	int signal = recv_fingerchunk(&fchunk);
	while (signal != STREAM_END) {
		container_usage_monitor_update(usage_monitor, fchunk->container_id,
				&fchunk->fingerprint, fchunk->length);
		jvol_append_fingerchunk(jcr->job_volume, fchunk);

		if (seed_id != -1 && seed_id != fchunk->container_id) {
			jvol_append_seed(jcr->job_volume, seed_id, seed_len);
			seed_len = 0;
		}
		/* merge sequential accesses */
		seed_id = fchunk->container_id;
		seed_len += fchunk->length;

		free(fchunk);
		signal = recv_fingerchunk(&fchunk);
	}

	if (seed_len > 0)
		jvol_append_seed(jcr->job_volume, seed_id, seed_len);
	sync_queue_free(fingerchunk_queue, NULL);

	jcr->sparse_container_num = g_hash_table_size(usage_monitor->sparse_map);
	jcr->total_container_num = g_hash_table_size(usage_monitor->dense_map)
			+ jcr->sparse_container_num;

	while ((jcr->inherited_sparse_num = container_usage_monitor_print(
			usage_monitor, jcr->job_id, jcr->historical_sparse_containers)) < 0) {
		dprint("retry!");
	}

	/* store recipes of processed file */
	int i = 0;
	for (; i < jcr->file_num; ++i) {
		Recipe *recipe = (Recipe*) sync_queue_pop(jcr->completed_files_queue);
		recipe->fileindex = i;
		if (jvol_append_meta(jcr->job_volume, recipe) != SUCCESS) {
			printf("%s, %d: some errors happened in appending recipe!\n",
			__FILE__, __LINE__);
			return FAILURE;
		}
		jcr->chunk_num += recipe->chunknum;
		recipe_free(recipe);
	}

	stop_append_phase();
	stop_filter_phase();
	stop_segment_phase();
	if (simulation_level == SIMULATION_ALL) {
		stop_read_trace_phase(jcr);
	} else {
		stop_hash_phase();
		stop_chunk_phase();
		stop_read_phase();
	}

	container_usage_monitor_free(usage_monitor);
	print_cfl(cfl_monitor);
	cfl_monitor_free(cfl_monitor);

	return 0;
}
Пример #27
0
	// Database connection
	DatabasePrivate::DatabasePrivate(char const * location, int flags) {
		dprint("Opening %s", location);
		opened_ = sqlite3_open_v2(location, &db_, flags, NULL) == SQLITE_OK;
	}
Пример #28
0
int backup_server(char *path) {
	Jcr *jcr = new_write_jcr();
	strcpy(jcr->backup_path, path);
	if (access(jcr->backup_path, 4) != 0) {
		free(jcr);
		puts("This path does not exist or can not be read!");
		return -1;
	}

	if (index_init() == FALSE) {
		return -1;
	}

	jcr->job_id = get_next_job_id();
	if (is_job_existed(jcr->job_id)) {
		printf("job existed!\n");
		free(jcr);
		return FAILURE;
	}

	if (jcr->job_id == 0) {
		destor_stat->simulation_level = simulation_level;
	} else {
		if (simulation_level <= SIMULATION_RECOVERY
				&& destor_stat->simulation_level >= SIMULATION_APPEND
				|| simulation_level >= SIMULATION_APPEND
						&& destor_stat->simulation_level <= SIMULATION_RECOVERY) {
			dprint(
					"the current simulation level is not matched with the destor stat!");
			return FAILURE;
		}
	}

	jcr->job_volume = create_job_volume(jcr->job_id);

	puts("==== backup begin ====");
	puts("==== transfering begin ====");

	struct timeval begin, end;
	gettimeofday(&begin, 0);
	if (backup(jcr) != 0) {
		free(jcr);
		return FAILURE;
	}
	gettimeofday(&end, 0);

	index_destroy();

	jcr->time = end.tv_sec - begin.tv_sec
			+ (double) (end.tv_usec - begin.tv_usec) / (1000 * 1000);
	puts("==== transferring end ====");

	printf("job id: %d\n", jcr->job_id);
	printf("backup path: %s\n", jcr->backup_path);
	printf("number of files: %d\n", jcr->file_num);
	//printf("number of chunks: %d\n", jcr->chunk_num);
	printf("number of dup chunks: %d\n", jcr->number_of_dup_chunks);
	printf("total size: %ld\n", jcr->job_size);
	printf("dedup size: %ld\n", jcr->dedup_size);
	printf("dedup efficiency: %.4f, %.4f\n",
			jcr->job_size != 0 ?
					(double) (jcr->dedup_size) / (double) (jcr->job_size) : 0,
			jcr->job_size / (double) (jcr->job_size - jcr->dedup_size));
	printf("elapsed time: %.3fs\n", jcr->time);
	printf("throughput: %.2fMB/s\n",
			(double) jcr->job_size / (1024 * 1024 * jcr->time));
	printf("zero chunk count: %d\n", jcr->zero_chunk_count);
	printf("zero_chunk_amount: %ld\n", jcr->zero_chunk_amount);
	printf("rewritten_chunk_count: %d\n", jcr->rewritten_chunk_count);
	printf("rewritten_chunk_amount: %ld\n", jcr->rewritten_chunk_amount);
	printf("rewritten rate in amount: %.3f\n",
			jcr->rewritten_chunk_amount / (double) jcr->job_size);
	printf("rewritten rate in count: %.3f\n",
			jcr->rewritten_chunk_count / (double) jcr->chunk_num);

	destor_stat->data_amount += jcr->job_size;
	destor_stat->consumed_capacity += jcr->job_size - jcr->dedup_size;
	destor_stat->saved_capacity += jcr->dedup_size;
	destor_stat->number_of_chunks += jcr->chunk_num;
	destor_stat->number_of_dup_chunks += jcr->number_of_dup_chunks;
	destor_stat->zero_chunk_count += jcr->zero_chunk_count;
	destor_stat->zero_chunk_amount += jcr->zero_chunk_amount;
	destor_stat->rewritten_chunk_count += jcr->rewritten_chunk_count;
	destor_stat->rewritten_chunk_amount += jcr->rewritten_chunk_amount;
	destor_stat->sparse_chunk_count += sparse_chunk_count;
	destor_stat->sparse_chunk_amount += sparse_chunk_amount;
	destor_stat->container_num = container_volume.container_num;
	destor_stat->index_memory_overhead = index_memory_overhead;

	printf("read_time : %.3fs, %.2fMB/s\n", jcr->read_time / 1000000,
			jcr->job_size * 1000000 / jcr->read_time / 1024 / 1024);
	printf("chunk_time : %.3fs, %.2fMB/s\n", jcr->chunk_time / 1000000,
			jcr->job_size * 1000000 / jcr->chunk_time / 1024 / 1024);
	printf("name_time : %.3fs, %.2fMB/s\n", jcr->name_time / 1000000,
			jcr->job_size * 1000000 / jcr->name_time / 1024 / 1024);
	printf("filter_time : %.3fs, %.2fMB/s\n", jcr->filter_time / 1000000,
			jcr->job_size * 1000000 / jcr->filter_time / 1024 / 1024);
	printf("write_time : %.3fs, %.2fMB/s\n", jcr->write_time / 1000000,
			jcr->job_size * 1000000 / jcr->write_time / 1024 / 1024);
	printf("index_search_time : %.3fs, %.2fMB/s\n", search_time / 1000000,
			jcr->job_size * 1000000 / search_time / 1024 / 1024);
	printf("index_update_time : %.3fs, %.2fMB/s\n", update_time / 1000000,
			jcr->job_size * 1000000 / update_time / 1024 / 1024);
	puts("==== backup end ====");

	jcr->job_volume->job.job_id = jcr->job_id;
	jcr->job_volume->job.is_del = FALSE;
	jcr->job_volume->job.file_num = jcr->file_num;
	jcr->job_volume->job.chunk_num = jcr->chunk_num;

	strcpy(jcr->job_volume->job.backup_path, jcr->backup_path);

	update_job_volume_des(jcr->job_volume);
	close_job_volume(jcr->job_volume);
	jcr->job_volume = 0;

	double seek_time = 0.005; //5ms
	double bandwidth = 120 * 1024 * 1024; //120MB/s

	double index_lookup_throughput = jcr->job_size
			/ (index_read_times * seek_time
					+ index_read_entry_counter * 24 / bandwidth) / 1024 / 1024;

	double write_data_throughput = 1.0 * jcr->job_size * bandwidth
			/ (jcr->job_size - jcr->dedup_size) / 1024 / 1024;
	double index_read_throughput = 1.0 * jcr->job_size / 1024 / 1024
			/ (index_read_times * seek_time
					+ index_read_entry_counter * 24 / bandwidth);
	double index_write_throughput = 1.0 * jcr->job_size / 1024 / 1024
			/ (index_write_times * seek_time
					+ index_write_entry_counter * 24 / bandwidth);

	double estimated_throughput = write_data_throughput;
	if (estimated_throughput > index_read_throughput)
		estimated_throughput = index_read_throughput;
	/*if (estimated_throughput > index_write_throughput)
	 estimated_throughput = index_write_throughput;*/

	char logfile[] = "backup.log";
	int fd = open(logfile, O_WRONLY | O_CREAT, S_IRWXU);
	lseek(fd, 0, SEEK_END);
	char buf[512];
	/*
	 * job id,
	 * chunk number,
	 * accumulative consumed capacity,
	 * deduplication ratio,
	 * rewritten ratio,
	 * total container number,
	 * sparse container number,
	 * inherited container number,
	 * throughput,
	 * index memory overhead,
	 * index lookups,
	 * index updates,
	 */
	sprintf(buf, "%d %d %ld %.4f %.4f %d %d %d %.2f %ld %ld %ld\n", jcr->job_id,
			jcr->chunk_num, destor_stat->consumed_capacity,
			jcr->job_size != 0 ?
					(double) (jcr->dedup_size) / (double) (jcr->job_size) : 0,
			jcr->job_size != 0 ?
					(double) (jcr->rewritten_chunk_amount)
							/ (double) (jcr->job_size) :
					0, jcr->total_container_num, jcr->sparse_container_num,
			jcr->inherited_sparse_num,
			(double) jcr->job_size / (1024 * 1024 * jcr->time),
			index_memory_overhead, index_read_times, index_write_times);
	if (write(fd, buf, strlen(buf)) != strlen(buf)) {
	}
	close(fd);
	free_jcr(jcr);
	return SUCCESS;

}
Пример #29
0
void main(int argc, char *argv[])
{
    int i;
    String *t;
    char *termargs[10], **ap;

    ap = termargs;
    *ap++ = "samterm";
    ARGBEGIN{
    case 'd':
        dflag++;
        break;
    case 'r':
        machine = EARGF(usage());
        break;
    case 'R':
        Rflag++;
        break;
    case 't':
        samterm = EARGF(usage());
        break;
    case 's':
        rsamname = EARGF(usage());
        break;
    default:
        dprint("sam: unknown flag %c\n", ARGC());
        usage();
        /* options for samterm */
    case 'a':
        *ap++ = "-a";
        break;
    } ARGEND
    *ap = nil;

    Strinit(&cmdstr);
    Strinit0(&lastpat);
    Strinit0(&lastregexp);
    Strinit0(&genstr);
    Strinit0(&rhs);
    Strinit0(&curwd);
    Strinit0(&plan9cmd);
    home = getenv(HOME);
    disk = diskinit();
    if(home == 0)
        home = "/";
    if(!dflag)
        startup(machine, Rflag, termargs, argv);
    notify(notifyf);
    getcurwd();
    if(argc>0) {
        for(i=0; i<argc; i++) {
            if(!setjmp(mainloop)) {
                t = tmpcstr(argv[i]);
                Straddc(t, '\0');
                Strduplstr(&genstr, t);
                freetmpstr(t);
                fixname(&genstr);
                logsetname(newfile(), &genstr);
            }
        }
    } else if(!downloaded)
        newfile();
    seq++;
    if(file.nused)
        current(file.filepptr[0]);
    setjmp(mainloop);
    cmdloop();
    trytoquit();	/* if we already q'ed, quitok will be TRUE */
    exits(0);
}
Пример #30
0
void process_action(keyrecord_t *record)
{
    keyevent_t event = record->event;
#ifndef NO_ACTION_TAPPING
    uint8_t tap_count = record->tap.count;
#endif

    if (IS_NOEVENT(event)) { return; }

    action_t action = layer_switch_get_action(event.key);
    dprint("ACTION: "); debug_action(action);
#ifndef NO_ACTION_LAYER
    dprint(" layer_state: "); layer_debug();
    dprint(" default_layer_state: "); default_layer_debug();
#endif
    dprintln();

    switch (action.kind.id) {
        /* Key and Mods */
        case ACT_LMODS:
        case ACT_RMODS:
            {
                uint8_t mods = (action.kind.id == ACT_LMODS) ?  action.key.mods :
                                                                action.key.mods<<4;
                if (event.pressed) {
                    if (mods) {
                        add_weak_mods(mods);
                        send_keyboard_report();
                    }
                    register_code(action.key.code);
                } else {
                    unregister_code(action.key.code);
                    if (mods) {
                        del_weak_mods(mods);
                        send_keyboard_report();
                    }
                }
            }
            break;
#ifndef NO_ACTION_TAPPING
        case ACT_LMODS_TAP:
        case ACT_RMODS_TAP:
            {
                uint8_t mods = (action.kind.id == ACT_LMODS_TAP) ?  action.key.mods :
                                                                    action.key.mods<<4;
                switch (action.layer_tap.code) {
    #ifndef NO_ACTION_ONESHOT
                    case MODS_ONESHOT:
                        // Oneshot modifier
                        if (event.pressed) {
                            if (tap_count == 0) {
                                register_mods(mods);
                            }
                            else if (tap_count == 1) {
                                dprint("MODS_TAP: Oneshot: start\n");
                                set_oneshot_mods(mods);
                            }
                            else {
                                register_mods(mods);
                            }
                        } else {
                            if (tap_count == 0) {
                                clear_oneshot_mods();
                                unregister_mods(mods);
                            }
                            else if (tap_count == 1) {
                                // Retain Oneshot mods
                            }
                            else {
                                clear_oneshot_mods();
                                unregister_mods(mods);
                            }
                        }
                        break;
    #endif
                    case MODS_TAP_TOGGLE:
                        if (event.pressed) {
                            if (tap_count <= TAPPING_TOGGLE) {
                                register_mods(mods);
                            }
                        } else {
                            if (tap_count < TAPPING_TOGGLE) {
                                unregister_mods(mods);
                            }
                        }
                        break;
                    default:
                        if (event.pressed) {
                            if (tap_count > 0) {
                                if (record->tap.interrupted) {
                                    dprint("MODS_TAP: Tap: Cancel: add_mods\n");
                                    // ad hoc: set 0 to cancel tap
                                    record->tap.count = 0;
                                    register_mods(mods);
                                } else {
                                    dprint("MODS_TAP: Tap: register_code\n");
                                    register_code(action.key.code);
                                }
                            } else {
                                dprint("MODS_TAP: No tap: add_mods\n");
                                register_mods(mods);
                            }
                        } else {
                            if (tap_count > 0) {
                                dprint("MODS_TAP: Tap: unregister_code\n");
                                unregister_code(action.key.code);
                            } else {
                                dprint("MODS_TAP: No tap: add_mods\n");
                                unregister_mods(mods);
                            }
                        }
                        break;
                }
            }
            break;
#endif
#ifdef EXTRAKEY_ENABLE
        /* other HID usage */
        case ACT_USAGE:
            switch (action.usage.page) {
                case PAGE_SYSTEM:
                    if (event.pressed) {
                        host_system_send(action.usage.code);
                    } else {
                        host_system_send(0);
                    }
                    break;
                case PAGE_CONSUMER:
                    if (event.pressed) {
                        host_consumer_send(action.usage.code);
                    } else {
                        host_consumer_send(0);
                    }
                    break;
            }
            break;
#endif
#ifdef MOUSEKEY_ENABLE
        /* Mouse key */
        case ACT_MOUSEKEY:
            if (event.pressed) {
                mousekey_on(action.key.code);
                mousekey_send();
            } else {
                mousekey_off(action.key.code);
                mousekey_send();
            }
            break;
#endif
#ifndef NO_ACTION_LAYER
        case ACT_LAYER:
            if (action.layer_bitop.on == 0) {
                /* Default Layer Bitwise Operation */
                if (!event.pressed) {
                    uint8_t shift = action.layer_bitop.part*4;
                    uint32_t bits = ((uint32_t)action.layer_bitop.bits)<<shift;
                    uint32_t mask = (action.layer_bitop.xbit) ? ~(((uint32_t)0xf)<<shift) : 0;
                    switch (action.layer_bitop.op) {
                        case OP_BIT_AND: default_layer_and(bits | mask); break;
                        case OP_BIT_OR:  default_layer_or(bits | mask);  break;
                        case OP_BIT_XOR: default_layer_xor(bits | mask); break;
                        case OP_BIT_SET: default_layer_and(mask); default_layer_or(bits); break;
                    }
                }
            } else {
                /* Layer Bitwise Operation */
                if (event.pressed ? (action.layer_bitop.on & ON_PRESS) :
                                    (action.layer_bitop.on & ON_RELEASE)) {
                    uint8_t shift = action.layer_bitop.part*4;
                    uint32_t bits = ((uint32_t)action.layer_bitop.bits)<<shift;
                    uint32_t mask = (action.layer_bitop.xbit) ? ~(((uint32_t)0xf)<<shift) : 0;
                    switch (action.layer_bitop.op) {
                        case OP_BIT_AND: layer_and(bits | mask); break;
                        case OP_BIT_OR:  layer_or(bits | mask);  break;
                        case OP_BIT_XOR: layer_xor(bits | mask); break;
                        case OP_BIT_SET: layer_and(mask); layer_or(bits); break;
                    }
                }
            }
            break;
    #ifndef NO_ACTION_TAPPING
        case ACT_LAYER_TAP:
        case ACT_LAYER_TAP_EXT:
            switch (action.layer_tap.code) {
                case 0xe0 ... 0xef:
                    /* layer On/Off with modifiers(left only) */
                    if (event.pressed) {
                        layer_on(action.layer_tap.val);
                        register_mods(action.layer_tap.code & 0x0f);
                    } else {
                        layer_off(action.layer_tap.val);
                        unregister_mods(action.layer_tap.code & 0x0f);
                    }
                    break;
                case OP_TAP_TOGGLE:
                    /* tap toggle */
                    if (event.pressed) {
                        if (tap_count < TAPPING_TOGGLE) {
                            layer_invert(action.layer_tap.val);
                        }
                    } else {
                        if (tap_count <= TAPPING_TOGGLE) {
                            layer_invert(action.layer_tap.val);
                        }
                    }
                    break;
                case OP_ON_OFF:
                    event.pressed ? layer_on(action.layer_tap.val) :
                                    layer_off(action.layer_tap.val);
                    break;
                case OP_OFF_ON:
                    event.pressed ? layer_off(action.layer_tap.val) :
                                    layer_on(action.layer_tap.val);
                    break;
                case OP_SET_CLEAR:
                    event.pressed ? layer_move(action.layer_tap.val) :
                                    layer_clear();
                    break;
                default:
                    /* tap key */
                    if (event.pressed) {
                        if (tap_count > 0) {
                            dprint("KEYMAP_TAP_KEY: Tap: register_code\n");
                            register_code(action.layer_tap.code);
                        } else {
                            dprint("KEYMAP_TAP_KEY: No tap: On on press\n");
                            layer_on(action.layer_tap.val);
                        }
                    } else {
                        if (tap_count > 0) {
                            dprint("KEYMAP_TAP_KEY: Tap: unregister_code\n");
                            unregister_code(action.layer_tap.code);
                        } else {
                            dprint("KEYMAP_TAP_KEY: No tap: Off on release\n");
                            layer_off(action.layer_tap.val);
                        }
                    }
                    break;
            }
            break;
    #endif
#endif
        /* Extentions */
#ifndef NO_ACTION_MACRO
        case ACT_MACRO:
            action_macro_play(action_get_macro(record, action.func.id, action.func.opt));
            break;
#endif
#ifdef BACKLIGHT_ENABLE
        case ACT_BACKLIGHT:
            if (!event.pressed) {
                switch (action.backlight.opt) {
                    case BACKLIGHT_INCREASE:
                        backlight_increase();
                        break;
                    case BACKLIGHT_DECREASE:
                        backlight_decrease();
                        break;
                    case BACKLIGHT_TOGGLE:
                        backlight_toggle();
                        break;
                    case BACKLIGHT_STEP:
                        backlight_step();
                        break;
                    case BACKLIGHT_LEVEL:
                        backlight_level(action.backlight.level);
                        break;
                }
            }
            break;
#endif
        case ACT_COMMAND:
            switch (action.command.opt) {
                case AC_CHANGE_SEND_MODE:
                   if (event.pressed) {
                        host_system_send(CHANGE_SEND_MODE);
                    } else {
                        host_system_send(DONT_SEND_REPORT);
                    }
                    break;
                case AC_CHANGE_BLE_NAME:
                    if (event.pressed) {
                        host_system_send(CHANGE_BLE_NAME);
                    } else {
                        host_system_send(DONT_SEND_REPORT);
                    }
                    break;
                case AC_PAIRING_BLE:
                    if (event.pressed) {
                        host_system_send(PAIRING_BLE);
                    } else {
                        host_system_send(DONT_SEND_REPORT);
                    }
                    break;
                 case AC_DISCONT_BLE:
                    if (event.pressed) {
                        host_system_send(DISCONT_BLE);
                    } else {
                        host_system_send(DONT_SEND_REPORT);
                    }
                    break;
                case NOGUI_TOGGLE:
                    if (event.pressed){
                        keymap_config.no_gui = !keymap_config.no_gui;
                    }
                    break;
            }

            break;
#ifndef NO_ACTION_FUNCTION
        case ACT_FUNCTION:
            action_function(record, action.func.id, action.func.opt);
            break;
#endif
        default:
            break;
    }
}