Example #1
0
void usage(void)
{
    printf("./memcpy <blocksize> <total_size> <dst_buffer_size>\n");
    exit(1);
}
Example #2
0
int
main(int argc, char *argv[])
{
	struct exec head;
	struct ecoff_exechdr ehead;
	struct ecoff_scnhdr escn[3];
	int infd, outfd;
	int n;

	if (argc != 3)
		usage();

	infd = open(argv[1], O_RDONLY);
	if (infd < 0)
		err(1, argv[1]);

	outfd = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0644);
	if (outfd < 0)
		err(1, argv[2]);

	n = read(infd, &head, sizeof(head));
	if (n < sizeof(head))
		err(1, "read");

	if (N_BADMAG(head)) {
		printf("%s: bad magic number\n", argv[1]);
		exit(1);
	}

	if (head.a_trsize || head.a_drsize) {
		printf("%s: has relocations\n", argv[1]);
		exit(1);
	}

	/*
	 * Header
	 */

	ehead.f.f_magic = 0x016d;		/* MC88OMAGIC */
	ehead.f.f_nscns = 3;
	ehead.f.f_timdat = 0;			/* ignored */
	ehead.f.f_symptr = 0;			/* ignored */
	ehead.f.f_nsyms = 0;			/* ignored */
	ehead.f.f_opthdr = sizeof ehead.a;
	ehead.f.f_flags = 0x020f;
		/* F_RELFLG | F_EXEC | F_LNNO | 8 | F_AR16WR */

	ehead.a.magic = N_GETMAGIC(head);
	ehead.a.vstamp = 0;			/* ignored */
	ehead.a.tsize = head.a_text;		/* ignored */
	ehead.a.dsize = head.a_data;		/* ignored */
	ehead.a.bsize = head.a_bss;		/* ignored */
	ehead.a.entry = head.a_entry;
	ehead.a.text_start = N_TXTADDR(head);	/* ignored */
	ehead.a.data_start = N_DATADDR(head);	/* ignored */

	n = write(outfd, &ehead, sizeof(ehead));
	if (n != sizeof(ehead))
		err(1, "write");

	/*
	 * Sections.
	 * Note that we merge .bss into .data since the PROM will not
	 * clear it and locore does not do this either.
	 */

	strncpy(escn[0].s_name, ".text", sizeof escn[0].s_name);
	escn[0].s_paddr = N_TXTADDR(head);	/* ignored, 1:1 mapping */
	escn[0].s_size = round(head.a_text, 8);
	escn[0].s_scnptr = round(sizeof(ehead) + sizeof(escn), 0x10);
	escn[0].s_relptr = 0;
	escn[0].s_lnnoptr = 0;
	escn[0].s_nlnno = 0;
	escn[0].s_flags = 0x20;	/* STYP_TEXT */

	strncpy(escn[1].s_name, ".data", sizeof escn[1].s_name);
	escn[1].s_paddr = N_DATADDR(head);		/* ignored, 1:1 mapping */
	escn[1].s_scnptr = escn[0].s_scnptr + escn[0].s_size;
	escn[1].s_size = round(head.a_data + head.a_bss, 8);
	escn[1].s_relptr = 0;
	escn[1].s_lnnoptr = 0;
	escn[1].s_nlnno = 0;
	escn[1].s_flags = 0x40;	/* STYP_DATA */

	strncpy(escn[2].s_name, ".bss", sizeof escn[2].s_name);
	escn[2].s_paddr = N_BSSADDR(head) + head.a_bss;	/* ignored, 1:1 mapping */
	escn[2].s_scnptr = 0;		/* nothing in the file */
	escn[2].s_size = 0;
	escn[2].s_relptr = 0;
	escn[2].s_lnnoptr = 0;
	escn[2].s_nlnno = 0;
	escn[2].s_flags = 0x80;	/* STYP_BSS */

	/* adjust load addresses */
	escn[0].s_paddr += (head.a_entry & ~(__LDPGSZ - 1)) - __LDPGSZ;
	escn[1].s_paddr += (head.a_entry & ~(__LDPGSZ - 1)) - __LDPGSZ;
	escn[2].s_paddr += (head.a_entry & ~(__LDPGSZ - 1)) - __LDPGSZ;
	escn[0].s_vaddr = escn[0].s_paddr;
	escn[1].s_vaddr = escn[1].s_paddr;
	escn[2].s_vaddr = escn[2].s_paddr;

	n = write(outfd, &escn, sizeof(escn));
	if (n != sizeof(escn))
		err(1, "write");

	/*
	 * Copy text section
	 */

#ifdef DEBUG
	printf("copying %s: source %lx dest %lx size %x\n",
	    escn[0].s_name, N_TXTOFF(head), escn[0].s_scnptr, head.a_text);
#endif
	lseek(outfd, escn[0].s_scnptr, SEEK_SET);
	lseek(infd, N_TXTOFF(head), SEEK_SET);
	copybits(infd, outfd, head.a_text);

	/*
	 * Copy data section
	 */

#ifdef DEBUG
	printf("copying %s: source %lx dest %lx size %x\n",
	    escn[1].s_name, N_DATOFF(head), escn[1].s_scnptr, head.a_data);
#endif
	lseek(outfd, escn[1].s_scnptr, SEEK_SET);
	lseek(infd, N_DATOFF(head), SEEK_SET);
	copybits(infd, outfd, head.a_data);

	/*
	 * ``Copy'' bss section
	 */

#ifdef DEBUG
	printf("copying %s: size %lx\n",
	    escn[2].s_name, round(head.a_data + head.a_bss, 8) - head.a_data);
#endif
	zerobits(outfd, round(head.a_data + head.a_bss, 8) - head.a_data);

	close(infd);
	close(outfd);
	exit(0);
}
Example #3
0
int
main(int argc, char **argv)
{
    char *log_file = NULL;
    char *queue_dir = NULL;
    char *list[2];
    int num_to_send = DEFAULT_NUM, chunk;
    int fd;
    FTS *fts;
    FTSENT *ftsent;
    int piece, npieces;
    char filename[PATH_MAX];

    err_prog_name(argv[0]);

    OPTIONS("[-l log] [-n num] queuedir")
	NUMBER('n', num_to_send)
	STRING('l', log_file)
    ENDOPTS

    if (argc != 2)
	usage();

    if (log_file)
	err_set_log(log_file);

    queue_dir = argv[1];
    list[0] = queue_dir;
    list[1] = NULL;

    fts = fts_open(list, FTS_PHYSICAL|FTS_COMFOLLOW, fts_sort);
    if (fts == NULL)
    {
	err("fts failed on `%s'", queue_dir);
	exit(1);
    }

    ftsent = fts_read(fts);
    if (ftsent == NULL || ftsent->fts_info != FTS_D)
    {
	err("not a directory: %s", queue_dir);
	exit(1);
    }

    ftsent = fts_children(fts, 0);
    if (ftsent == NULL && errno)
    {
	err("*ftschildren failed");
	exit(1);
    }

    for (chunk = 1; ftsent != NULL; ftsent = ftsent->fts_link)
    {
	/*
	 * Skip non-files and ctm_smail tmp files (ones starting with `.')
	 */
	if (ftsent->fts_info != FTS_F || ftsent->fts_name[0] == '.')
	    continue;

	snprintf(filename, sizeof(filename), "%s/%s", queue_dir,
	    ftsent->fts_name);
	fd = open(filename, O_RDONLY);
	if (fd < 0)
	{
	    err("*open: %s", filename);
	    exit(1);
	}

	if (run_sendmail(fd))
	    exit(1);

	close(fd);
	
	if (unlink(filename) < 0)
	{
	    err("*unlink: %s", filename);
	    exit(1);
	}
	
	/*
	 * Deduce the delta, piece number, and number of pieces from
	 * the name of the file in the queue.  Ideally, we should be
	 * able to get the mail alias name too.
	 *
	 * NOTE: This depends intimately on the queue name used in ctm_smail.
	 */
	npieces = atoi(&ftsent->fts_name[ftsent->fts_namelen-3]);
	piece = atoi(&ftsent->fts_name[ftsent->fts_namelen-7]);
	err("%.*s %d/%d sent", (int)(ftsent->fts_namelen-8), ftsent->fts_name,
		piece, npieces);

	if (chunk++ == num_to_send)
	    break;
    }

    fts_close(fts);

    return(0);
}
Example #4
0
local void makeking(dyn * b, int n, real w0, bool n_flag, bool u_flag, int test)

// Create a King model, and optionally initialize an N-body system
// with total mass = n, core radius = 1.

{
    int i, iz, j, jcore, jhalf;
    real dz, z, rho0;
    real rhalf, zmcore;

    int nprof;
    real v20;

    if (w0 > 16) err_exit("makeking: must specify w0 < 16");

    initialize_global();

    // Compute the cluster density/velocity/potential profile
    
    poisson(rr, NM, w0, nprof, v20);

    if (test == 1)
	dump_model_and_exit(nprof);

    // Determine statistics and characteristic scales of the King model.

    rho0 = 1 / zm[nprof];		 // Central density for total mass = 1

    // Unit of velocity = sig, where rc^2 = 9 sig^2 / (4 pi G rho0)

    real sig = sqrt(four3pi * rho0 / 3); // This 3 was v20 in the f77 version...
					 // v20 is central vel. disp. / sig^2

    // Scale the zm array to unit total mass.

    for (i = 0; i <= nprof; i++)
	zm[i] = zm[i] / zm[nprof];

    // Index the mass distribution, and determine the core mass and
    // the half-mass radius.

    // By construction, rr[indx[j]] and rr[indx[j+1]] bracket the
    // radius containing a fraction j / NINDX of the total mass.

    indx[0] = 0;
    indx[NINDX] = nprof;

    dz = 1.0/NINDX;
    z = dz;
    iz = 1;
    for (j = 1; j <= nprof - 1; j++) {
	if (rr[j] < 1) jcore = j;
	if (zm[j] < 0.5) jhalf = j; 
	if (zm[j] > z) {
	    indx[iz] = j - 1;
	    z = z + dz;
	    iz = iz + 1;
	}
    }

    zmcore = zm[jcore] + (zm[jcore+1] - zm[jcore]) * (1 - rr[jcore])
		/ (rr[jcore+1] - rr[jcore]);

    rhalf = rr[jhalf] + (rr[jhalf+1] - rr[jhalf])
		* (0.5 - zm[jhalf])
		    / (zm[jhalf+1] - zm[jhalf]);

    // Compute the kinetic and potential energies, and determine the
    // virial radius and ratio.

    real kin = 0, pot =0;

    for (i = 1; i <= nprof; i++) {
	kin += (zm[i] - zm[i-1]) * (v2[i-1] + v2[i]);
	pot -= (zm[i] - zm[i-1]) * (zm[i] + zm[i-1]) / (rr[i-1] + rr[i]);
    }
    kin *= 0.25*sig*sig*v20;

    real rvirial = -0.5/pot;

    cerr << endl << "King model";
    cerr << "\n    w0 = " << w0 << "  beta = " << beta << "  nprof =" << nprof
	 <<        "  V20/sig2 = " << v20
	 <<        "  Mc/M = " << zmcore << endl
         <<   "    Rt/Rc = " << rr[nprof] << " (c = " << log10(rr[nprof])
         <<        ")  Rh/Rc = " << rhalf
         <<        "  Rvir/Rc = " << rvirial // << "  -T/U = " << -kin/pot
	 << endl
         <<   "    Rc/Rvir = " << 1/rvirial
         <<        "  Rh/Rvir = " << rhalf/rvirial
         <<        "  Rt/Rvir = " << rr[nprof]/rvirial
	 << "\n\n";

    if (test == 2) {

	// Scaling factors are for Mtotal = 1, Rvir = 1:

	dump_model_and_exit(nprof, rho0, 1/rvirial);
    }

    if (b == NULL || n < 1) return;

    // Initialize the N-body system.

    sprintf(tmp_string,
    "         King model, w0 = %.2f, Rt/Rc = %.3f, Rh/Rc = %.3f, Mc/M = %.3f",
	      w0, rr[nprof], rhalf, zmcore);
    b->log_comment(tmp_string);

    // Write essential model information to root dyn story.

    putrq(b->get_log_story(), "initial_mass", 1.0);

    // putrq(b->get_log_story(), "initial_rvirial", 0.25/kin); // assumes a lot!
							       // -- too much...

    putrq(b->get_log_story(), "initial_rtidal_over_rvirial",
	  rr[nprof] / (0.25/kin));

    // Assign positions and velocities. Note that it may actually
    // be preferable to do this in layers instead.

    for_all_daughters(dyn, b, bi) {

	if (test == 3) {

	    // Test: For a pure King model, getvel should generate a
	    //       distribution of velocities with maximum speed
	    //       sqrt(-2*p) and <v^2> = v2*v20, where p and v2
	    //       are the scaled potential and mean-square
	    //       velocity at any given radius.

	    real nsum = 10000;

	    for (int zone = 0; zone < 0.95*nprof; zone += nprof/15) {
		real v2sum = 0;
		real v2max = 0;
		for (int jj = 0; jj < nsum; jj++) {
		    setvel(bi, psi[zone]);
		    real vsq = bi->get_vel()*bi->get_vel();
		    v2sum += vsq;
		    v2max = Starlab::max(v2max, vsq);
		}

		cerr << "zone " << zone << "  r = " << rr[zone]
		     << "  v2max = " << v2max<< "  ?= "  << -2*psi[zone]
		     << "  v2mean = " << v2sum/nsum << "  ?= " << v2[zone]*v20
		     << endl;
	    }

	    exit(0);

	}

	if (n_flag)
	    bi->set_mass(1.0/n);

	real pot;
	setpos(bi, pot);
	setvel(bi, pot);

	// Unit of length = rc.
	// Unit of velocity = sig.

	bi->scale_vel(sig);
    }

    // System is in virial equilibrium in a consistent set of units
    // with G, core radius, and total mass = 1.

    // Convenient to have the "unscaled" system (-u on the command line)
    // be as close to standard units as possible, so rescale here to force
    // the virial radius to 1.  (Steve, 9/04)

    real xfac = 1/rvirial;
    real vfac = 1/sqrt(xfac);

    for_all_daughters(dyn, b, bi) {
	bi->set_pos(xfac*bi->get_pos());
	bi->set_vel(vfac*bi->get_vel());
    }
Example #5
0
command_stream_t
make_command_stream (int (*get_next_byte) (void *), void *get_next_byte_argument)
{
  //=========Let's just try to read the input in first.============//
  
  size_t bufferSize = 1024;
  size_t bufferIterator = 0;
  char value;
  char* buffer = (char*) checked_malloc(bufferSize);

  while ((value = get_next_byte(get_next_byte_argument)) != EOF) //store into value while it isn't EOF
  {
    buffer[bufferIterator++] = value;
    //    printf("looped once: %c \n", value);
    //    printf("bufferSize: %d \n", (int) bufferSize);
    if (bufferSize == bufferIterator){
      buffer =  (char*) checked_grow_alloc(buffer, &bufferSize);
      //printf("called checked_realloc: %d\n", (int) bufferSize);
    }
  }
  if (bufferSize == bufferIterator){
    buffer =  (char*) checked_grow_alloc(buffer, &bufferSize);
    //printf("called checked_realloc: %d\n", (int) bufferSize);
  }
  buffer[bufferIterator] = '\0';

  //printf("bufferIterator: %d \n", (int) bufferIterator);
  //puts(buffer);  //will output to stdout
  
  //=========Let's tokenize the stream============//
  //we need to do the same thing as before, except instead of taking from the filestream and putting it into the array.
  //Now take the array and put it into a token stream.
  //Could never get the outside function working due to all that referential bullshit.  Let's just do it inline.

  
  token_stream* tstream = (token_stream*) checked_malloc(sizeof(token_stream*));
  token_stream* trackend = tstream;
  int bufferIteratorT = 0;
  int comment = 0;
  int linNumber = 1;

  token_type type;
  
  //do a dual parsing here where we handle two characters at the same time. This makes the && and || and comments easy
  //Need to check if the buffer is completely empty (has '\0' as the only character).  Then we don't do anything so we  //can just return

  if (buffer[bufferIteratorT] == '\0')
  {  
    command_stream_t empty = (command_stream_t) checked_malloc(sizeof(command_stream_t));
    empty->size = 0;
    return empty;
  }
  
  char first;
  char second;
  while (buffer[bufferIteratorT+1] != '\0')
  {
    first = buffer[bufferIteratorT];
    second = buffer[bufferIteratorT+1];

    //Check for &&
    if (first == '&')
      {
        if (second == '&')
          { 
     	    type = AND_TOKEN;
	    bufferIteratorT++;//deals with the fact that && is two chars
          }
        else
          {
	    type = MISC_TOKEN;  //We can test for MISC_TOKEN later, this is an invalid input, only 1 &
          }
      }
    
    //Check for ||
    else if (first == '|')
      {
	if (second == '|')
	  {
	    type = OR_TOKEN;
	    bufferIteratorT++;
          }
	else
	  {
	    type = PIPE_TOKEN;	    
	  }
      }

    else if (first == '#')
      {
	
	if (bufferIteratorT != 0 && isWordChar(buffer[bufferIteratorT-1]))
	  {
	    //if BIT is not 0 , then check if prior is a word, definitely a comment
	    fprintf(stderr,"%i: problem at this line in script\n", linNumber);
	    exit(0);
	  }
	type = COMMENTS_TOKEN;
      	comment = 1;
      }

    else if (first == ';')
      {
	type = SEMICOLON_TOKEN;
      }

    else if (first == '(')
      {
	type = LEFT_PAREN_TOKEN;
      }

    else if (first == ')')
      {
	type = RIGHT_PAREN_TOKEN;
      }

    else if (first == '<')
      {
	type = LESS_TOKEN;
      }

    else if (first == '>')
      {
	type = GREATER_TOKEN;
      }

    else if (first == '\n')
      {
	type = NEWLINE_TOKEN;
	linNumber++;
	comment = 0;
      }

    else //unknown character 
      {
	type = MISC_TOKEN;
      }
    //idea is to figure out how long the word length is and then use token adding part to figure out how far to add the words.  Also, make sure you move ahead in the outer loop.  This will also overwrite MISC_TOKEN if word is found
    int wordlength = 1;
    int placeholder = bufferIteratorT;
    if (isWordChar(first))  
      {
	type = WORD_TOKEN;
	
	while (isWordChar(buffer[bufferIteratorT+wordlength]))
	  {
	    wordlength++;
	  }
        bufferIteratorT += wordlength-1;
	//	printf("placeholder: %d + \n" , placeholder);
	//printf("end: %d \n", bufferIteratorT);
      }

    //token insertion here.
    if (first == ' ' || first == '\t' || comment == 1)
      {
	//Don't insert
      }
    else 
      {
	token temp;
	temp.type = type;
	temp.linNum = linNumber;
	if ( type == WORD_TOKEN)
	  {
	    temp.words = (char*) checked_malloc ((sizeof(char)*wordlength)+1);
	    int i = 0;
	    for (; i != wordlength;i++)
	    {
	    	temp.words[i] = buffer[placeholder+i]; 
	    }
	    temp.words[i] = '\0';
	  }
	else
	  {
	    temp.words = NULL;	
	  }
	//now insert into token stream
	token_stream* temp_ts = (token_stream*) checked_malloc(sizeof(token_stream*));
	temp_ts->m_token = temp;  
	//might have a serious problem here because if m_token is just a copy of 
	//temp and temp gets erased because temp goes out of scope (e.g. out of this function), 
	//temp might get erased and that also deletes our character array for words, leaving a dangling pointer.
	temp_ts->next = NULL;
	temp_ts->prev = trackend;
	trackend->next = temp_ts;
	trackend = temp_ts;
      }
    bufferIteratorT++;
  }
  
  //now tstream should point to the beginning of a token stream
  //the issue is we initialize the tstream to a blank token so happens is the first token_stream in tstream is empty so we skip it.

  tstream = tstream->next;
  
  //=========Code that outputs the tokens so we can test them============//
  
  puts("WORD_TOKEN: 0 \nSEMICOLON_TOKEN: 1 \nPIPE_TOKEN: 2 \nAND_TOKEN: 3 \nOR_TOKEN: 4 \nLEFT_PAREN_TOKEN: 5 \nRIGHT_PAREN_TOKEN: 6 \nGREATER_TOKEN: 7 \nLESS_TOKEN: 8 \nCOMMENTS_TOKEN: 9 \nNEWLINE_TOKEN: 10 \nMISC_TOKEN: 11 \n");
  
  //puts(tstream->m_token.words);
  /*
  while (tstream->next != NULL)
    {
      //printf("%d \n", tstream->m_token.type);
      //the above line works to display just the tokens, the below doesn't work because there's a segfault on accessing the token words
      if (tstream->m_token.type == WORD_TOKEN)
	{
	  printf("%d:%i: ", tstream->m_token.type, tstream->m_token.linNum);
	puts(tstream->m_token.words);
	//puts("\n");
	}
      else
	printf("%d:%i \n", tstream->m_token.type, tstream->m_token.linNum);
    
      tstream = tstream->next;
    }
printf("%d \n", tstream->m_token.type);
  */

  //=========Code that checks for input errors and validates the tokens before parsing tokens into commands============//

  int leftParenCount = 0;
  int rightParenCount = 0;
  while (tstream != NULL)
  {

    //MISC_TOKENS find inputs not in our subset syntax
    if (tstream->m_token.type == MISC_TOKEN)
      {
       fprintf(stderr,"%i: problem at this line in script\n", tstream->m_token.linNum);
       exit(0);
      }

    //Do count of parentheses 
    if (tstream->m_token.type == LEFT_PAREN_TOKEN)
      leftParenCount++;
    if (tstream->m_token.type == RIGHT_PAREN_TOKEN)
      rightParenCount++;
    if (tstream->next == NULL && leftParenCount != rightParenCount)
      {
	fprintf(stderr,"%i: Unmatching Parentheses\n", tstream->m_token.linNum);  //not sure about this
	exit(0);
      }      

    //Redirec always followed by a word.
    if (tstream->m_token.type == LESS_TOKEN || tstream->m_token.type == GREATER_TOKEN)
      {
	if (tstream->next == NULL)
	  {
	    fprintf(stderr,"%i: Redirect Needs a word following it.\n", tstream->m_token.linNum);
	    exit(0);
	  }
	else if (tstream->next->m_token.type != WORD_TOKEN)
          {
	    fprintf(stderr,"%i: Need word after redirect\n", tstream->m_token.linNum);  
	    exit(0);
	  }        
      }
   
    //Newlines have some specific places they can appear in.
    if (tstream->m_token.type == NEWLINE_TOKEN)
      {
	//check the ones after it for ( ) or words
	if (tstream->next != NULL)
	  {
	    if (tstream->next->m_token.type == LEFT_PAREN_TOKEN || tstream->next->m_token.type == RIGHT_PAREN_TOKEN || tstream->next->m_token.type == WORD_TOKEN)
	      {}
	    else
	      {
		fprintf(stderr,"%i: newline is followed by (,), or words\n", tstream->m_token.linNum);  
		exit(0);
	      }        
	  }
      }

    tstream = tstream->next;
  }
  
      // idea here it to represent problems parsing the code with MISC_TOKEN and have code up in the tokenization part where if the 
      //token is a MISC token, store the line number into the char* words array and if we detect it here, then output it with the line number.

  //=========Changes the tokens into commands============//
  command_stream_t fake = (command_stream_t) checked_malloc(sizeof(command_stream_t));
  fake->size = 1;
  fake->iterator = 0;
  return fake;
}
Example #6
0
void	errorlabel(char *label)
{
  my_printf(2, "Undefined reference to the label : %s\n", label);
  exit(EXIT_FAILURE);
}
Example #7
0
/* Most minimal update, forces re-emit of URB fence packet after GS
 * unit turned on/off.
 */
static void recalculate_urb_fence( struct brw_context *brw )
{
   GLuint csize = brw->curbe.total_size;
   GLuint vsize = brw->vs.prog_data->base.urb_entry_size;
   GLuint sfsize = brw->sf.prog_data->urb_entry_size;

   if (csize < limits[CS].min_entry_size)
      csize = limits[CS].min_entry_size;

   if (vsize < limits[VS].min_entry_size)
      vsize = limits[VS].min_entry_size;

   if (sfsize < limits[SF].min_entry_size)
      sfsize = limits[SF].min_entry_size;

   if (brw->urb.vsize < vsize ||
       brw->urb.sfsize < sfsize ||
       brw->urb.csize < csize ||
       (brw->urb.constrained && (brw->urb.vsize > vsize ||
				 brw->urb.sfsize > sfsize ||
				 brw->urb.csize > csize))) {


      brw->urb.csize = csize;
      brw->urb.sfsize = sfsize;
      brw->urb.vsize = vsize;

      brw->urb.nr_vs_entries = limits[VS].preferred_nr_entries;	
      brw->urb.nr_gs_entries = limits[GS].preferred_nr_entries;	
      brw->urb.nr_clip_entries = limits[CLP].preferred_nr_entries;
      brw->urb.nr_sf_entries = limits[SF].preferred_nr_entries;	
      brw->urb.nr_cs_entries = limits[CS].preferred_nr_entries;	

      brw->urb.constrained = 0;

      if (brw->gen == 5) {
         brw->urb.nr_vs_entries = 128;
         brw->urb.nr_sf_entries = 48;
         if (check_urb_layout(brw)) {
            goto done;
         } else {
            brw->urb.constrained = 1;
            brw->urb.nr_vs_entries = limits[VS].preferred_nr_entries;
            brw->urb.nr_sf_entries = limits[SF].preferred_nr_entries;
         }
      } else if (brw->is_g4x) {
	 brw->urb.nr_vs_entries = 64;
	 if (check_urb_layout(brw)) {
	    goto done;
	 } else {
	    brw->urb.constrained = 1;
	    brw->urb.nr_vs_entries = limits[VS].preferred_nr_entries;
	 }
      }

      if (!check_urb_layout(brw)) {
	 brw->urb.nr_vs_entries = limits[VS].min_nr_entries;	
	 brw->urb.nr_gs_entries = limits[GS].min_nr_entries;	
	 brw->urb.nr_clip_entries = limits[CLP].min_nr_entries;
	 brw->urb.nr_sf_entries = limits[SF].min_nr_entries;	
	 brw->urb.nr_cs_entries = limits[CS].min_nr_entries;	

	 /* Mark us as operating with constrained nr_entries, so that next
	  * time we recalculate we'll resize the fences in the hope of
	  * escaping constrained mode and getting back to normal performance.
	  */
	 brw->urb.constrained = 1;
	
	 if (!check_urb_layout(brw)) {
	    /* This is impossible, given the maximal sizes of urb
	     * entries and the values for minimum nr of entries
	     * provided above.
	     */
	    fprintf(stderr, "couldn't calculate URB layout!\n");
	    exit(1);
	 }
	
	 if (unlikely(INTEL_DEBUG & (DEBUG_URB|DEBUG_PERF)))
	    fprintf(stderr, "URB CONSTRAINED\n");
      }

done:
      if (unlikely(INTEL_DEBUG & DEBUG_URB))
	 fprintf(stderr,
                 "URB fence: %d ..VS.. %d ..GS.. %d ..CLP.. %d ..SF.. %d ..CS.. %d\n",
                 brw->urb.vs_start,
                 brw->urb.gs_start,
                 brw->urb.clip_start,
                 brw->urb.sf_start,
                 brw->urb.cs_start,
                 brw->urb.size);

      brw->state.dirty.brw |= BRW_NEW_URB_FENCE;
   }
}
Example #8
0
int main(int argc, char *argv[])  
{  
  bamFile in; 

  if (argc == 1) {  
    fprintf(stderr, "Usage: bam_pe_insert <in.bam>\n");  
    return 1;  
  }  
  int k;
  long num_negative_vals=0;
  long num_alns=0;
  long num_alns_pe=0;
  unsigned int bins[MAX_INSERT_SIZE/BIN_SIZE+1];

  for (k=0;k<=MAX_INSERT_SIZE/BIN_SIZE;++k) bins[k]=0;
  in = bam_open(argv[1], "rb");  
  if (in == 0) {  
    fprintf(stderr, "Fail to open BAM file %s\n", argv[1]);  
    return 1;  
  }  
  int ref;  
  bam_header_t *header;
  header = bam_header_read(in);
  bam1_t *aln=bam_init1();
  while(bam_read1(in,aln)>=0) {
    ++num_alns;
    if (aln->core.tid < 0) continue;
    if (aln->core.flag & BAM_FSECONDARY) continue; // skip secondary alignments
    if (aln->core.flag & ! BAM_FPAIRED) continue; // not paired
    if (aln->core.flag & ! BAM_FPROPER_PAIR) continue; // not a proper pair
    if (aln->core.flag & ! BAM_FMUNMAP) continue; // the mate is mapped
    if (aln->core.flag & BAM_FSECONDARY) continue; // secundary read
    if (aln->core.flag & BAM_FREAD2) continue; // only count each pair once
    if (aln->core.isize<=0) ++num_negative_vals;
    else {
      //printf("%d %d bin=%d pos=%lu matepos=%lu\n",aln->core.flag,aln->core.isize,aln->core.isize/BIN_SIZE,     aln->core.pos,aln->core.mpos);
      if (aln->core.isize>MAX_INSERT_SIZE) {
	++bins[MAX_INSERT_SIZE/BIN_SIZE];
      } else ++bins[aln->core.isize/BIN_SIZE];
      ++num_alns_pe;
    }
  }
  // 
  printf("#Alignments: %lu    #PE alignments: %lu\n",num_alns,num_alns_pe*2);
  printf("#Insert size<0: %lu\n",num_negative_vals);
  if ( !num_alns_pe ) {
    exit(1);
  }
  unsigned long long tot=0;
  for (k=0;k<=MAX_INSERT_SIZE/BIN_SIZE;++k) {
    printf("%d\t%d\n",k*BIN_SIZE,bins[k]);
    tot+=k*BIN_SIZE*bins[k];
  }
  unsigned int avg=tot/num_alns_pe;
  tot=0;
  for (k=0;k<=MAX_INSERT_SIZE/BIN_SIZE;++k) {    
    tot+=((k*BIN_SIZE)-avg)*((k*BIN_SIZE)-avg)*bins[k];
    //if (bins[k]) printf("%ld %lu %lu %lu %ld\n",k*BIN_SIZE,avg,(k*BIN_SIZE),((k*BIN_SIZE)-avg)*((k*BIN_SIZE)-avg),bins[k]);
  }
  unsigned long var=tot/(num_alns_pe-1);
  long int stdev=sqrt(var);
  printf("Avg. insert size: %lu  stdev:%ld\n",avg,stdev);
  bam_destroy1(aln);
  bam_close(in);  
  return 0;  
}  
Example #9
0
/*! This function determines how many particles there are in a given block,
 *  based on the information in the header-structure.  It also flags particle
 *  types that are present in the block in the typelist array. If one wants to
 *  add a new output-block, this function should be augmented accordingly.
 */
int get_particles_in_block(enum iofields blocknr, int *typelist)
{
  int i, nall, ntot_withmasses, ngas, nstars;

  nall = 0;
  ntot_withmasses = 0;

  for(i = 0; i < numtype; i++)
    {
      typelist[i] = 0;

      if(header.npart[i] > 0)
	{
	  nall += header.npart[i];
	  typelist[i] = 1;
	}

      if(All.MassTable[i] == 0)
	ntot_withmasses += header.npart[i];
    }

  ngas = header.npart[0];
  nstars = header.npart[4];


  switch (blocknr)
    {
    case IO_POS:
    case IO_VEL:
    case IO_ACCEL:
    case IO_TSTP:
    case IO_ID:
    case IO_POT:

      return nall;
      break;

    case IO_MASS:
      for(i = 0; i < numtype; i++)
	{
	  typelist[i] = 0;
	  if(All.MassTable[i] == 0 && header.npart[i] > 0)
	    typelist[i] = 1;
	}
      return ntot_withmasses;
      break;

    case IO_U:
    case IO_RHO:
    case IO_HSML:
    case IO_DTENTR:
#ifdef POLYTROPE
    case IO_PRESSURE:
#endif
#ifdef CHEMCOOL
    case IO_CHEM:
    case IO_GAMMA:
#endif
#ifdef METALS_TG
    case IO_METALLICITY:
#endif
#ifdef SINKVAL
     case IO_SINK:
#endif
#ifdef RAYTRACE
    case IO_COLUMN:
#endif
      for(i = 1; i < numtype; i++)
	typelist[i] = 0;
      return ngas;
      break;
    }

  exit(212);
  return 0;
}
Example #10
0
int
main (int argc, char **argv)
{
    int s;
    int c;
    int r;
    int localport = 8888;
    size_t sinsize;
    struct sockaddr_in sin;
    fd_set fds;
    char *host = NAP_SERVER;
    int port = NAP_PORT;

    while ((r = getopt (argc, argv, "hs:p:l:")) != EOF)
    {
        switch (r)
        {
        case 'l':
            localport = atoi (optarg);
            break;
        case 's':
            host = optarg;
            break;
        case 'p':
            port = atoi (optarg);
            break;
        default:
            usage ();
        }
    }

    /* accept connection from client */
    s = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s < 0)
    {
        perror ("socket");
        exit (1);
    }
    c = 1;
    if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &c, sizeof (c)) != 0)
    {
        perror ("setsockopt");
        exit (1);
    }
    memset (&sin, 0, sizeof (sin));
    sin.sin_port = htons (localport);
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = INADDR_ANY;
    if (bind (s, &sin, sizeof (sin)) < 0)
    {
        perror ("bind");
        exit (1);
    }
    if (listen (s, 1) < 0)
    {
        perror ("listen");
        exit (1);
    }
    puts ("waiting for client");
    if (select (s + 1, &fds, 0, 0, 0) < 0)
    {
        perror ("select");
        exit (1);
    }
    sinsize = sizeof (sin);
    c = accept (s, &sin, &sinsize);
    if (c < 0)
    {
        perror ("accept");
        exit (1);
    }
    puts ("got client");

    /* make connection to server */
    printf ("connecting to server...");
    fflush (stdout);
    r = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (r < 0)
    {
        perror ("socket");
        exit (1);
    }
    memset (&sin, 0, sizeof (sin));
    sin.sin_port = htons (port);
    sin.sin_family = AF_INET;
    sin.sin_addr.s_addr = inet_addr (host);
    if (connect (r, &sin, sizeof (sin)) < 0)
    {
        perror ("connect");
        exit (1);
    }
    puts ("connected to server");

    for (;;)
    {
        FD_ZERO (&fds);
        FD_SET (r, &fds);
        FD_SET (c, &fds);
        if (select (((r > c) ? r : c) + 1, &fds, 0, 0, 0) < 0)
        {
            perror ("select");
            break;
        }
        if (FD_ISSET (r, &fds))
        {
            if (pass_message ("server", r, c) != 0)
                break;
        }
        if (FD_ISSET (c, &fds))
        {
            if (pass_message ("client", c, r) != 0)
                break;
        }
    }
    close (r);
    close (s);
    close (c);
    exit (0);
}
Example #11
0
int main(int argc, char *argv[])
{
	int c;
	random_init();
	set_makeflow_exe(argv[0]);
	debug_config(get_makeflow_exe());
	int display_mode = 0;

	cctools_version_debug(D_DEBUG, get_makeflow_exe());
	const char *dagfile;

	int condense_display = 0;
	int change_size = 0;
	int export_as_dax = 0;
	int ppm_mode = 0;
	char *ppm_option = NULL;

	struct option long_options_viz[] = {
		{"display-mode", required_argument, 0, 'D'},
		{"help", no_argument, 0, 'h'},
		{"dot-merge-similar", no_argument, 0,  LONG_OPT_DOT_CONDENSE},
		{"dot-proportional",  no_argument, 0,  LONG_OPT_DOT_PROPORTIONAL},
		{"ppm-highlight-row", required_argument, 0, LONG_OPT_PPM_ROW},
		{"ppm-highlight-exe", required_argument, 0, LONG_OPT_PPM_EXE},
		{"ppm-highlight-file", required_argument, 0, LONG_OPT_PPM_FILE},
		{"ppm-show-levels", no_argument, 0, LONG_OPT_PPM_LEVELS},
		{"export-as-dax", no_argument, 0, 'e'},
		{"version", no_argument, 0, 'v'},
		{0, 0, 0, 0}
	};
	const char *option_string_viz = "b:D:ehv";

	while((c = getopt_long(argc, argv, option_string_viz, long_options_viz, NULL)) >= 0) {
		switch (c) {
			case 'D':
				if(strcasecmp(optarg, "dot") == 0)
					display_mode = SHOW_DAG_DOT;
				else if (strcasecmp(optarg, "ppm") == 0)
					display_mode = SHOW_DAG_PPM;
				else
					fatal("Unknown display option: %s\n", optarg);
				break;
			case LONG_OPT_DOT_CONDENSE:
				display_mode = SHOW_DAG_DOT;
				condense_display = 1;
				break;
			case LONG_OPT_DOT_PROPORTIONAL:
				display_mode = SHOW_DAG_DOT;
				change_size = 1;
				break;
			case LONG_OPT_PPM_EXE:
				display_mode = SHOW_DAG_PPM;
				ppm_option = optarg;
				ppm_mode = 2;
				break;
			case LONG_OPT_PPM_FILE:
				display_mode = SHOW_DAG_PPM;
				ppm_option = optarg;
				ppm_mode = 3;
				break;
			case LONG_OPT_PPM_ROW:
				display_mode = SHOW_DAG_PPM;
				ppm_option = optarg;
				ppm_mode = 4;
				break;
			case LONG_OPT_PPM_LEVELS:
				display_mode = SHOW_DAG_PPM;
				ppm_mode = 5;
				break;
			case 'e':
				export_as_dax = 1;
				break;
			case 'h':
				show_help_viz(get_makeflow_exe());
				return 0;
			case 'v':
				cctools_version_print(stdout, get_makeflow_exe());
				return 0;
			default:
				show_help_viz(get_makeflow_exe());
				return 1;
		}
	}

	if((argc - optind) != 1) {
		int rv = access("./Makeflow", R_OK);
		if(rv < 0) {
			fprintf(stderr, "makeflow: No makeflow specified and file \"./Makeflow\" could not be found.\n");
			fprintf(stderr, "makeflow: Run \"%s -h\" for help with options.\n", get_makeflow_exe());
			return 1;
		}

		dagfile = "./Makeflow";
	} else {
		dagfile = argv[optind];
	}

	struct dag *d = dag_from_file(dagfile);
	if(!d) {
		fatal("makeflow: couldn't load %s: %s\n", dagfile, strerror(errno));
	}

	if(export_as_dax) {
		dag_to_dax(d, path_basename(dagfile));
		return 0;
	}

	if(display_mode)
	{
		switch(display_mode)
		{
			case SHOW_DAG_DOT:
				dag_to_dot(d, condense_display, change_size);
				break;

			case SHOW_DAG_PPM:
				dag_to_ppm(d, ppm_mode, ppm_option);
				break;

			default:
				fatal("Unknown display option.");
				break;
		}
		exit(0);
	}

	return 0;
}
Example #12
0
static void
usage (void)
{
    puts ("usage: spyserv [ -s SERVER ] [ -p SERVERPORT ] [ -l LOCALPORT ]");
    exit (0);
}
Example #13
0
int main(int argc, char **argv)
{
    int i, c, ret, errflag = 0;
    char s[6];
    
    while ((c = getopt_long(argc, argv, "A:F:p:lrRvVw?", longopts, 0)) != EOF)
	switch (c) {
	case 'A': nway_advertise = parse_media(optarg); break;
	case 'F': fixed_speed = parse_media(optarg); break;
	case 'p': override_phy = atoi(optarg); break;
	case 'r': opt_restart++;	break;
	case 'R': opt_reset++;		break;
	case 'v': verbose++;		break;
	case 'V': opt_version++;	break;
	case 'w': opt_watch++;		break;
	case 'l': opt_log++;		break;
	case '?': errflag++;
	}
    /* Check for a few inappropriate option combinations */
    if (opt_watch) verbose = 0;
    if (errflag || (fixed_speed & (fixed_speed-1)) ||
	(fixed_speed && (opt_restart || nway_advertise))) {
	fprintf(stderr, usage, argv[0]);
	return 2;
    }

    if (opt_version)
	printf(version);

    /* Open a basic socket. */
    if ((skfd = socket(AF_INET, SOCK_DGRAM,0)) < 0) {
	perror("socket");
	exit(-1);
    }

    /* No remaining args means show all interfaces. */
    if (optind == argc) {
	ret = 1;
	for (i = 0; i < MAX_ETH; i++) {
	    sprintf(s, "eth%d", i);
	    ret &= do_one_xcvr(skfd, s, 1);
	}
	if (ret)
	    fprintf(stderr, "no MII interfaces found\n");
    } else {
	ret = 0;
	for (i = optind; i < argc; i++) {
	    ret |= do_one_xcvr(skfd, argv[i], 0);
	}
    }

    if (opt_watch && (ret == 0)) {
	while (1) {
	    sleep(1);
	    if (optind == argc) {
		for (i = 0; i < MAX_ETH; i++) {
		    sprintf(s, "eth%d", i);
		    watch_one_xcvr(skfd, s, i);
		}
	    } else {
		for (i = optind; i < argc; i++)
		    watch_one_xcvr(skfd, argv[i], i-optind);
	    }
	}
    }

    close(skfd);
    return ret;
}
Example #14
0
static void
usage(void)
{
	(void)fprintf(stderr, "usage: domainname [ypdomain]\n");
	exit(1);
}
Example #15
0
int main(int ac, char *av[])
{
	//initialize a lot of struct and data points needed
    struct addrinfo *in, *pin;
    struct addrinfo start;
    int sockets[10], socket_num = 0;	
	allocatedMemory[0] = 0;
	myStruct *arg;
	pthread_t dthread;
	pthread_mutex_t *mutex;
	//clear the struct data values
	memset(&start, 0, sizeof start);//clear the object and then check for the right number of arguments passed
	
    if (ac < 3) 
	{
		printf("Usage: %s -p <port>\n", av[0]), exit(0);
	}
	if (ac == 4)
	{
		printf("Usage: %s -p <port> -R <path>\n", av[0]), exit(0);
	}
	else if (ac == 5) 
	{
		path = av[4];
	}
	//set the flags for the correct type of server
    start.ai_flags = AI_PASSIVE | AI_NUMERICSERV | AI_ADDRCONFIG;
    start.ai_protocol = IPPROTO_TCP; // only interested in TCP
    start.ai_family = AF_INET6;
	
	if (strcmp(av[1],"-p"))
		return -1;
	//gets the port number
    char *nport = av[2];

    int gai = getaddrinfo(NULL, nport, &start, &in);
	
    if (gai != 0)
	{
        gai_strerror(gai);
		exit(-1);
	}

    char printed_addr[1024];
    for (pin = in; pin; pin = pin->ai_next) {
        assert (pin->ai_protocol == IPPROTO_TCP);
        int gai = getnameinfo(pin->ai_addr, pin->ai_addrlen,
                             printed_addr, sizeof printed_addr, NULL, 0,
                             NI_NUMERICHOST);
		
        if (gai != 0)
            gai_strerror(gai), exit(-1);

        printf("%s: %s\n", pin->ai_family == AF_INET ? "AF_INET" :
                           pin->ai_family == AF_INET6 ? "AF_INET6" : "?", 
                           printed_addr);

        int s = socket(pin->ai_family, pin->ai_socktype, pin->ai_protocol);
        if (s == -1)
            perror("socket"), exit(-1);

        int opt = 1;
        setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof (opt));

        gai = bind(s, pin->ai_addr, pin->ai_addrlen);
        if (gai == -1 && errno == EADDRINUSE) {
            // ignore Linux limitation
            close(s);
            continue;
        }

        if (gai == -1)
            perror("bind"), exit(-1);
		//begin listening on the socket
        gai = listen(s, 10);
        if (gai == -1)
            perror("listen"), exit(-1);

        assert(socket_num < sizeof(sockets)/sizeof(sockets[0]));
        sockets[socket_num++] = s;
    }
	freeaddrinfo(in);
    assert(socket_num == 1);
	//initialize mutex before accepting
    struct sockaddr_storage rem;
    socklen_t remlen = sizeof (rem);
	
	mutex = malloc(sizeof(pthread_mutex_t));
	pthread_mutex_init(mutex, NULL);
	while(1){
		//accept a connection
		arg = malloc(sizeof(myStruct));
		arg->mutex = mutex;
		//accept the connection
        arg->s = accept (sockets[0], (struct sockaddr *) &rem, &remlen);
		
		//if the connection works
        if (arg->s == -1)
		{
			pthread_mutex_lock(mutex);
            perror ("accept");
			pthread_mutex_unlock(mutex);
			free(arg);
			pthread_mutex_destroy(mutex);
			exit(-1);			
		}
		pthread_mutex_lock(mutex);

        char buffer[200];

		//get information about the connection
        if (getnameinfo ((struct sockaddr *) &rem, remlen, buffer, sizeof (buffer), NULL, 0, 0))
            strcpy (buffer, "???");   // hostname unknown

        char buf2[100];
        (void) getnameinfo ((struct sockaddr *) &rem, remlen, 
                buf2, sizeof (buf2), NULL, 0, NI_NUMERICHOST);
        printf ("connection from %s (%s)\n", buffer, buf2);
		
		
		//create the thread and call the echo functions
		//makes sure to lock and unlock and set the stack size
		pthread_mutex_unlock(mutex);
		arg->attribute = malloc(sizeof(pthread_attr_t));
		pthread_attr_init(arg->attribute);
		pthread_attr_setstacksize(arg->attribute, PTHREAD_STACK_MIN+8192);
		pthread_attr_setdetachstate(arg->attribute, PTHREAD_CREATE_DETACHED);
		pthread_create(&dthread, arg->attribute, echo, arg);
		
    }

    return 0;
}
Example #16
0
int main (int argc, char **argv)
{
  int exoid, num_dim, num_nodes, num_elem, num_elem_blk;
  int num_elem_in_block[10], num_nodes_per_elem[10];
  int num_node_sets, num_side_sets, error;
  int i, j, k, kk, m, *elem_map, *connect;
  int node_list[100],elem_list[100],side_list[100];
  int ebids[10], ssids[10], nsids[10], nattr[10];
  int num_nodes_per_set[10], num_elem_per_set[10];
  int num_df_per_set[10];
  int  num_qa_rec, num_info;
  int num_glo_vars, num_nod_vars, num_ele_vars, num_nset_vars, num_sset_vars;
  int *truth_tab, *nset_tab, *sset_tab;
  int whole_time_step, num_time_steps;
  int CPU_word_size,IO_word_size;
  int prop_array[2];

  float *glob_var_vals, *nodal_var_vals, *elem_var_vals, *nset_var_vals, *sset_var_vals;
  float time_value;
  float x[100], y[100], z[100];
  float attrib[1], dist_fact[100];
  char *coord_names[3], *qa_record[2][4], *info[3], *var_names[7];
  char *prop_names[2];
  char *eb_type[10];
   
  ex_opts (EX_VERBOSE || EX_ABORT);

  /* Specify compute and i/o word size */

  CPU_word_size = 0;                   /* sizeof(float) */
  IO_word_size = 4;                    /* (4 bytes) */

  /* create EXODUS II file */

  exoid = ex_create ("test.exo",       /* filename path */
		     EX_CLOBBER,      /* create mode */
		     &CPU_word_size,  /* CPU float word size in bytes */
		     &IO_word_size);  /* I/O float word size in bytes */
  printf ("after ex_create for test.exo, exoid = %d\n", exoid);
  printf (" cpu word size: %d io word size: %d\n",CPU_word_size,IO_word_size);

  /* ncopts = NC_VERBOSE; */

  /* initialize file with parameters */

  num_dim = 3;
  num_nodes = 33;
  num_elem = 7;
  num_elem_blk = 7;
  num_node_sets = 2;
  num_side_sets = 5;

  error = ex_put_init (exoid, "This is a test", num_dim, num_nodes, num_elem,
		       num_elem_blk, num_node_sets, num_side_sets);

  printf ("after ex_put_init, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* write nodal coordinates values and names to database */

  /* Quad #1 */
  x[0] = 0.0; y[0] = 0.0; z[0] = 0.0;
  x[1] = 1.0; y[1] = 0.0; z[1] = 0.0;
  x[2] = 1.0; y[2] = 1.0; z[2] = 0.0;
  x[3] = 0.0; y[3] = 1.0; z[3] = 0.0;

  /* Quad #2 */
  x[4]  =  1.0; y[4]  =  0.0; z[4]  =  0.0;
  x[5]  =  2.0; y[5]  =  0.0; z[5]  =  0.0;
  x[6]  =  2.0; y[6]  =  1.0; z[6]  =  0.0;
  x[7]  =  1.0; y[7]  =  1.0; z[7]  =  0.0;

  /* Hex #1 */
  x[8]  =  0.0; y[8]  =  0.0; z[8]  =  0.0;
  x[9]  = 10.0; y[9]  =  0.0; z[9]  =  0.0;
  x[10] = 10.0; y[10] =  0.0; z[10] =-10.0;
  x[11] =  1.0; y[11] =  0.0; z[11] =-10.0;
  x[12] =  1.0; y[12] = 10.0; z[12] =  0.0;
  x[13] = 10.0; y[13] = 10.0; z[13] =  0.0;
  x[14] = 10.0; y[14] = 10.0; z[14] =-10.0;
  x[15] =  1.0; y[15] = 10.0; z[15] =-10.0;

  /* Tetra #1 */
  x[16] =  0.0; y[16] =  0.0; z[16] =  0.0;
  x[17] =  1.0; y[17] =  0.0; z[17] =  5.0;
  x[18] = 10.0; y[18] =  0.0; z[18] =  2.0;
  x[19] =  7.0; y[19] =  5.0; z[19] =  3.0;

  /* Wedge #1 */
  x[20] =  3.0; y[20] =  0.0; z[20] =  6.0;
  x[21] =  6.0; y[21] =  0.0; z[21] =  0.0;
  x[22] =  0.0; y[22] =  0.0; z[22] =  0.0;
  x[23] =  3.0; y[23] =  2.0; z[23] =  6.0;
  x[24] =  6.0; y[24] =  2.0; z[24] =  2.0;
  x[25] =  0.0; y[25] =  2.0; z[25] =  0.0;

  /* Tetra #2 */
  x[26] =  2.7; y[26] =  1.7; z[26] =  2.7;
  x[27] =  6.0; y[27] =  1.7; z[27] =  3.3;
  x[28] =  5.7; y[28] =  1.7; z[28] =  1.7;
  x[29] =  3.7; y[29] =  0.0; z[29] =  2.3;

  /* 3d Tri */
  x[30] =  0.0; y[30] =  0.0; z[30] =  0.0;
  x[31] = 10.0; y[31] =  0.0; z[31] =  0.0;
  x[32] = 10.0; y[32] = 10.0; z[32] = 10.0;

  error = ex_put_coord (exoid, x, y, z);
  printf ("after ex_put_coord, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  coord_names[0] = "xcoor";
  coord_names[1] = "ycoor";
  coord_names[2] = "zcoor";

  error = ex_put_coord_names (exoid, coord_names);
  printf ("after ex_put_coord_names, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* write element order map */

  elem_map = (int *) calloc(num_elem, sizeof(int));

  for (i=1; i<=num_elem; i++)
    {
      elem_map[i-1] = i;
    }

  error = ex_put_map (exoid, elem_map);
  printf ("after ex_put_map, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  free (elem_map);


  /* write element block parameters */

  num_elem_in_block[0] = 1;
  num_elem_in_block[1] = 1;
  num_elem_in_block[2] = 1;
  num_elem_in_block[3] = 1;
  num_elem_in_block[4] = 1;
  num_elem_in_block[5] = 1;
  num_elem_in_block[6] = 1;

  num_nodes_per_elem[0] = 4; /* elements in block #1 are 4-node quads  */
  num_nodes_per_elem[1] = 4; /* elements in block #2 are 4-node quads  */
  num_nodes_per_elem[2] = 8; /* elements in block #3 are 8-node hexes  */
  num_nodes_per_elem[3] = 4; /* elements in block #4 are 4-node tetras */
  num_nodes_per_elem[4] = 6; /* elements in block #5 are 6-node wedges */
  num_nodes_per_elem[5] = 8; /* elements in block #6 are 8-node tetras */
  num_nodes_per_elem[6] = 3; /* elements in block #7 are 3-node tris   */

  ebids[0] = 10;
  ebids[1] = 11;
  ebids[2] = 12;
  ebids[3] = 13;
  ebids[4] = 14;
  ebids[5] = 15;
  ebids[6] = 16;

  nattr[0] = nattr[1] = nattr[2] = nattr[3] = 1;
  nattr[4] = nattr[5] = nattr[6] = 1;
   
  eb_type[0] = "quad";
  eb_type[1] = "quad";
  eb_type[2] = "hex";
  eb_type[3] = "tetra";
  eb_type[4] = "wedge";
  eb_type[5] = "tetra";
  eb_type[6] = "tri";
     
  error = ex_put_concat_elem_block (exoid, ebids, eb_type,
				    num_elem_in_block, num_nodes_per_elem,
				    nattr, 0);
  printf ("after ex_put_concat_elem_block, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* write element block properties */

  prop_names[0] = "MATL";
  prop_names[1] = "DENSITY";
  error = ex_put_prop_names(exoid,EX_ELEM_BLOCK,2,prop_names);
  printf ("after ex_put_prop_names, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[0], "MATL", 10);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[1], "MATL", 20);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[2], "MATL", 30);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[3], "MATL", 40);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[4], "MATL", 50);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[5], "MATL", 60);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_ELEM_BLOCK, ebids[6], "MATL", 70);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* write element connectivity */

  connect = (int *) calloc(8, sizeof(int));
  connect[0] = 1; connect[1] = 2; connect[2] = 3; connect[3] = 4;

  error = ex_put_elem_conn (exoid, ebids[0], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  connect[0] = 5; connect[1] = 6; connect[2] = 7; connect[3] = 8;

  error = ex_put_elem_conn (exoid, ebids[1], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 9; connect[1] = 10; connect[2] = 11; connect[3] = 12;
  connect[4] = 13; connect[5] = 14; connect[6] = 15; connect[7] = 16;

  error = ex_put_elem_conn (exoid, ebids[2], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 17; connect[1] = 18; connect[2] = 19; connect[3] = 20;

  error = ex_put_elem_conn (exoid, ebids[3], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 21; connect[1] = 22; connect[2] = 23;
  connect[3] = 24; connect[4] = 25; connect[5] = 26;

  error = ex_put_elem_conn (exoid, ebids[4], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 17; connect[1] = 18; connect[2] = 19; connect[3] = 20;
  connect[4] = 27; connect[5] = 28; connect[6] = 30; connect[7] = 29;

  error = ex_put_elem_conn (exoid, ebids[5], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  connect[0] = 31; connect[1] = 32; connect[2] = 33;

  error = ex_put_elem_conn (exoid, ebids[6], connect);
  printf ("after ex_put_elem_conn, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  free (connect);


  /* write element block attributes */

  attrib[0] = 3.14159;
  error = ex_put_elem_attr (exoid, ebids[0], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  attrib[0] = 6.14159;
  error = ex_put_elem_attr (exoid, ebids[1], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[2], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[3], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[4], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[5], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_elem_attr (exoid, ebids[6], attrib);
  printf ("after ex_put_elem_attr, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* write individual node sets */


  nsids[0] = 20; nsids[1] = 21;
  num_nodes_per_set[0] = 5; num_nodes_per_set[1] = 3;
  num_df_per_set[0] = 5; num_df_per_set[1] = 3;

  error = ex_put_concat_node_sets (exoid, nsids, num_nodes_per_set,
				   num_df_per_set, 0, 0, 0, 0);

  printf ("after ex_put_concat_node_sets, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  node_list[0] = 100; node_list[1] = 101; node_list[2] = 102; 
  node_list[3] = 103; node_list[4] = 104; 

  dist_fact[0] = 1.0; dist_fact[1] = 2.0; dist_fact[2] = 3.0;
  dist_fact[3] = 4.0; dist_fact[4] = 5.0;

  error = ex_put_node_set (exoid, 20, node_list);
  printf ("after ex_put_node_set, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_node_set_dist_fact (exoid, 20, dist_fact);
  printf ("after ex_put_node_set_dist_fact, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  node_list[0] = 200; node_list[1] = 201; node_list[2] = 202; 

  dist_fact[0] = 1.1; dist_fact[1] = 2.1; dist_fact[2] = 3.1;

  error = ex_put_node_set (exoid, 21, node_list);
  printf ("after ex_put_node_set, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_node_set_dist_fact (exoid, 21, dist_fact);
  printf ("after ex_put_node_set_dist_fact, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  error = ex_put_prop(exoid, EX_NODE_SET, 20, "FACE", 4);
  printf ("after ex_put_prop, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_NODE_SET, 21, "FACE", 5);
  printf ("after ex_put_prop, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  prop_array[0] = 1000;
  prop_array[1] = 2000;

  error = ex_put_prop_array(exoid, EX_NODE_SET, "VELOCITY", prop_array);
  printf ("after ex_put_prop_array, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /* Define the sideset params at one time, then write individually */
  ssids[0] = 30;
  ssids[1] = 31;
  ssids[2] = 32;
  ssids[3] = 33;
  ssids[4] = 34;

  num_elem_per_set[0] = 2;
  num_elem_per_set[1] = 2;
  num_elem_per_set[2] = 7;
  num_elem_per_set[3] = 8;
  num_elem_per_set[4] = 10;

  num_df_per_set[0] = 4;
  num_df_per_set[1] = 4;
  num_df_per_set[2] = 0;
  num_df_per_set[3] = 0;
  num_df_per_set[4] = 0;

  error = ex_put_concat_side_sets (exoid, ssids, num_elem_per_set,
				   num_df_per_set, 0, 0, 0, 0, 0);
  printf ("after ex_put_concat_side_sets, error = %d\n", error);

  /* write individual side sets */

  /* side set #1  - quad */

  elem_list[0] = 2; elem_list[1] = 2;

  side_list[0] = 4; side_list[1] = 2;

  dist_fact[0] = 30.0; dist_fact[1] = 30.1; dist_fact[2] = 30.2;
  dist_fact[3] = 30.3;

  error = ex_put_side_set (exoid, 30, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_side_set_dist_fact (exoid, 30, dist_fact);
  printf ("after ex_put_side_set_dist_fact, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* side set #2  - quad, spanning 2 elements  */

  elem_list[0] = 1; elem_list[1] = 2;

  side_list[0] = 2; side_list[1] = 3;

  dist_fact[0] = 31.0; dist_fact[1] = 31.1; dist_fact[2] = 31.2;
  dist_fact[3] = 31.3;

  error = ex_put_side_set (exoid, 31, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_side_set_dist_fact (exoid, 31, dist_fact);
  printf ("after ex_put_side_set_dist_fact, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* side set #3  - hex */

  elem_list[0] = 3; elem_list[1] = 3;
  elem_list[2] = 3; elem_list[3] = 3;
  elem_list[4] = 3; elem_list[5] = 3;
  elem_list[6] = 3;

  side_list[0] = 5; side_list[1] = 3;
  side_list[2] = 3; side_list[3] = 2;
  side_list[4] = 4; side_list[5] = 1;
  side_list[6] = 6;

  error = ex_put_side_set (exoid, 32, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* side set #4  - tetras */

  elem_list[0] = 4; elem_list[1] = 4;
  elem_list[2] = 4; elem_list[3] = 4;
  elem_list[4] = 6; elem_list[5] = 6;
  elem_list[6] = 6; elem_list[7] = 6;

  side_list[0] = 1; side_list[1] = 2;
  side_list[2] = 3; side_list[3] = 4;
  side_list[4] = 1; side_list[5] = 2;
  side_list[6] = 3; side_list[7] = 4;

  error = ex_put_side_set (exoid, 33, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* side set #5  - wedges and tris */

  elem_list[0] = 5; elem_list[1] = 5;
  elem_list[2] = 5; elem_list[3] = 5;
  elem_list[4] = 5; elem_list[5] = 7;
  elem_list[6] = 7; elem_list[7] = 7;
  elem_list[8] = 7; elem_list[9] = 7;

  side_list[0] = 1; side_list[1] = 2;
  side_list[2] = 3; side_list[3] = 4;
  side_list[4] = 5; side_list[5] = 1;
  side_list[6] = 2; side_list[7] = 3;
  side_list[8] = 4; side_list[9] = 5;

  error = ex_put_side_set (exoid, 34, elem_list, side_list);
  printf ("after ex_put_side_set, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_SIDE_SET, 30, "COLOR", 100);
  printf ("after ex_put_prop, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  error = ex_put_prop(exoid, EX_SIDE_SET, 31, "COLOR", 101);
  printf ("after ex_put_prop, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* write QA records; test empty and just blank-filled records */

  num_qa_rec = 2;


  qa_record[0][0] = "TESTWT";
  qa_record[0][1] = "testwt";
  qa_record[0][2] = "07/07/93";
  qa_record[0][3] = "15:41:33";
  qa_record[1][0] = "";
  qa_record[1][1] = "                            ";
  qa_record[1][2] = "";
  qa_record[1][3] = "                        ";

  error = ex_put_qa (exoid, num_qa_rec, qa_record);
  printf ("after ex_put_qa, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* write information records; test empty and just blank-filled records */

  num_info = 3;


  info[0] = "This is the first information record.";
  info[1] = "";
  info[2] = "                                     ";

  error = ex_put_info (exoid, num_info, info);
  printf ("after ex_put_info, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }



  /* write results variables parameters and names */
  num_glo_vars  = 1;
  num_nod_vars  = 2;
  num_ele_vars  = 3;
  num_nset_vars = 4;
  num_sset_vars = 7;

  truth_tab = (int *) calloc ((num_elem_blk  * num_ele_vars),  sizeof(int));
  nset_tab  = (int *) calloc ((num_node_sets * num_nset_vars), sizeof(int));
  sset_tab  = (int *) calloc ((num_side_sets * num_sset_vars), sizeof(int));

  k = 0;
  for (i=0; i<num_elem_blk; i++) {
    for (j=0; j<num_ele_vars; j++) {
      truth_tab[k++] = 1;
    }
  }
   
  k = 0;
  for (i=0; i<num_node_sets; i++) {
    for (j=0; j<num_nset_vars; j++) {
      if (k%2 == 0)
	nset_tab[k++] = 1;
      else
	nset_tab[k++] = 0;
    }
  }
   
  k = 0;
  for (i=0; i<num_side_sets; i++) {
    for (j=0; j<num_sset_vars; j++) {
      if (k%2 == 0)
	sset_tab[k++] = 0;
      else
	sset_tab[k++] = 1;
    }
  }
   
  ex_put_all_var_param(exoid, num_glo_vars, num_nod_vars, num_ele_vars, truth_tab,
		       num_nset_vars, nset_tab, num_sset_vars, sset_tab);
  printf ("after ex_put_all_var_param, error = %d\n", error);

  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  free (truth_tab);
  free (nset_tab);
  free (sset_tab);
   
  var_names[0] = "glo_vars";
  error = ex_put_var_names (exoid, "g", num_glo_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  /*              12345678901234567890123456789012 */
  var_names[0] = "node_variable_a_very_long_name_0";
  var_names[1] = "nod_var1";
  error = ex_put_var_names (exoid, "n", num_nod_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }



  var_names[0] = "ele_var0";
  var_names[1] = "ele_var1";
  var_names[2] = "ele_var2";
  error = ex_put_var_names (exoid, "e", num_ele_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  var_names[0] = "nset_var0";
  var_names[1] = "nset_var1";
  var_names[2] = "nset_var2";
  var_names[3] = "nset_var3";
  error = ex_put_var_names (exoid, "m", num_nset_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }

  var_names[0] = "sset_var0";
  var_names[1] = "sset_var1";
  var_names[2] = "sset_var2";
  var_names[3] = "sset_var3";
  var_names[4] = "sset_var4";
  var_names[5] = "sset_var5";
  var_names[6] = "sset_var6";
  error = ex_put_var_names (exoid, "s", num_sset_vars, var_names);
  printf ("after ex_put_var_names, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }


  /* for each time step, write the analysis results;
   * the code below fills the arrays glob_var_vals, 
   * nodal_var_vals, and elem_var_vals with values for debugging purposes;
   * obviously the analysis code will populate these arrays
   */

  whole_time_step = 1;
  num_time_steps = 10;

  glob_var_vals =  (float *) calloc (num_glo_vars, CPU_word_size);
  nodal_var_vals = (float *) calloc (num_nodes, CPU_word_size);
  elem_var_vals =  (float *) calloc (4, CPU_word_size);
  nset_var_vals =  (float *) calloc (5, CPU_word_size);
  sset_var_vals =  (float *) calloc (10, CPU_word_size);

  for (i=0; i<num_time_steps; i++)
    {
      time_value = (float)(i+1)/100.;

      /* write time value */

      error = ex_put_time (exoid, whole_time_step, &time_value);
      printf ("after ex_put_time, error = %d\n", error);

      if (error) {
	ex_close (exoid);
	exit(-1);
      }

      /* write global variables */

      for (j=0; j<num_glo_vars; j++) {
	glob_var_vals[j] = (float)(j+2) * time_value;
      }

      error = ex_put_glob_vars (exoid, whole_time_step, num_glo_vars, 
				glob_var_vals);
      printf ("after ex_put_glob_vars, error = %d\n", error);

      if (error) {
	ex_close (exoid);
	exit(-1);
      }

      /* write nodal variables */

      for (k=1; k<=num_nod_vars; k++) {
	for (j=0; j<num_nodes; j++) {
	  nodal_var_vals[j] = (float)k + ((float)(j+1) * time_value);
	}

	error = ex_put_nodal_var (exoid, whole_time_step, k, num_nodes,
				  nodal_var_vals);
	printf ("after ex_put_nodal_var, error = %d\n", error);
	if (error) {
	  ex_close (exoid);
	  exit(-1);
	}

      }

      /* write element variables */

      for (k=1; k<=num_ele_vars; k++) {
	for (j=0; j<num_elem_blk; j++) {
	  for (m=0; m<num_elem_in_block[j]; m++) {
	    elem_var_vals[m] = (float)(k+1) + (float)(j+2) + 
	      ((float)(m+1)*time_value);
	  }
	  error = ex_put_elem_var (exoid, whole_time_step, k, ebids[j],
				   num_elem_in_block[j], elem_var_vals);
	  printf ("after ex_put_elem_var, error = %d\n", error);
	  if (error) {
	    ex_close (exoid);
	    exit(-1);
	  }
	}
      }

      /* write nodeset variables */

      kk = 0;
      for (j=0; j<num_node_sets; j++) {
	for (k=0; k<num_nset_vars; k++) {
	  if (kk++ % 2 == 0) {
	    for (m=0; m<num_nodes_per_set[j]; m++) {
	      nset_var_vals[m] = (float)(k+1) + (float)(j+2) + 
		((float)(m+1)*time_value);
	    }
	    error = ex_put_nset_var (exoid, whole_time_step, k+1, nsids[j],
				     num_nodes_per_set[j], nset_var_vals);
	    printf ("after ex_put_nset_var, error = %d\n", error);
	    if (error) {
	      ex_close (exoid);
	      exit(-1);
	    }
	  }
	}
      }

      /* write sideset variables */

      kk = 0;
      for (j=0; j<num_side_sets; j++) {
	for (k=0; k<num_sset_vars; k++) {
	  if (kk++ % 2 != 0) {
	    for (m=0; m<num_elem_per_set[j]; m++) {
	      sset_var_vals[m] = (float)(k+1) + (float)(j+2) + 
		((float)(m+1)*time_value);
	    }
	    error = ex_put_sset_var (exoid, whole_time_step, k+1, ssids[j],
				     num_elem_per_set[j], sset_var_vals);
	    printf ("after ex_put_sset_var, error = %d\n", error);
	    if (error) {
	      ex_close (exoid);
	      exit(-1);
	    }
	  }
	}
      }

      whole_time_step++;

      /* update the data file; this should be done at the end of every time step
       * to ensure that no data is lost if the analysis dies
       */
      error = ex_update (exoid);
      printf ("after ex_update, error = %d\n", error);
      if (error) {
	ex_close (exoid);
	exit(-1);
      }
    }
  free(glob_var_vals);
  free(nodal_var_vals);
  free(elem_var_vals);
  free(nset_var_vals);
  free(sset_var_vals);

  /* close the EXODUS files
   */
  error = ex_close (exoid);
  printf ("after ex_close, error = %d\n", error);
  if (error) {
    ex_close (exoid);
    exit(-1);
  }
  return 0;
}
Example #17
0
File: App.cpp Project: namuol/lite
 void App::run_variable_timestep()
 {
     // TODO!
     cerr << "Variable timestep not implemented yet!" << endl;
     exit(-1);
 }
Example #18
0
/*
 * IOError - fatal I/O error encountered
 */
void IOError( int error )
{
    printf( "\nDOS error[%d] %s\n", error, strerror( error ) );
    exit( 1 );

} /* IOError */
Example #19
0
void	errorvaluereg(char *args)
{
  my_printf(2, "Wrong Value of reg: %s\n", args);
  exit(EXIT_FAILURE);
}
Example #20
0
/* main function */
int main(int argc, char* argv[]) 
{
    clock_t tstart,tend;
    double duration;

    /*flags*/
    bool verb, adj; /* migration(adjoint) flag */
    bool wantwf; /* outputs wavefield snapshots */
    bool wantrecord; /* actually means "need record" */
    bool illum; /* source illumination flag*/
    bool roll; /* survey strategy */
    
    /*I/O*/
    sf_file Fvel;
    sf_file left, right, leftb, rightb;
    sf_file Fsrc, Frcd/*source and record*/;
    sf_file Ftmpwf;
    sf_file Fimg;

    /*axis*/
    sf_axis at, ax, az, as;

    /*grid index variables*/
    int nx, nz, nt, wfnt;
    int nzx, nx2, nz2, n2, m2, m2b, pad1, nk;
    int ix, iz, it, is;
    int nxb, nzb;
    int snpint;
    float dt, dx, dz, wfdt;
    float ox, oz;

    /*source/geophone location*/
    int   spx, spz;
    int   gpz,gpx,gpl; /*geophone depth/x-crd/length*/

    /*Model*/
    sf_complex **lt, **rt;
    sf_complex **ltb, **rtb;

    /*Data*/
    sf_complex ***wavefld;
    sf_complex ***record, **tmprec, **img, **imgsum;
    float **sill;

    /*source*/
    sf_complex *ww;
    float *rr;
    int rectz,rectx,repeat; /*smoothing parameters*/
    float trunc;
    int sht0,shtbgn,shtend,shtnum,shtnum0,shtint,shtcur;

    /*abc boundary*/
    int top,bot,lft,rht;

    /*tmp*/
    int tmpint;

    /*parameter structs*/
    geopar geop;
    mpipar mpip;

    /*MPI*/
    int rank, nodes;
    sf_complex *sendbuf, *recvbuf;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &nodes);

    sf_init(argc, argv);

    if(rank==0) sf_warning("nodes=%d",nodes);

    if (!sf_getbool("verb", &verb)) verb=false; /*verbosity*/
    if (!sf_getbool("adj", &adj)) adj=true; /*migration*/
    if (!sf_getbool("wantwf", &wantwf)) wantwf=false; /*output forward and backward wavefield*/
    if (!sf_getbool("wantrecord", &wantrecord)) wantrecord=true; /*if n, using record data generated by this program */
    if (!sf_getbool("illum", &illum)) illum=false; /*if n, no source illumination applied */
    if (!sf_getbool("roll", &roll)) roll=false; /*if n, receiver is independent of source location and gpl=nx*/
    /* source/receiver info */
    if (!sf_getint("shtbgn", &shtbgn)) sf_error("Need shot starting location on grid!");
    if (!sf_getint("sht0", &sht0)) sht0=shtbgn; /*actual shot origin on grid*/
    if (!sf_getint("shtend", &shtend)) sf_error("Need shot ending location on grid!");
    if (!sf_getint("shtint", &shtint)) sf_error("Need shot interval on grid!");
    shtnum = (int)((shtend-shtbgn)/shtint) + 1;
    shtnum0 = shtnum;
    if (!sf_getint("spz", &spz)) sf_error("Need source depth!");
    if (!sf_getint("gpz", &gpz)) sf_error("Need receiver depth!");
    if (roll) if (!sf_getint("gpl", &gpl)) sf_error("Need receiver length");
    if (!sf_getint("snapinter", &snpint)) snpint=1;     /* snap interval */
    /*--- parameters of source ---*/
    if (!sf_getfloat("srctrunc", &trunc)) trunc=0.4;
    if (!sf_getint("rectz", &rectz)) rectz=1;
    if (!sf_getint("rectx", &rectx)) rectx=1;
    if (!sf_getint("repeat", &repeat)) repeat=0;
    /* abc parameters */
    if (!sf_getint("top", &top)) top=40;
    if (!sf_getint("bot", &bot)) bot=40;
    if (!sf_getint("lft", &lft)) lft=40;
    if (!sf_getint("rht", &rht)) rht=40;

    /*Set I/O file*/
    if (adj) { /* migration */
      if (wantrecord) {
	Frcd = sf_input("input"); /*record from elsewhere*/
	Fsrc  = sf_input("src");   /*source wavelet*/      
      } else {
	Frcd = sf_output("rec"); /*record produced by forward modeling*/
	Fsrc = sf_input("input");   /*source wavelet*/
      }
      Fimg  = sf_output("output");
    } else { /* modeling */
      Fimg = sf_input("input");
      Frcd = sf_output("output");
      Fsrc  = sf_input("src");   /*source wavelet*/      
    }
    left  = sf_input("left");
    right = sf_input("right");
    leftb  = sf_input("leftb");
    rightb = sf_input("rightb");
    Fvel  = sf_input("vel");  /*velocity - just for model dimension*/
    if (wantwf) {
	Ftmpwf  = sf_output("tmpwf");/*wavefield snap*/
    } else {
	Ftmpwf  = NULL;
    }

    /*--- Axes parameters ---*/
    at = sf_iaxa(Fsrc, 1); nt = sf_n(at);  dt = sf_d(at);      
    az = sf_iaxa(Fvel, 1); nzb = sf_n(az); dz = sf_d(az); oz = sf_o(az);
    ax = sf_iaxa(Fvel, 2); nxb = sf_n(ax); dx = sf_d(ax); ox = sf_o(ax);
    nzx = nzb*nxb;
    nz = nzb - top - bot;
    nx = nxb - lft - rht;
    if (!roll) gpl = nx; /* global survey setting */
    /* wavefield axis */
    wfnt = (int)(nt-1)/snpint+1;
    wfdt = dt*snpint;

    /* propagator matrices */
    if (!sf_getint("pad1",&pad1)) pad1=1; /* padding factor on the first axis */
    nz2 = kiss_fft_next_fast_size(nzb*pad1);
    nx2 = kiss_fft_next_fast_size(nxb);
    nk = nz2*nx2; /*wavenumber*/
    if (!sf_histint(left,"n1",&n2) || n2 != nzx) sf_error("Need n1=%d in left",nzx);
    if (!sf_histint(left,"n2",&m2))  sf_error("Need n2= in left");
    if (!sf_histint(right,"n1",&n2) || n2 != m2) sf_error("Need n1=%d in right",m2);
    if (!sf_histint(right,"n2",&n2) || n2 != nk) sf_error("Need n2=%d in right",nk);

    if (!sf_histint(leftb,"n1",&n2) || n2 != nzx) sf_error("Need n1=%d in left",nzx);
    if (!sf_histint(leftb,"n2",&m2b))  sf_error("Need n2= in left");
    if (!sf_histint(rightb,"n1",&n2) || n2 != m2b) sf_error("Need n1=%d in right",m2b);
    if (!sf_histint(rightb,"n2",&n2) || n2 != nk) sf_error("Need n2=%d in right",nk);

    /*check record data*/
    if (adj && wantrecord){
	sf_histint(Frcd,"n1", &tmpint);
	if (tmpint != nt ) sf_error("Error parameter n1 in record!");
	sf_histint(Frcd,"n2", &tmpint);
	if (tmpint != gpl ) sf_error("Error parameter n2 in record!");
	sf_histint(Frcd,"n3", &tmpint);
	if (tmpint != shtnum0 ) sf_error("Error parameter n3 in record!");
    }

    /*allocate memory*/
    ww=sf_complexalloc(nt);
    rr=sf_floatalloc(nzx);
    lt = sf_complexalloc2(nzx,m2);
    rt = sf_complexalloc2(m2,nk);
    ltb = sf_complexalloc2(nzx,m2b);
    rtb = sf_complexalloc2(m2b,nk);
    geop = (geopar) sf_alloc(1, sizeof(*geop));
    mpip = (mpipar) sf_alloc(1, sizeof(*mpip));
    tmprec = sf_complexalloc2(nt, gpl);
    if (shtnum%nodes!=0) {
      shtnum += nodes-shtnum%nodes;
      if (verb) sf_warning("Total shot number is not divisible by total number of nodes! shunum padded to %d.", shtnum);
    }
    if (rank==0) {
      record = sf_complexalloc3(nt, gpl, shtnum);
    } else record = NULL;
    wavefld = sf_complexalloc3(nz, nx, wfnt);
    if (illum) sill = sf_floatalloc2(nz, nx);
    else sill = NULL;
    img = sf_complexalloc2(nz, nx);
    if (adj) {
      imgsum = sf_complexalloc2(nz, nx);
#ifdef _OPENMP
#pragma omp parallel for private(ix,iz)
#endif
	for (ix=0; ix<nx; ix++)
	  for (iz=0; iz<nz; iz++)
	    imgsum[ix][iz] = sf_cmplx(0.,0.);
    }
    /*read from files*/
    sf_complexread(ww,nt,Fsrc);
    sf_complexread(lt[0],nzx*m2,left);
    sf_complexread(rt[0],m2*nk,right);
    sf_complexread(ltb[0],nzx*m2b,leftb);
    sf_complexread(rtb[0],m2b*nk,rightb);
    if(!adj) sf_complexread(img[0],nx*nz,Fimg);
    if (rank==0) {
      if(adj && wantrecord) {
	sf_complexread(record[0][0], shtnum0*gpl*nt, Frcd);
	if (shtnum0%nodes!=0) {
#ifdef _OPENMP
#pragma omp parallel for private(is,ix,it)
#endif
	  for (is=shtnum0; is<shtnum; is++)
	    for (ix=0; ix<gpl; ix++)
	      for (it=0; it<nt; it++)
		record[is][ix][it] = sf_cmplx(0.,0.);
	}
      } else {
#ifdef _OPENMP
#pragma omp parallel for private(is,ix,it)
#endif
	for (is=0; is<shtnum; is++)
	  for (ix=0; ix<gpl; ix++)
	    for (it=0; it<nt; it++)
	      record[is][ix][it] = sf_cmplx(0.,0.);
      }
    }
    
    /*close RSF files*/
    sf_fileclose(Fsrc);
    sf_fileclose(left);
    sf_fileclose(right);
    sf_fileclose(leftb);
    sf_fileclose(rightb);

    /*load constant geopar elements*/
    mpip->cpuid=rank;
    mpip->numprocs=nodes;
    /*load constant geopar elements*/
    geop->nx  = nx;
    geop->nz  = nz;
    geop->nxb = nxb;
    geop->nzb = nzb;
    geop->dx  = dx;
    geop->dz  = dz;
    geop->ox  = ox;
    geop->oz  = oz;
    geop->snpint = snpint;
    geop->spz = spz;
    geop->gpz = gpz;
    geop->gpl = gpl;
    geop->top = top;
    geop->bot = bot;
    geop->lft = lft;
    geop->rht = rht;
    geop->nt = nt;
    geop->dt = dt;
    geop->trunc = trunc;
    geop->shtnum = shtnum;

    /* output RSF files */

    if (rank==0) {
      sf_setn(ax, gpl);
      sf_setn(az, nz);
      as = sf_iaxa(Fvel, 2);
      sf_setn(as,shtnum0);
      sf_setd(as,shtint*dx);
      sf_seto(as,shtbgn*dx+ox);
      
      if (adj) { /* migration */
	if(!wantrecord) {
	  sf_oaxa(Frcd, at, 1);
	  sf_oaxa(Frcd, ax, 2);
	  sf_oaxa(Frcd, as, 3);
	  sf_settype(Frcd,SF_COMPLEX);	
	}
	sf_setn(ax, nx);
	/*write image*/
	sf_oaxa(Fimg, az, 1);
	sf_oaxa(Fimg, ax, 2);
	sf_settype(Fimg,SF_COMPLEX);
      } else { /* modeling */
	sf_oaxa(Frcd, at, 1);
	sf_oaxa(Frcd, ax, 2);
	sf_oaxa(Frcd, as ,3);
	sf_settype(Frcd,SF_COMPLEX);
      }
      
      if (wantwf) {
	sf_setn(ax, nx);
	/*write temp wavefield */
	sf_setn(at, wfnt);
	sf_setd(at, wfdt);
	
	sf_oaxa(Ftmpwf, az, 1);
	sf_oaxa(Ftmpwf, ax, 2);
	sf_oaxa(Ftmpwf, at, 3);
	sf_settype(Ftmpwf,SF_COMPLEX);
      }
    }
    
    tstart = clock();

    for (is=0; is*nodes<shtnum; is++){

      shtcur = is*nodes+rank; // current shot index

      if (shtcur<shtnum0) {
	spx = shtbgn + shtint*(shtcur);
	if (roll)
	  gpx = spx - (int)(gpl/2);
	else
	  gpx = 0;
	geop->spx = spx;
	geop->gpx = gpx;
	
	if (verb) {
	  sf_warning("============================");
	  sf_warning("processing shot #%d", shtcur);
	  sf_warning("nx=%d nz=%d nt=%d", geop->nx, geop->nz, geop->nt);
	  sf_warning("nxb=%d nzb=%d ", geop->nxb, geop->nzb);
	  sf_warning("dx=%f dz=%f dt=%f", geop->dx, geop->dz, geop->dt);
	  sf_warning("top=%d bot=%d lft=%d rht=%d", geop->top, geop->bot, geop->lft, geop->rht);
	  sf_warning("rectz=%d rectx=%d repeat=%d srctrunc=%f",rectz,rectx,repeat,geop->trunc);
	  sf_warning("spz=%d spx=%d gpz=%d gpx=%d gpl=%d", spz, spx, gpz, gpx, gpl);
	  sf_warning("snpint=%d wfdt=%f wfnt=%d ", snpint, wfdt, wfnt);
	  sf_warning("sht0=%d shtbgn=%d shtend=%d shtnum0=%d shtnum=%d", sht0, shtbgn, shtend, shtnum0, shtnum);
	  if (roll) sf_warning("Rolling survey!");
	  else sf_warning("Global survey (gpl=nx)!");
	  if (illum) sf_warning("Using source illumination!");
	  else sf_warning("No source illumination!");
	  sf_warning("============================");
	}
	
	/*generate reflectivity map*/
	reflgen(nzb, nxb, spz+top, spx+lft, rectz, rectx, repeat, rr);
	
	lrosfor2(wavefld, sill, tmprec, verb, lt, rt, m2, geop, ww, rr, pad1, illum);
      }

      if(adj && wantrecord) {
	if (rank==0) sendbuf = record[is*nodes][0];
	else sendbuf = NULL;
	recvbuf = tmprec[0];
	MPI_Scatter(sendbuf, gpl*nt, MPI_COMPLEX, recvbuf, gpl*nt, MPI_COMPLEX, 0, MPI_COMM_WORLD); // tmprec[ix][it] = record[is][ix][it];
      }
      
      if (shtcur<shtnum0) {
	lrosback2(img, wavefld, sill, tmprec, adj, verb, wantwf, ltb, rtb, m2b, geop, pad1, illum);
	if (adj) { /*local image reduction*/
#ifdef _OPENMP
#pragma omp parallel for private(ix,iz)
#endif
	  for (ix=0; ix<nx; ix++) {
	    for (iz=0; iz<nz; iz++) {
#ifdef SF_HAS_COMPLEX_H
	      imgsum[ix][iz] += img[ix][iz];
#else
	      imgsum[ix][iz] = sf_cadd(imgsum[ix][iz],img[ix][iz]);
#endif      
	    }
	  }
	}
      }

      if (!adj || !wantrecord) {
	//	MPI_Barrier(MPI_COMM_WORLD);
	if (rank==0) recvbuf = record[is*nodes][0];
	else recvbuf = NULL;
	sendbuf = tmprec[0];
	MPI_Gather(sendbuf, gpl*nt, MPI_COMPLEX, recvbuf, gpl*nt, MPI_COMPLEX, 0, MPI_COMM_WORLD); // record[is][ix][it] = tmprec[ix][it];
      }

      if (wantwf && shtcur==0)
	sf_complexwrite(wavefld[0][0], wfnt*nx*nz, Ftmpwf);
    } /*shot iteration*/

    MPI_Barrier(MPI_COMM_WORLD);
    /*write record/image*/
    if (adj) {
      if (rank==0) {
#if MPI_VERSION >= 2
	sendbuf = (sf_complex *) MPI_IN_PLACE;
#else /* will fail */
	sendbuf = NULL;
#endif 
	recvbuf = imgsum[0];
      } else {
	sendbuf = imgsum[0];
      	recvbuf = NULL;
      }
      MPI_Reduce(sendbuf, recvbuf, nx*nz, MPI_COMPLEX, MPI_SUM, 0, MPI_COMM_WORLD); 
      if (rank==0)
	sf_complexwrite(imgsum[0], nx*nz, Fimg);
    }

    if (!adj || !wantrecord) {
      if (rank==0)
	sf_complexwrite(record[0][0], shtnum0*gpl*nt, Frcd);
    }

    /*free memory*/
    free(ww); free(rr);
    free(*lt); free(lt);
    free(*rt); free(rt);
    free(*ltb);free(ltb);
    free(*rtb);free(rtb);
    free(geop);free(mpip);
    free(*tmprec); free(tmprec);
    if (rank==0) {free(**record); free(*record); free(record);}
    free(**wavefld); free(*wavefld); free(wavefld);
    if (illum) {
      free(*sill); free(sill);
    }
    free(*img); free(img);
    if (adj) {
      free(*imgsum); free(imgsum);
    }

    tend = clock();
    duration=(double)(tend-tstart)/CLOCKS_PER_SEC;
    sf_warning(">> The CPU time of single shot migration is: %f seconds << ", duration);

    MPI_Finalize();
    exit(0);
}
Example #21
0
File: sim.c Project: dkuo7/CS2200
/**
 * Opens the references file, reads in each line, and dispatches the commands
 * specified as appropriate to the CPU and OS modules.
 */
void sim_readdata(void) {
  FILE *fp;
  char buff[512];

  if ((fp = fopen(filename, "r")) == NULL) {
    PERROR(filename);
    exit(EXIT_FAILURE);
  }

  /* For each line in the file... */
  while (fgets(buff, sizeof(buff), fp) != NULL) {
    char *cmd, *arg1, *arg2, *arg3;
    int pid;
    vaddr_t addr;
    word_t val, val2;
    
    /* Parse command and possible arguments */
    cmd  = strtok(buff, WHITESPACE);
    arg1 = strtok(NULL, WHITESPACE);
    arg2 = strtok(NULL, WHITESPACE);
    arg3 = strtok(NULL, WHITESPACE);

    switch (cmd[0]) {

    /* Create a new process */
    case '@':
      pid = atoi(arg1);
      if (pid < max_jobs) {
        printf("Forking new process %s (pid %d)...\n", arg2, pid);
        proc_fork(pid, arg2);
      } else {
        printf("Too many jobs, not forking new process!\n");
      }
      break;

    /* Load from a memory location */
    case 'l':
      pid = atoi(arg1);
      addr = atoi(arg2);
      val = atoi(arg3) % 256;
      if (pid >= max_jobs) {
        break;
      } else if (current == NULL || current->pid != pid) {
        printf("Switching to %s (pid %d)...\n", proc_getname(pid), pid);
        proc_switch(pid);
      }
      val2 = mem_load(addr);
      if (val2 != val) {
        printf(" ERROR! loaded value did not equal expected!\n");
        /* XXX: Dump a mem image here and quit */
      } else {
        printf("...OK\n");
      }
      break;
      
    /* Store to a memory location */
    case 's':
      pid = atoi(arg1);
      addr = atoi(arg2);
      val = atoi(arg3) % 256;
      if (pid >= max_jobs) {
        break;
      } else if (current == NULL || current->pid != pid) {
        printf("Switching to %s (pid %d)...\n", proc_getname(pid), pid);
        proc_switch(pid);
      }
      mem_store(addr, val);
      printf("...OK\n");

    /* Ignore other commands (for comments and the like */
    default:
      break;
    }
  }

  fclose(fp);
}
Example #22
0
/*
 * check the temporal archname.index
 */
int
pass1(__pmContext *ctxp, char *archname)
{
    int		i;
    char	path[MAXPATHLEN];
    off_t	meta_size = -1;		/* initialize to pander to gcc */
    off_t	log_size = -1;		/* initialize to pander to gcc */
    struct stat	sbuf;
    __pmLogTI	*tip;
    __pmLogTI	*lastp;

    if (vflag)
	fprintf(stderr, "%s: start pass1 (check temporal index)\n", archname);

    if (ctxp->c_archctl->ac_log->l_numti <= 0) {
	fprintf(stderr, "%s: warning temporal index is missing\n", archname);
	return STS_WARNING;
    }

    lastp = NULL;
    for (i = 1; i <= ctxp->c_archctl->ac_log->l_numti; i++) {
	/*
	 * Integrity Checks
	 *
	 * this(tv_sec) < 0
	 * this(tv_usec) < 0 || this(tv_usec) > 999999
	 * this(timestamp) < last(timestamp)
	 * this(timestamp) >= label timestamp
	 * this(vol) >= 0
	 * this(vol) < last(vol)
	 * this(vol) == last(vol) && this(meta) <= last(meta)
	 * this(vol) == last(vol) && this(log) <= last(log)
	 * file_exists(<base>.meta) && this(meta) > file_size(<base>.meta)
	 * file_exists(<base>.this(vol)) &&
	 *		this(log) > file_size(<base>.this(vol))
	 *
	 * Integrity Warnings
	 *
	 * this(vol) != last(vol) && !file_exists(<base>.this(vol))
	 */
	tip = &ctxp->c_archctl->ac_log->l_ti[i-1];
	tv.tv_sec = tip->ti_stamp.tv_sec;
	tv.tv_usec = tip->ti_stamp.tv_usec;
	if (i == 1) {
	    snprintf(path, sizeof(path), "%s.meta", archname);
	    if (stat(path, &sbuf) == 0)
		meta_size = sbuf.st_size;
	    else {
		/* should not get here ... as detected in after pass0 */
		fprintf(stderr, "%s: pass1: botch: cannot open metadata file (%s)\n", pmProgname, path);
		exit(1);
	    }
	}
	if (tip->ti_vol < 0) {
	    fprintf(stderr, "%s.index[entry %d]: illegal negative volume number %d\n",
		    archname, i, tip->ti_vol);
	    index_state = STATE_BAD;
	    log_size = -1;
	}
	else if (lastp == NULL || tip->ti_vol != lastp->ti_vol) { 
	    snprintf(path, sizeof(path), "%s.%d", archname, tip->ti_vol);
	    if (stat(path, &sbuf) == 0)
		log_size = sbuf.st_size;
	    else {
		log_size = -1;
		fprintf(stderr, "%s: file missing or compressed for log volume %d\n", path, tip->ti_vol);
	    }
	}
	if (tip->ti_stamp.tv_sec < 0 || tip->ti_stamp.tv_usec < 0) {
	    fprintf(stderr, "%s.index[entry %d]: illegal negative timestamp value (%d sec, %d usec)\n",
		archname, i, tip->ti_stamp.tv_sec, tip->ti_stamp.tv_usec);
	    index_state = STATE_BAD;
	}
	if (tip->ti_stamp.tv_usec > 999999) {
	    fprintf(stderr, "%s.index[entry %d]: illegal timestamp usec value (%d sec, %d usec)\n",
		archname, i, tip->ti_stamp.tv_sec, tip->ti_stamp.tv_usec);
	    index_state = STATE_BAD;
	}
	if (tip->ti_meta < sizeof(__pmLogLabel)+2*sizeof(int)) {
	    fprintf(stderr, "%s.index[entry %d]: offset to metadata (%ld) before end of label record (%ld)\n",
		archname, i, (long)tip->ti_meta, (long)(sizeof(__pmLogLabel)+2*sizeof(int)));
	    index_state = STATE_BAD;
	}
	if (meta_size != -1 && tip->ti_meta > meta_size) {
	    fprintf(stderr, "%s.index[entry %d]: offset to metadata (%ld) past end of file (%ld)\n",
		archname, i, (long)tip->ti_meta, (long)meta_size);
	    index_state = STATE_BAD;
	}
	if (tip->ti_log < sizeof(__pmLogLabel)+2*sizeof(int)) {
	    fprintf(stderr, "%s.index[entry %d]: offset to log (%ld) before end of label record (%ld)\n",
		archname, i, (long)tip->ti_log, (long)(sizeof(__pmLogLabel)+2*sizeof(int)));
	    index_state = STATE_BAD;
	}
	if (log_size != -1 && tip->ti_log > log_size) {
	    fprintf(stderr, "%s.index[entry %d]: offset to log (%ld) past end of file (%ld)\n",
		archname, i, (long)tip->ti_log, (long)log_size);
	    index_state = STATE_BAD;
	}
	if (log_label.ill_start.tv_sec != 0) {
	    if (__pmTimevalSub(&tip->ti_stamp, &log_label.ill_start) < 0) {
		fprintf(stderr, "%s.index[entry %d]: timestamp (%d.%06d) less than log label timestamp (%d.%06d)\n",
			archname, i,
			(int)tip->ti_stamp.tv_sec, (int)tip->ti_stamp.tv_usec,
			(int)log_label.ill_start.tv_sec, (int)log_label.ill_start.tv_usec);
		index_state = STATE_BAD;
	    }
	}
	if (lastp != NULL) {
	    if (__pmTimevalSub(&tip->ti_stamp, &lastp->ti_stamp) < 0) {
		fprintf(stderr, "%s.index[entry %d]: timestamp (%d.%06d) went backwards in time (from %d.%06d at [entry %d])\n",
			archname, i,
			(int)tip->ti_stamp.tv_sec, (int)tip->ti_stamp.tv_usec,
			(int)lastp->ti_stamp.tv_sec, (int)lastp->ti_stamp.tv_usec, i-1);
		index_state = STATE_BAD;
	    }
	    if (tip->ti_vol < lastp->ti_vol) {
		fprintf(stderr, "%s.index[entry %d]: volume number (%d) decreased (from %d at [entry %d])\n",
			archname, i, tip->ti_vol, lastp->ti_vol, i-1);
		index_state = STATE_BAD;
	    }
	    if (tip->ti_vol == lastp->ti_vol && tip->ti_meta < lastp->ti_meta) {
		fprintf(stderr, "%s.index[entry %d]: offset to metadata (%ld) decreased (from %ld at [entry %d])\n",
			archname, i, (long)tip->ti_meta, (long)lastp->ti_meta, i-1);
		index_state = STATE_BAD;
	    }
	    if (tip->ti_vol == lastp->ti_vol && tip->ti_log < lastp->ti_log) {
		fprintf(stderr, "%s.index[entry %d]: offset to log (%ld) decreased (from %ld at [entry %d])\n",
			archname, i, (long)tip->ti_log, (long)lastp->ti_log, i-1);
		index_state = STATE_BAD;
	    }
	}
	lastp = tip;
    }

    return STS_OK;

}
Example #23
0
/*=== populate_collections_ctr_list =====================================
  Populates poplists associated with Remittance Center text field on miscinfo
  window.
  ===========================================================================*/
int populate_collections_ctr_list()
{
   int  ret_code;
   int  db_value;
   char description[POPLIST_DESCR_LEN];

   num_collections_ctr_codes = 0;

   dbcmd (dbproc1, "select sc.service_center_id, sc_name ") ;
   dbcmd (dbproc1, "from SERVICE_CENTERS sc, SERVICE_CENTER_TYPES sct ");
   dbcmd (dbproc1, "where sc.service_center_id = sct.service_center_id ") ;
   dbfcmd(dbproc1, "and service_center_type = %d", SC_FRONT);

   br_dbsqlexec(dbproc1);
   if (Sybase_error)
   {
      dbcancel(dbproc1);
      return(FAILURE);
   }

   while ((ret_code = dbresults(dbproc1)) != NO_MORE_RESULTS)
   {
      if (ret_code == FAIL)
      {
         dbcancel(dbproc1);
         return(FAILURE);
      }
      else
      {
         dbbind(dbproc1, 1, INTBIND, 0, &db_value);
         dbbind(dbproc1, 2, NTBSTRINGBIND, 0, description);
         while (dbnextrow(dbproc1) != NO_MORE_ROWS)
         {
            num_collections_ctr_codes++;

            /* Increase memory for list structure */
            collections_ctr_list =
               (DB_POPLIST_TYPE *) realloc (collections_ctr_list,
                num_collections_ctr_codes * sizeof (DB_POPLIST_TYPE));
	    if (collections_ctr_list == NULL) 
	      {
		printf("realloc of collections_ctr_list FAILED %d\n",
			num_collections_ctr_codes);
		exit(1) ;
	      }

            /* Increase memory for XmString structure */
            collections_ctr_strings =
               (XmString *) realloc (collections_ctr_strings,
               num_collections_ctr_codes * sizeof (XmString));
	    if (collections_ctr_strings == NULL) 
	      {
		printf("realloc of serv_ctcollections_ctr_strings FAILED %d\n",
			num_collections_ctr_codes);
		exit(1) ;
	    }

            /* Fill in list structre */
            collections_ctr_list[num_collections_ctr_codes-1].db_code =
               db_value;
            strcpy
               (collections_ctr_list[num_collections_ctr_codes-1].description,
               description);

            /* Fill in XmString structure */
            collections_ctr_strings[num_collections_ctr_codes-1] =
	      XmStringCreateSimple(description);

	    collections_ctr_default = 0 ;
         } /* end while dbnextrow */
      } /* end else */
   } /* end while dbresuls */

   return(SUCCESS);

} /* end populate_collections_ctr_list */
Example #24
0
/*
 * We will eventually be called from inetd or via the rc scripts directly
 * Parse arguments and act appropiately.
 */
int
main(int argc, char **argv)
{
    extern char *optarg;
    FILE *fp;
    int	c, *s, ns;
    struct pollfd *pfds;

#if PROFILE
    moncontrol(0);
#endif

    if ((progname = strrchr(*argv, '/')) != NULL) {
	progname++;
    } else
	progname = *argv;

    /* initialise global session data */
    memset(&session, 0, sizeof(session));
    session.peer = tac_strdup("unknown");


    if (argc <= 1) {
	usage();
	tac_exit(1);
    }

    while ((c = getopt(argc, argv, "B:C:d:hiPp:tGgvSsLw:u:")) != EOF)
	switch (c) {
	case 'B':		/* bind() address*/
	    bind_address = optarg;
	    break;
	case 'L':		/* lookup peer names via DNS */
	    lookup_peer = 1;
	    break;
	case 's':		/* don't respond to sendpass */
	    sendauth_only = 1;
	    break;
	case 'v':		/* print version and exit */
	    vers();
	    tac_exit(1);
	case 't':
	    console = 1;	/* log to console too */
	    break;
	case 'P':		/* Parse config file only */
	    parse_only = 1;
	    break;
	case 'G':		/* foreground */
	    opt_G = 1;
	    break;
	case 'g':		/* single threaded */
	    single = 1;
	    break;
	case 'p':		/* port */
	    port = atoi(optarg);
	    portstr = optarg;
	    break;
	case 'd':		/* debug */
	    debug |= atoi(optarg);
	    break;
	case 'C':		/* config file name */
	    session.cfgfile = tac_strdup(optarg);
	    break;
	case 'h':		/* usage */
	    usage();
	    tac_exit(0);
	case 'i':		/* inetd mode */
	    standalone = 0;
	    break;
	case 'S':		/* enable single-connection */
	    opt_S = 1;
	    break;
#ifdef MAXSESS
	case 'w':		/* wholog file */
	    wholog = tac_strdup(optarg);
	    break;
#endif
	case 'u':
	    wtmpfile = tac_strdup(optarg);
	    break;

	default:
	    fprintf(stderr, "%s: bad switch %c\n", progname, c);
	    usage();
	    tac_exit(1);
	}

    parser_init();

    /* read the configuration/etc */
    init();
#if defined(REAPCHILD) && defined(REAPSIGIGN)
    client_count_init();
#endif
    open_logfile();

    signal(SIGUSR1, handler);
    signal(SIGHUP, handler);
    signal(SIGUSR2, dump_clients_handler);
    signal(SIGTERM, die);
    signal(SIGPIPE, SIG_IGN);

    if (parse_only)
	tac_exit(0);

    if (debug)
	report(LOG_DEBUG, "tac_plus server %s starting", version);

    if (!standalone) {
	/* running under inetd */
	char host[NI_MAXHOST];
	int on;
#ifdef IPV6
	struct sockaddr_in6 name;
#else
  struct sockaddr_in name;
#endif
	socklen_t name_len;

	name_len = sizeof(name);
	session.flags |= SESS_NO_SINGLECONN;

	session.sock = 0;
#ifdef IPV6
	if (getpeername(session.sock, (struct sockaddr6 *)&name, &name_len)) {
	    report(LOG_ERR, "getpeername failure %s", strerror(errno));
#else
	if (getpeername(session.sock, (struct sockaddr *)&name, &name_len)) {
	    report(LOG_ERR, "getpeername failure %s", strerror(errno));
#endif
	} else {
	    if (lookup_peer)
		on = 0;
	    else
		on = NI_NUMERICHOST;
#ifdef IPV6
	    if (getnameinfo((struct sockaddr6 *)&name, name_len, host, 128,
			    NULL, 0, on)) {
#else
	    if (getnameinfo((struct sockaddr *)&name, name_len, host, 128,
			    NULL, 0, on)) {
#endif
		strncpy(host, "unknown", NI_MAXHOST - 1);
		host[NI_MAXHOST - 1] = '\0';
	    }
	    if (session.peer) free(session.peer);
	    session.peer = tac_strdup(host);

	    if (session.peerip) free(session.peerip);
#ifdef IPV6
	    session.peerip = tac_strdup((char *)inet_ntop(name.sin6_family,
					&name.sin6_addr, host, name_len));
#else
	    session.peerip = tac_strdup((char *)inet_ntop(name.sin_family,
					&name.sin_addr, host, name_len));
#endif
	    if (debug & DEBUG_AUTHEN_FLAG)
		report(LOG_INFO, "session.peerip is %s", session.peerip);
	}
#ifdef FIONBIO
	on = 1;
	if (ioctl(session.sock, FIONBIO, &on) < 0) {
	    report(LOG_ERR, "ioctl(FIONBIO) %s", strerror(errno));
	    tac_exit(1);
	}
#endif
	start_session();
	tac_exit(0);
 }

    if (single) {
	session.flags |= SESS_NO_SINGLECONN;
    } else {
	/*
	 * Running standalone; background ourselves and release controlling
	 * tty, unless -G option was specified to keep the parent in the
	 * foreground.
	 */
#ifdef SIGTTOU
	signal(SIGTTOU, SIG_IGN);
#endif
#ifdef SIGTTIN
	signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTSTP
	signal(SIGTSTP, SIG_IGN);
#endif
	if (!opt_S)
	    session.flags |= SESS_NO_SINGLECONN;

	if (!opt_G) {
	    if ((childpid = fork()) < 0)
		report(LOG_ERR, "Can't fork first child");
	    else if (childpid > 0)
		exit(0);		/* parent */

	    if (debug)
		report(LOG_DEBUG, "Backgrounded");

#if SETPGRP_VOID
	    if (setpgrp() == -1)
#else
	    if (setpgrp(0, getpid()) == -1)
#endif /* SETPGRP_VOID */
		report(LOG_ERR, "Can't change process group: %s",
		       strerror(errno));

	    /* XXX What does "REAPCHILD" have to do with TIOCNOTTY? */
#ifndef REAPCHILD
	    c = open("/dev/tty", O_RDWR);
	    if (c >= 0) {
		ioctl(c, TIOCNOTTY, (char *)0);
		(void) close(c);
	    }
#else /* REAPCHILD */
	    if ((childpid = fork()) < 0)
		report(LOG_ERR, "Can't fork second child");
	    else if (childpid > 0)
		exit(0);

	    if (debug & DEBUG_FORK_FLAG)
		report(LOG_DEBUG, "Forked grandchild");

#endif /* REAPCHILD */

	    /* some systems require this */
	    closelog();

	    for (c = getdtablesize(); c >= 0; c--)
		(void)close(c);

	    /*
	     * make sure we can still log to syslog now that we have closed
	     * everything
	     */
	    open_logfile();
	}
    }
#if REAPCHILD
#if REAPSIGIGN
    signal(SIGCHLD, reapchild);
#else
    signal(SIGCHLD, SIG_IGN);
#endif
#endif

    ostream = NULL;
    /* chdir("/"); */
    umask(022);
    errno = 0;

    get_socket(&s, &ns);

#ifndef SOMAXCONN
#define SOMAXCONN 5
#endif

    for (c = 0; c < ns; c++) {
	if (listen(s[c], SOMAXCONN) < 0) {
	    console = 1;
	report(LOG_ERR, "listen: %s", strerror(errno));
	tac_exit(1);
    }
    }

    if (port == TAC_PLUS_PORT) {
	if (bind_address == NULL) {
	    strncpy(pidfilebuf, TACPLUS_PIDFILE, PIDSZ);
	    if (pidfilebuf[PIDSZ - 1] != '\0')
		c = PIDSZ;
	    else
		c = PIDSZ - 1;
	} else
	    c = snprintf(pidfilebuf, PIDSZ, "%s.%s", TACPLUS_PIDFILE,
			 bind_address);
    } else {
	if (bind_address == NULL)
	    c = snprintf(pidfilebuf, PIDSZ, "%s.%d", TACPLUS_PIDFILE, port);
	else
	    c = snprintf(pidfilebuf, PIDSZ, "%s.%s.%d", TACPLUS_PIDFILE,
			 bind_address, port);
    }
    if (c >= PIDSZ) {
	pidfilebuf[PIDSZ - 1] = '\0';
	report(LOG_ERR, "pid filename truncated: %s", pidfilebuf);
	childpid = 0;
    } else {
	/* write process id to pidfile */
	if ((fp = fopen(pidfilebuf, "w")) != NULL) {
	    fprintf(fp, "%d\n", (int)getpid());
	    fclose(fp);
	    /*
	     * After forking to disassociate; make sure we know we're the
	     * mother so that we remove our pid file upon exit in die().
	     */
	    childpid = 1;
	} else {
	    report(LOG_ERR, "Cannot write pid to %s %s", pidfilebuf,
		   strerror(errno));
	    childpid = 0;
	}
    }
#ifdef TACPLUS_GROUPID
    if (setgid(TACPLUS_GROUPID))
	report(LOG_ERR, "Cannot set group id to %d %s",
	       TACPLUS_GROUPID, strerror(errno));
#endif

#ifdef TACPLUS_USERID
    if (setuid(TACPLUS_USERID))
	report(LOG_ERR, "Cannot set user id to %d %s",
	       TACPLUS_USERID, strerror(errno));
#endif

#ifdef MAXSESS
    maxsess_loginit();
#endif /* MAXSESS */

    report(LOG_DEBUG, "uid=%d euid=%d gid=%d egid=%d s=%d",
	   getuid(), geteuid(), getgid(), getegid(), s);

    pfds = malloc(sizeof(struct pollfd) * ns);
    if (pfds == NULL) {
	report(LOG_ERR, "malloc failure: %s", strerror(errno));
	tac_exit(1);
    }
    for (c = 0; c < ns; c++) {
	pfds[c].fd = s[c];
	pfds[c].events = POLLIN | POLLERR | POLLHUP | POLLNVAL;
    }

    for (;;) {
#if HAVE_PID_T
	pid_t pid;
#else
	int pid;
#endif
	char host[NI_MAXHOST];
#ifdef IPV6
	struct sockaddr_in6 from;
#else
	struct sockaddr_in from;
#endif
	socklen_t from_len;
	int newsockfd, status;
	int flags;
  int procs_for_client;

#if defined(REAPCHILD) && defined(REAPSIGIGN)
  if (reap_children)
    reapchildren();
#endif

	if (reinitialize)
	    init();

  if (dump_client_table) {
    report(LOG_ALERT, "Dumping Client Tables");
    dump_client_tables();
    dump_client_table = 0;
  }

	status = poll(pfds, ns, cfg_get_accepttimeout() * 1000);
	if (status == 0)
	    continue;
	if (status == -1)
	    if (errno == EINTR)
		continue;

	from_len = sizeof(from);
	memset((char *)&from, 0, from_len);
	for (c = 0; c < ns; c++) {
	    if (pfds[c].revents & POLLIN)
  #ifdef IPV6
		newsockfd = accept(s[c], (struct sockaddr6 *)&from, &from_len);
  #else
		newsockfd = accept(s[c], (struct sockaddr *)&from, &from_len);
  #endif
	    else if (pfds[c].revents & (POLLERR | POLLHUP | POLLNVAL)) {
		report(LOG_ERR, "exception on listen FD %d", s[c]);
		tac_exit(1);
	    }
	}

	if (newsockfd < 0) {
	    if (errno == EINTR)
		continue;

	    report(LOG_ERR, "accept: %s", strerror(errno));
	    continue;
	}

	if (lookup_peer)
	    flags = 0;
	else
	    flags = NI_NUMERICHOST;
#ifdef IPV6
	if (getnameinfo((struct sockaddr_in6 *)&from, from_len, host, 128, NULL, 0,
			flags)) {
#else
	if (getnameinfo((struct sockaddr_in *)&from, from_len, host, 128, NULL, 0,
			flags)) {
#endif
	    strncpy(host, "unknown", NI_MAXHOST - 1);
	    host[NI_MAXHOST - 1] = '\0';
	}

	if (session.peer) free(session.peer);
	session.peer = tac_strdup(host);

	if (session.peerip) free(session.peerip);
#ifdef IPV6
	session.peerip = tac_strdup((char *)inet_ntop(from.sin6_family,
          &from.sin6_addr, host, INET6_ADDRSTRLEN));
#else
	session.peerip = tac_strdup((char *)inet_ntop(from.sin_family,
          &from.sin_addr, host, INET_ADDRSTRLEN));
#endif
	if (debug & DEBUG_PACKET_FLAG)
	    report(LOG_DEBUG, "session request from %s sock=%d",
		   session.peer, newsockfd);

	if (!single) {
#if defined(REAPCHILD) && defined(REAPSIGIGN)
      /* first we check the tocal process count to see if we are at the limit */
      if (total_child_count >= cfg_get_maxprocs()) {
        report(LOG_ALERT, "refused connection from %s [%s] at global max procs [%d]",
          session.peer, session.peerip, total_child_count);
        shutdown(newsockfd, 2);
        close(newsockfd);
        continue;
      }
      /* no we check the process count per client */
      procs_for_client = get_client_count(session.peerip);
      report(LOG_ALERT, "connection [%d] from %s [%s]", procs_for_client + 1, session.peer, session.peerip);
      if (procs_for_client >= cfg_get_maxprocsperclt()) {
        report(LOG_ALERT, "refused connection from %s [%s] at client max procs [%d]",
          session.peer, session.peerip, procs_for_client);
        shutdown(newsockfd, 2);
        close(newsockfd);
        continue;
      }
#endif
	    pid = fork();
	    if (pid < 0) {
		    report(LOG_ERR, "fork error");
		    tac_exit(1);
	    }
	} else {
	    pid = 0;
	}
	if (pid == 0) {
	  /* child */
	  if (!single) {
            if (ns > 1) {
              for (c = 0; c < ns; c++) {
                close(s[c]);
              }
            }
          }
	  session.sock = newsockfd;
#ifdef LIBWRAP
	  if (! hosts_ctl(progname,session.peer,session.peerip,progname)) {
		  report(LOG_ALERT, "refused connection from %s [%s]",
		       session.peer, session.peerip);
      shutdown(session.sock, 2);
      close(session.sock);
      if (!single) {
          tac_exit(0);
      } else {
          close(session.sock);
          continue;
      }
    }
    if (debug)
      report(LOG_DEBUG, "connect from %s [%s]", session.peer, session.peerip);
#endif
#if PROFILE
	    moncontrol(1);
#endif

	    start_session();
	    shutdown(session.sock, 2);
	    close(session.sock);
	    if (!single)
		    tac_exit(0);
	} else {
	    /* parent */
#if defined(REAPCHILD) && defined(REAPSIGIGN)
      total_child_count++;
      procs_for_client = increment_client_count_for_proc(pid, session.peerip);
      snprintf(msgbuf, MSGBUFSZ, "forked %lu for %s, procs %d, procs for client %d",
            (long)pid, session.peerip, total_child_count, procs_for_client);
		    report(LOG_DEBUG, msgbuf);
#endif
	    close(newsockfd);
	}
    }
}