Ejemplo n.º 1
0
/**
 * @brief This method performs one transport sweep of all azimuthal angles,
 *        Tracks, Track segments, polar angles and energy groups.
 * @details The method integrates the flux along each Track and updates the
 *          boundary fluxes for the corresponding output Track, while updating
 *          the scalar flux in each flat source region.
 */
void CPUSolver::transportSweep() {

  int tid;
  int min_track, max_track;
  Track* curr_track;
  int azim_index;
  int num_segments;
  segment* curr_segment;
  segment* segments;
  FP_PRECISION* track_flux;

  log_printf(DEBUG, "Transport sweep with %d OpenMP threads", _num_threads);

  /* Initialize flux in each FSr to zero */
  flattenFSRFluxes(0.0);

  if (_cmfd != NULL && _cmfd->isFluxUpdateOn())
    zeroSurfaceCurrents();

  /* Loop over azimuthal angle halfspaces */
  for (int i=0; i < 2; i++) {

    /* Compute the minimum and maximum Track IDs corresponding to
     * this azimuthal angular halfspace */
    min_track = i * (_tot_num_tracks / 2);
    max_track = (i + 1) * (_tot_num_tracks / 2);

    /* Loop over each thread within this azimuthal angle halfspace */
    #pragma omp parallel for private(curr_track, azim_index, num_segments, \
      curr_segment, segments, track_flux, tid) schedule(guided)
    for (int track_id=min_track; track_id < max_track; track_id++) {

      tid = omp_get_thread_num();

      /* Use local array accumulator to prevent false sharing*/
      FP_PRECISION* thread_fsr_flux;
      thread_fsr_flux = new FP_PRECISION[_num_groups];

      /* Initialize local pointers to important data structures */
      curr_track = _tracks[track_id];
      azim_index = curr_track->getAzimAngleIndex();
      num_segments = curr_track->getNumSegments();
      segments = curr_track->getSegments();
      track_flux = &_boundary_flux(track_id,0,0,0);

      /* Loop over each Track segment in forward direction */
      for (int s=0; s < num_segments; s++) {
        curr_segment = &segments[s];
        scalarFluxTally(curr_segment, azim_index, track_flux,
                        thread_fsr_flux, true);
      }

      /* Transfer boundary angular flux to outgoing Track */
      transferBoundaryFlux(track_id, azim_index, true, track_flux);

      /* Loop over each Track segment in reverse direction */
      track_flux += _polar_times_groups;

      for (int s=num_segments-1; s > -1; s--) {
        curr_segment = &segments[s];
        scalarFluxTally(curr_segment, azim_index, track_flux,
                        thread_fsr_flux, false);
      }
      delete thread_fsr_flux;

      /* Transfer boundary angular flux to outgoing Track */
      transferBoundaryFlux(track_id, azim_index, false, track_flux);
    }
  }

  return;
}
int main (int argc,char *argv[])
{
	const char *progname,*filename = NULL,*device = NULL;
	int i,flags = FLAG_NONE;
	ssize_t result;
	size_t size,written;
	struct mtd_info_user mtd;
	struct erase_info_user erase;
	struct stat filestat;
	unsigned char src[BUFSIZE],dest[BUFSIZE];

	(progname = strrchr (argv[0],'/')) ? progname++ : (progname = argv[0]);

	/*********************
	 * parse cmd-line
	 *****************/

	for (;;) {
		int option_index = 0;
		static const char *short_options = "hv";
		static const struct option long_options[] = {
			{"help", no_argument, 0, 'h'},
			{"verbose", no_argument, 0, 'v'},
			{0, 0, 0, 0},
		};

		int c = getopt_long(argc, argv, short_options,
				long_options, &option_index);
		if (c == EOF) {
			break;
		}

		switch (c) {
			case 'h':
				flags |= FLAG_HELP;
				DEBUG("Got FLAG_HELP\n");
				break;
			case 'v':
				flags |= FLAG_VERBOSE;
				DEBUG("Got FLAG_VERBOSE\n");
				break;
			default:
				DEBUG("Unknown parameter: %s\n",argv[option_index]);
				showusage (progname,true);
		}
	}
	if (optind+2 == argc) {
		flags |= FLAG_FILENAME;
		filename = argv[optind];
		DEBUG("Got filename: %s\n",filename);

		flags |= FLAG_DEVICE;
		device = argv[optind+1];
		DEBUG("Got device: %s\n",device);
	}

	if (flags & FLAG_HELP || progname == NULL || device == NULL)
		showusage (progname,flags != FLAG_HELP);

	atexit (cleanup);

	/* get some info about the flash device */
	dev_fd = safe_open (device,O_SYNC | O_RDWR);
	if (ioctl (dev_fd,MEMGETINFO,&mtd) < 0)
	{
		DEBUG("ioctl(): %m\n");
		log_printf (LOG_ERROR,"This doesn't seem to be a valid MTD flash device!\n");
		exit (EXIT_FAILURE);
	}

	/* get some info about the file we want to copy */
	fil_fd = safe_open (filename,O_RDONLY);
	if (fstat (fil_fd,&filestat) < 0)
	{
		log_printf (LOG_ERROR,"While trying to get the file status of %s: %m\n",filename);
		exit (EXIT_FAILURE);
	}

	/* does it fit into the device/partition? */
	if (filestat.st_size > mtd.size)
	{
		log_printf (LOG_ERROR,"%s won't fit into %s!\n",filename,device);
		exit (EXIT_FAILURE);
	}

	/*****************************************************
	 * erase enough blocks so that we can write the file *
	 *****************************************************/

#warning "Check for smaller erase regions"

	erase.start = 0;
	erase.length = (filestat.st_size + mtd.erasesize - 1) / mtd.erasesize;
	erase.length *= mtd.erasesize;

	if (flags & FLAG_VERBOSE)
	{
		/* if the user wants verbose output, erase 1 block at a time and show him/her what's going on */
		int blocks = erase.length / mtd.erasesize;
		erase.length = mtd.erasesize;
		log_printf (LOG_NORMAL,"Erasing blocks: 0/%d (0%%)",blocks);
		for (i = 1; i <= blocks; i++)
		{
			log_printf (LOG_NORMAL,"\rErasing blocks: %d/%d (%d%%)",i,blocks,PERCENTAGE (i,blocks));
			if (ioctl (dev_fd,MEMERASE,&erase) < 0)
			{
				log_printf (LOG_NORMAL,"\n");
				log_printf (LOG_ERROR,
						"While erasing blocks 0x%.8x-0x%.8x on %s: %m\n",
						(unsigned int) erase.start,(unsigned int) (erase.start + erase.length),device);
				exit (EXIT_FAILURE);
			}
			erase.start += mtd.erasesize;
		}
		log_printf (LOG_NORMAL,"\rErasing blocks: %d/%d (100%%)\n",blocks,blocks);
	}
	else
	{
		/* if not, erase the whole chunk in one shot */
		if (ioctl (dev_fd,MEMERASE,&erase) < 0)
		{
			log_printf (LOG_ERROR,
					"While erasing blocks from 0x%.8x-0x%.8x on %s: %m\n",
					(unsigned int) erase.start,(unsigned int) (erase.start + erase.length),device);
			exit (EXIT_FAILURE);
		}
	}
	DEBUG("Erased %u / %luk bytes\n",erase.length,filestat.st_size);

	/**********************************
	 * write the entire file to flash *
	 **********************************/

	if (flags & FLAG_VERBOSE) log_printf (LOG_NORMAL,"Writing data: 0k/%luk (0%%)",KB (filestat.st_size));
	size = filestat.st_size;
	i = BUFSIZE;
	written = 0;
	while (size)
	{
		if (size < BUFSIZE) i = size;
		if (flags & FLAG_VERBOSE)
			log_printf (LOG_NORMAL,"\rWriting data: %dk/%luk (%lu%%)",
					KB (written + i),
					KB (filestat.st_size),
					PERCENTAGE (written + i,filestat.st_size));

		/* read from filename */
		safe_read (fil_fd,filename,src,i,flags & FLAG_VERBOSE);

		/* write to device */
		result = write (dev_fd,src,i);
		if (i != result)
		{
			if (flags & FLAG_VERBOSE) log_printf (LOG_NORMAL,"\n");
			if (result < 0)
			{
				log_printf (LOG_ERROR,
						"While writing data to 0x%.8x-0x%.8x on %s: %m\n",
						written,written + i,device);
				exit (EXIT_FAILURE);
			}
			log_printf (LOG_ERROR,
					"Short write count returned while writing to x%.8x-0x%.8x on %s: %d/%lu bytes written to flash\n",
					written,written + i,device,written + result,filestat.st_size);
			exit (EXIT_FAILURE);
		}

		written += i;
		size -= i;
	}
	if (flags & FLAG_VERBOSE)
		log_printf (LOG_NORMAL,
				"\rWriting data: %luk/%luk (100%%)\n",
				KB (filestat.st_size),
				KB (filestat.st_size));
	DEBUG("Wrote %d / %luk bytes\n",written,filestat.st_size);

	/**********************************
	 * verify that flash == file data *
	 **********************************/

	safe_rewind (fil_fd,filename);
	safe_rewind (dev_fd,device);
	size = filestat.st_size;
	i = BUFSIZE;
	written = 0;
	if (flags & FLAG_VERBOSE) log_printf (LOG_NORMAL,"Verifying data: 0k/%luk (0%%)",KB (filestat.st_size));
	while (size)
	{
		if (size < BUFSIZE) i = size;
		if (flags & FLAG_VERBOSE)
			log_printf (LOG_NORMAL,
					"\rVerifying data: %dk/%luk (%lu%%)",
					KB (written + i),
					KB (filestat.st_size),
					PERCENTAGE (written + i,filestat.st_size));

		/* read from filename */
		safe_read (fil_fd,filename,src,i,flags & FLAG_VERBOSE);

		/* read from device */
		safe_read (dev_fd,device,dest,i,flags & FLAG_VERBOSE);

		/* compare buffers */
		if (memcmp (src,dest,i))
		{
			log_printf (LOG_ERROR,
					"File does not seem to match flash data. First mismatch at 0x%.8x-0x%.8x\n",
					written,written + i);
			exit (EXIT_FAILURE);
		}

		written += i;
		size -= i;
	}
	if (flags & FLAG_VERBOSE)
		log_printf (LOG_NORMAL,
				"\rVerifying data: %luk/%luk (100%%)\n",
				KB (filestat.st_size),
				KB (filestat.st_size));
	DEBUG("Verified %d / %luk bytes\n",written,filestat.st_size);

	exit (EXIT_SUCCESS);
}
Ejemplo n.º 3
0
/*
 * Basically the same guts as do_scan() from above (please keep them in
 * sync) used to find the victim we're firing at.	-Thoric
 */
char_data *scan_for_vic( char_data * ch, exit_data * pexit, const string & name )
{
   char_data *victim;
   room_index *was_in_room;
   short dist, dir;
   short max_dist = 8;

   if( ch->has_aflag( AFF_BLIND ) || !pexit )
      return nullptr;

   was_in_room = ch->in_room;

   if( ch->level < 50 )
      --max_dist;
   if( ch->level < 40 )
      --max_dist;
   if( ch->level < 30 )
      --max_dist;

   for( dist = 1; dist <= max_dist; )
   {
      if( IS_EXIT_FLAG( pexit, EX_CLOSED ) )
         break;

      if( pexit->to_room->is_private(  ) && ch->level < sysdata->level_override_private )
         break;

      ch->from_room(  );
      if( !ch->to_room( pexit->to_room ) )
         log_printf( "char_to_room: %s:%s, line %d.", __FILE__, __func__, __LINE__ );

      if( ( victim = ch->get_char_room( name ) ) != nullptr )
      {
         ch->from_room(  );
         if( !ch->to_room( was_in_room ) )
            log_printf( "char_to_room: %s:%s, line %d.", __FILE__, __func__, __LINE__ );
         return victim;
      }

      switch ( ch->in_room->sector_type )
      {
         default:
            ++dist;
            break;
         case SECT_AIR:
            if( number_percent(  ) < 80 )
               ++dist;
            break;
         case SECT_INDOORS:
         case SECT_FIELD:
         case SECT_UNDERGROUND:
            ++dist;
            break;
         case SECT_FOREST:
         case SECT_CITY:
         case SECT_DESERT:
         case SECT_HILLS:
            dist += 2;
            break;
         case SECT_WATER_SWIM:
         case SECT_WATER_NOSWIM:
         case SECT_RIVER:
            dist += 3;
            break;
         case SECT_MOUNTAIN:
         case SECT_UNDERWATER:
         case SECT_OCEANFLOOR:
            dist += 4;
            break;
      }

      if( dist >= max_dist )
         break;

      dir = pexit->vdir;
      if( !( pexit = ch->in_room->get_exit( dir ) ) )
         break;
   }

   ch->from_room(  );
   if( !ch->to_room( was_in_room ) )
      log_printf( "char_to_room: %s:%s, line %d.", __FILE__, __func__, __LINE__ );

   return nullptr;
}
Ejemplo n.º 4
0
static enum e_corosync_done corosync_flock (const char *lockfile, pid_t pid)
{
	struct flock lock;
	enum e_corosync_done err;
	char pid_s[17];
	int fd_flag;
	int lf;

	err = COROSYNC_DONE_EXIT;

	lf = open (lockfile, O_WRONLY | O_CREAT, 0640);
	if (lf == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't create lock file.");
		return (COROSYNC_DONE_AQUIRE_LOCK);
	}

retry_fcntl:
	lock.l_type = F_WRLCK;
	lock.l_start = 0;
	lock.l_whence = SEEK_SET;
	lock.l_len = 0;
	if (fcntl (lf, F_SETLK, &lock) == -1) {
		switch (errno) {
		case EINTR:
			goto retry_fcntl;
			break;
		case EAGAIN:
		case EACCES:
			log_printf (LOGSYS_LEVEL_ERROR, "Another Corosync instance is already running.");
			err = COROSYNC_DONE_ALREADY_RUNNING;
			goto error_close;
			break;
		default:
			log_printf (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't aquire lock. Error was %s",
			    strerror(errno));
			err = COROSYNC_DONE_AQUIRE_LOCK;
			goto error_close;
			break;
		}
	}

	if (ftruncate (lf, 0) == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't truncate lock file. Error was %s",
		    strerror (errno));
		err = COROSYNC_DONE_AQUIRE_LOCK;
		goto error_close_unlink;
	}

	memset (pid_s, 0, sizeof (pid_s));
	snprintf (pid_s, sizeof (pid_s) - 1, "%u\n", pid);

retry_write:
	if (write (lf, pid_s, strlen (pid_s)) != strlen (pid_s)) {
		if (errno == EINTR) {
			goto retry_write;
		} else {
			log_printf (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't write pid to lock file. "
				"Error was %s", strerror (errno));
			err = COROSYNC_DONE_AQUIRE_LOCK;
			goto error_close_unlink;
		}
	}

	if ((fd_flag = fcntl (lf, F_GETFD, 0)) == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't get close-on-exec flag from lock file. "
			"Error was %s", strerror (errno));
		err = COROSYNC_DONE_AQUIRE_LOCK;
		goto error_close_unlink;
	}
	fd_flag |= FD_CLOEXEC;
	if (fcntl (lf, F_SETFD, fd_flag) == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't set close-on-exec flag to lock file. "
			"Error was %s", strerror (errno));
		err = COROSYNC_DONE_AQUIRE_LOCK;
		goto error_close_unlink;
	}

	return (err);

error_close_unlink:
	unlink (lockfile);
error_close:
	close (lf);

	return (err);
}
Ejemplo n.º 5
0
static int32_t sig_exit_handler (int num, void *data)
{
	log_printf(LOGSYS_LEVEL_NOTICE, "Node was shut down by a signal");
	corosync_service_unlink_all (api, unlink_all_completed);
	return 0;
}
Ejemplo n.º 6
0
// Parses a header line. Returns true iff progress was made.
bool frameparser_parse_header(frameparser *fp, buffer *b)
{
  log_printf(LOG_LEVEL_DEBUG, "frameparser_parse_header\n");
  // Valid input in this state is either:
  // 1. CR/LF or LF alone, denoting the end of headers
  // 2. A key name, followed by a colon, followed by a value name, terminated with CR/LF or LF

  // Try to find LF line terminator
  int lfpos = buffer_find_byte(b, '\x0A');
  if (lfpos < 0)  // No LF yet?
  {
    if (buffer_get_length(b) > LIMIT_FRAME_HEADER_LINE_LEN)
      frameparser_set_error(fp, "Line length limit exceeded waiting for header");

    return false;  // No progress
  }
  else if (lfpos == 0)  // LF alone
  {
    buffer_consume(b, 1);
    frameparser_parse_headers_complete(fp);
    return true;
  }
  else if ((lfpos == 1) && (buffer_get_byte(b, 0) == '\x0D'))  // CR/LF alone
  {
    buffer_consume(b, 2);
    frameparser_parse_headers_complete(fp);
    return true;
  }

  // Figure out number of bytes in the line
  int len = lfpos;
  if (buffer_get_byte(b, len - 1) == '\x0D')
    len--;

  // Find the colon delimiter
  int colonpos = buffer_find_byte_within(b, ':', 0, len);
  if (colonpos < 0)  // No colon?
  {
    frameparser_set_error(fp, "Expected colon delimiter on header line");
    return false;
  }
  else if (colonpos == 0)  // Starts with colon?
  {
    frameparser_set_error(fp, "Header name has zero length");
    return false;
  }

  // Extract the key
  bytestring *key = bytestring_new(colonpos);
  buffer_append_bytestring(b, key, 0, colonpos);

  // Extract the value
  bytestring *val = bytestring_new(len - colonpos - 1);
  buffer_append_bytestring(b, val, colonpos + 1, len - colonpos - 1);

  // Consume the current line
  buffer_consume(b, lfpos + 1);

  // Unescape the key and value if needed
  frame_command cmd = frame_get_command(fp->cur_frame);
  if ((cmd != CMD_CONNECT) && (cmd != CMD_CONNECTED))
  {
    key = unescape_header_bytestring(key);
    val = unescape_header_bytestring(val);
  }

  bytestring_dump(key);
  bytestring_dump(val);

  headerbundle *hb = frame_get_headerbundle(fp->cur_frame);
  headerbundle_append_header(hb, key, val);  // The bundle takes ownership of key and val

  return true;
}
Ejemplo n.º 7
0
static void *ep0_thread(void *arg)
{
	device_pthread_setaffinity();

	char buf[sizeof(struct usb_gadgetfs_event)*10]; /* store up to 10 events */
	fd_set fds;
	struct timeval tv;
	int rc;

	LOG_PRINTF("entry: self %ld\n", syscall(SYS_gettid));
	rc = 0; 	// re-use rc as a loop counter
retry:
	/* novacom_ep0 */
	ep0_fd = open("/dev/novacom_ep0", O_RDWR);
	if (ep0_fd >= 0) {
		ep1in_name = "/dev/novacom_ep_in";
		ep2out_name = "/dev/novacom_ep_out";
		goto opened;
	}

	/* try the omap3's usb port first */
	ep0_fd = open("/dev/gadget/musb_hdrc", O_RDWR);
	if (ep0_fd >= 0) {
		struct stat stbuf;
		if (stat("/dev/gadget/ep4in", &stbuf) == 0) {
			ep1in_name = "/dev/gadget/ep4in";
			ep2out_name = "/dev/gadget/ep3out";
		} else {
			ep1in_name = "/dev/gadget/ep2in";
			ep2out_name = "/dev/gadget/ep2out";
		}
		goto opened;
	}

	/* omap2 */
	ep0_fd = open("/dev/gadget/omap_udc", O_RDWR);
	if (ep0_fd >= 0) {
		ep1in_name = "/dev/gadget/ep7in-bulk";
		ep2out_name = "/dev/gadget/ep8out-bulk";
		goto opened;
	}

	/* msm */
	ep0_fd = open("/dev/gadget/msm_hsusb", O_RDWR);
	if (ep0_fd >= 0) {
		struct stat stbuf;
		if (stat("/dev/gadget/ep4in", &stbuf) == 0) {
			ep1in_name = "/dev/gadget/ep4in";
			ep2out_name = "/dev/gadget/ep3out";
		} else {
			ep1in_name = "/dev/gadget/ep2in";
			ep2out_name = "/dev/gadget/ep2out";
		}
		goto opened;
	}

	/* fail */
	rc++;
	if (rc >= GADGET_RETRY_COUNT) {
		log_printf(LOG_ERROR, "failed to open gadgetfs %d times - giving up on usb\n", rc);
		return (NULL);
	}

	log_printf(LOG_ERROR, "failed to open gadgetfs ep0 node - retry\n");
	sleep(1);
	goto retry;

opened:
	fcntl(ep0_fd, F_SETFD, FD_CLOEXEC);

	/* main loop */
	for (;;) {
		struct timeval *ptrtv = NULL;
		/* we use timeout only when required:: usb_online && gadgetfs disconnect event*/
		if( (gadgetfs_online == false) && usb_online) {
			ptrtv = &tv;
			tv.tv_sec = TRANSPORT_RECOVERY_TIMEOUT;
			tv.tv_usec = 0;
			/* about to trigger wait timer: clear event */
			platform_event_unsignal(&usb_online_event);
		}
		/* select */
		FD_ZERO(&fds);
		FD_SET(ep0_fd, &fds);
		rc = select(ep0_fd + 1, &fds, NULL, NULL, ptrtv);
		/* error */
		if(-1 == rc) {
			if((EAGAIN == errno) || (EINTR == errno)) {
				continue;
			} else {
				break;
			}
		}

		/* timeout */
		if(rc == 0) {
			/* gadgetfs reported disconnect */
			if( (gadgetfs_online == false) && usb_online) {
				LOG_PRINTF("Postponed going offline...\n");
				set_usb_online(false);
			}
			else {
				LOG_PRINTF("Timeout, usb is in online state, to continue...\n");
			}
			continue;
		}

		/*normal flow */
		if ( !(FD_ISSET(ep0_fd, &fds)) ) {
			continue;
		}
		int err = read(ep0_fd, buf, sizeof(buf));
		LOG_PRINTF("ep0 err %d\n", err);
		if (err < 0)
			break;

		struct usb_gadgetfs_event *event = (struct usb_gadgetfs_event *)buf;
		int nevents = err / sizeof(struct usb_gadgetfs_event);
		for (; nevents > 0; nevents--) {
			LOG_PRINTF("got usb event type %d: ", event->type);
			switch (event->type) {
				case GADGETFS_NOP:
					LOG_PRINTF("NOP\n");
					break;
				case GADGETFS_CONNECT:
					LOG_PRINTF("CONNECT\n");
					LOG_PRINTF("speed %d\n", event->u.speed);
					break;
				case GADGETFS_DISCONNECT:
					LOG_PRINTF("DISCONNECT\n");
					gadgetfs_online = false;
					break;
				case GADGETFS_SETUP:
					LOG_PRINTF("SETUP: requesttype 0x%x, request 0x%x, value 0x%x, index 0x%x, length 0x%x", event->u.setup.bRequestType, event->u.setup.bRequest, event->u.setup.wValue, event->u.setup.wIndex, event->u.setup.wLength);
					switch (event->u.setup.bRequest) {
						case USB_REQ_SET_INTERFACE:
							LOG_PRINTF("USB_REQ_SET_INTERFACE: %d\n", event->u.setup.wValue);

							// setting interface to 0 seems to be a disconnect
//								if (event->u.setup.wValue == 0) {
//									stop_io();
//								}
							break;
						case USB_REQ_SET_CONFIGURATION:
							LOG_PRINTF("USB_REQ_SET_CONFIGURATION: config %d\n", event->u.setup.wValue);
							if (event->u.setup.wValue > 0) {
								if(set_usb_online(true) < 0) {
									close(ep0_fd);
									goto retry;
								}
								gadgetfs_online = true;
							} else {
								gadgetfs_online = false;
							}
							break;
						default:
							LOG_PRINTF("unhandled request\n");
					}
					break;
				case GADGETFS_SUSPEND:
					LOG_PRINTF("SUSPEND\n");
					break;
				default:
					LOG_PRINTF("UNKNOWN\n");
					break;
			}

			event++;
		}
	}

	LOG_PRINTF("closing ep0\n");
	set_usb_online(false);
	close(ep0_fd);

	return NULL;
}
Ejemplo n.º 8
0
int db_Conn()
{
	char username[] = "marantz";
	char password[] = "cctv001";
	char dbname[] = "dbdoom";

	/* EXEC SQL CONNECT :username IDENTIFIED BY :password USING :dbname; */ 

{
 struct sqlexd sqlstm;
 sqlstm.sqlvsn = 12;
 sqlstm.arrsiz = 4;
 sqlstm.sqladtp = &sqladt;
 sqlstm.sqltdsp = &sqltds;
 sqlstm.iters = (unsigned int  )50;
 sqlstm.offset = (unsigned int  )5;
 sqlstm.cud = sqlcud0;
 sqlstm.sqlest = (unsigned char  *)&sqlca;
 sqlstm.sqlety = (unsigned short)256;
 sqlstm.occurs = (unsigned int  )0;
 sqlstm.sqhstv[0] = (         void  *)username;
 sqlstm.sqhstl[0] = (unsigned int  )0;
 sqlstm.sqhsts[0] = (         int  )0;
 sqlstm.sqindv[0] = (         void  *)0;
 sqlstm.sqinds[0] = (         int  )0;
 sqlstm.sqharm[0] = (unsigned int  )0;
 sqlstm.sqadto[0] = (unsigned short )0;
 sqlstm.sqtdso[0] = (unsigned short )0;
 sqlstm.sqhstv[1] = (         void  *)password;
 sqlstm.sqhstl[1] = (unsigned int  )0;
 sqlstm.sqhsts[1] = (         int  )0;
 sqlstm.sqindv[1] = (         void  *)0;
 sqlstm.sqinds[1] = (         int  )0;
 sqlstm.sqharm[1] = (unsigned int  )0;
 sqlstm.sqadto[1] = (unsigned short )0;
 sqlstm.sqtdso[1] = (unsigned short )0;
 sqlstm.sqhstv[2] = (         void  *)dbname;
 sqlstm.sqhstl[2] = (unsigned int  )0;
 sqlstm.sqhsts[2] = (         int  )0;
 sqlstm.sqindv[2] = (         void  *)0;
 sqlstm.sqinds[2] = (         int  )0;
 sqlstm.sqharm[2] = (unsigned int  )0;
 sqlstm.sqadto[2] = (unsigned short )0;
 sqlstm.sqtdso[2] = (unsigned short )0;
 sqlstm.sqphsv = sqlstm.sqhstv;
 sqlstm.sqphsl = sqlstm.sqhstl;
 sqlstm.sqphss = sqlstm.sqhsts;
 sqlstm.sqpind = sqlstm.sqindv;
 sqlstm.sqpins = sqlstm.sqinds;
 sqlstm.sqparm = sqlstm.sqharm;
 sqlstm.sqparc = sqlstm.sqharc;
 sqlstm.sqpadto = sqlstm.sqadto;
 sqlstm.sqptdso = sqlstm.sqtdso;
 sqlstm.sqlcmax = (unsigned int )100;
 sqlstm.sqlcmin = (unsigned int )2;
 sqlstm.sqlcincr = (unsigned int )1;
 sqlstm.sqlctimeout = (unsigned int )0;
 sqlstm.sqlcnowait = (unsigned int )0;
 sqlcxt((void **)0, &sqlctx, &sqlstm, &sqlfpn);
}



	if ( SQLCODE != SQLOK ) {
		log_printf(LOG_ARG,"ORACLE CONNECT FAIL!! [%s]",SQLERRM);
		return FALSE;
	} else {
		log_printf(LOG_ARG,"ORACLE CONNECT !!");
	}

	return TRUE;
}
Ejemplo n.º 9
0
static int corosync_move_to_root_cgroup(void) {
	int res = -1;
#ifdef HAVE_LIBCGROUP
	int cg_ret;
	struct cgroup *root_cgroup = NULL;
	struct cgroup_controller *root_cpu_cgroup_controller = NULL;
	char *current_cgroup_path = NULL;

	cg_ret = cgroup_init();
	if (cg_ret) {
		log_printf(LOGSYS_LEVEL_WARNING, "Unable to initialize libcgroup: %s ",
		    cgroup_strerror(cg_ret));

		goto exit_res;
	}

	cg_ret = cgroup_get_current_controller_path(getpid(), "cpu", &current_cgroup_path);
	if (cg_ret) {
		log_printf(LOGSYS_LEVEL_WARNING, "Unable to get current cpu cgroup path: %s ",
		    cgroup_strerror(cg_ret));

		goto exit_res;
	}

	if (strcmp(current_cgroup_path, "/") == 0) {
		log_printf(LOGSYS_LEVEL_DEBUG, "Corosync is already in root cgroup path");

		res = 0;
		goto exit_res;
	}

	root_cgroup = cgroup_new_cgroup("/");
	if (root_cgroup == NULL) {
		log_printf(LOGSYS_LEVEL_WARNING, "Can't create root cgroup");

		goto exit_res;
	}

	root_cpu_cgroup_controller = cgroup_add_controller(root_cgroup, "cpu");
	if (root_cpu_cgroup_controller == NULL) {
		log_printf(LOGSYS_LEVEL_WARNING, "Can't create root cgroup cpu controller");

		goto exit_res;
	}

	cg_ret = cgroup_attach_task(root_cgroup);
	if (cg_ret) {
		log_printf(LOGSYS_LEVEL_WARNING, "Can't attach task to root cgroup: %s ",
		    cgroup_strerror(cg_ret));

		goto exit_res;
	}

	cg_ret = cgroup_get_current_controller_path(getpid(), "cpu", &current_cgroup_path);
	if (cg_ret) {
		log_printf(LOGSYS_LEVEL_WARNING, "Unable to get current cpu cgroup path: %s ",
		    cgroup_strerror(cg_ret));

		goto exit_res;
	}

	if (strcmp(current_cgroup_path, "/") == 0) {
		log_printf(LOGSYS_LEVEL_NOTICE, "Corosync successfully moved to root cgroup");
		res = 0;
	} else {
		log_printf(LOGSYS_LEVEL_WARNING, "Can't move Corosync to root cgroup");
	}

exit_res:
	if (root_cgroup != NULL) {
		cgroup_free(&root_cgroup);
	}

	/*
	 * libcgroup doesn't define something like cgroup_fini so there is no way how to clean
	 * it's cache. It has to be called when libcgroup authors decide to implement it.
	 */

#endif
	 return (res);
}
Ejemplo n.º 10
0
static int
do_encode_md (gcry_md_hd_t md, int algo, int pkalgo, unsigned int nbits,
              gcry_sexp_t pkey, gcry_mpi_t *r_val)
{
  int n;
  size_t nframe;
  unsigned char *frame;

  if (pkalgo == GCRY_PK_DSA || pkalgo == GCRY_PK_ECDSA)
    {
      unsigned int qbits;

      if ( pkalgo == GCRY_PK_ECDSA )
        qbits = gcry_pk_get_nbits (pkey);
      else
        qbits = get_dsa_qbits (pkey);

      if ( (qbits%8) )
	{
	  log_error(_("DSA requires the hash length to be a"
		      " multiple of 8 bits\n"));
	  return gpg_error (GPG_ERR_INTERNAL);
	}

      /* Don't allow any Q smaller than 160 bits.  We don't want
	 someone to issue signatures from a key with a 16-bit Q or
	 something like that, which would look correct but allow
	 trivial forgeries.  Yes, I know this rules out using MD5 with
	 DSA. ;) */
      if (qbits < 160)
	{
	  log_error (_("%s key uses an unsafe (%u bit) hash\n"),
                     gcry_pk_algo_name (pkalgo), qbits);
	  return gpg_error (GPG_ERR_INTERNAL);
	}

      /* Check if we're too short.  Too long is safe as we'll
	 automatically left-truncate. */
      nframe = gcry_md_get_algo_dlen (algo);
      if (nframe < qbits/8)
        {
	  log_error (_("a %u bit hash is not valid for a %u bit %s key\n"),
                     (unsigned int)nframe*8,
                     gcry_pk_get_nbits (pkey),
                     gcry_pk_algo_name (pkalgo));
          /* FIXME: we need to check the requirements for ECDSA.  */
          if (nframe < 20 || pkalgo == GCRY_PK_DSA  )
            return gpg_error (GPG_ERR_INTERNAL);
        }

      frame = xtrymalloc (nframe);
      if (!frame)
        return out_of_core ();
      memcpy (frame, gcry_md_read (md, algo), nframe);
      n = nframe;
      /* Truncate.  */
      if (n > qbits/8)
        n = qbits/8;
    }
  else
    {
      int i;
      unsigned char asn[100];
      size_t asnlen;
      size_t len;

      nframe = (nbits+7) / 8;

      asnlen = DIM(asn);
      if (!algo || gcry_md_test_algo (algo))
        return gpg_error (GPG_ERR_DIGEST_ALGO);
      if (gcry_md_algo_info (algo, GCRYCTL_GET_ASNOID, asn, &asnlen))
        {
          log_error ("no object identifier for algo %d\n", algo);
          return gpg_error (GPG_ERR_INTERNAL);
        }

      len = gcry_md_get_algo_dlen (algo);

      if ( len + asnlen + 4  > nframe )
        {
          log_error ("can't encode a %d bit MD into a %d bits frame\n",
                     (int)(len*8), (int)nbits);
          return gpg_error (GPG_ERR_INTERNAL);
        }

      /* We encode the MD in this way:
       *
       *	   0  A PAD(n bytes)   0  ASN(asnlen bytes)  MD(len bytes)
       *
       * PAD consists of FF bytes.
       */
      frame = xtrymalloc (nframe);
      if (!frame)
        return out_of_core ();
      n = 0;
      frame[n++] = 0;
      frame[n++] = 1; /* block type */
      i = nframe - len - asnlen -3 ;
      assert ( i > 1 );
      memset ( frame+n, 0xff, i ); n += i;
      frame[n++] = 0;
      memcpy ( frame+n, asn, asnlen ); n += asnlen;
      memcpy ( frame+n, gcry_md_read(md, algo), len ); n += len;
      assert ( n == nframe );
    }
  if (DBG_CRYPTO)
    {
      int j;
      log_debug ("encoded hash:");
      for (j=0; j < nframe; j++)
        log_printf (" %02X", frame[j]);
      log_printf ("\n");
    }

  gcry_mpi_scan (r_val, GCRYMPI_FMT_USG, frame, n, &nframe);
  xfree (frame);
  return 0;
}
Ejemplo n.º 11
0
int 
connect_x509(char *hostname, u_short port_no) 
{ 
	char *rn = "connect_x509"; 
 
	struct sockaddr_in peeraddr; 
	struct hostent *phostent; 
	int	optrc; 
	int	s; 
 
	struct  linger linger  =  {1, 1};          /* Linger Option set to 1 */ 
						   /*   for 1 second         */ 
 
 
	phostent = gethostbyname (hostname);  
	if( phostent == NULL)  
	{ 
		log_printf("%s: unknown host\n", rn); 
		return 0; 
	} 
 
	log_printf("%s: Host official name: %s\n", rn, phostent->h_name); 
 
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)  
	{ 
#ifdef WIN32 
		log_printf("%s: Failed creating socket 0x%08x (%d)\n", 
		        rn, WSAGetLastError(), WSAGetLastError()); 
#else 
		log_printf("%s: Failed creating socket\n%s\n", 
		        rn, strerror(errno)); 
#endif 
		return 0; 
	} 
 
	log_printf("%s: Issuing connect to port %d\n", rn, port_no); 
	peeraddr.sin_family = AF_INET; 
	peeraddr.sin_port   = htons(port_no); 
	peeraddr.sin_addr.s_addr = ((struct in_addr *)(phostent->h_addr))->s_addr; 
	if (connect(s, (struct sockaddr *) &peeraddr, sizeof(struct sockaddr_in))  == -1)  
	{ 
#ifdef WIN32 
        log_printf("%s: Failed connecting socket 0x%08x (%d)\n", 
                rn, WSAGetLastError(), WSAGetLastError()); 
#else 
		log_printf("%s: Failed connecting socket\n%s\n", 
		        rn, strerror(errno));  
#endif 
  
		return 0; 
	} 
 
	/* 
	** set the linger option.  This gives us a "Graceful" close 
	** meaning we receive all the data before the socket closes. 
	*/ 
	optrc = setsockopt (s, SOL_SOCKET, SO_LINGER,  
		               (char *) &linger, sizeof (struct linger)); 
	if (optrc == -1) 
		log_printf("%s: Unable to set linger option on socket\n%s\n", 
		            rn, strerror(errno)); 
	return s; 
} 
Ejemplo n.º 12
0
/* Check the signature on CERT using the ISSUER-CERT.  This function
   does only test the cryptographic signature and nothing else.  It is
   assumed that the ISSUER_CERT is valid. */
int
gpgsm_check_cert_sig (ksba_cert_t issuer_cert, ksba_cert_t cert)
{
  const char *algoid;
  gcry_md_hd_t md;
  int rc, algo;
  gcry_mpi_t frame;
  ksba_sexp_t p;
  size_t n;
  gcry_sexp_t s_sig, s_hash, s_pkey;

  algo = gcry_md_map_name ( (algoid=ksba_cert_get_digest_algo (cert)));
  if (!algo)
    {
      log_error ("unknown hash algorithm '%s'\n", algoid? algoid:"?");
      if (algoid
          && (  !strcmp (algoid, "1.2.840.113549.1.1.2")
                ||!strcmp (algoid, "1.2.840.113549.2.2")))
        log_info (_("(this is the MD2 algorithm)\n"));
      return gpg_error (GPG_ERR_GENERAL);
    }
  rc = gcry_md_open (&md, algo, 0);
  if (rc)
    {
      log_error ("md_open failed: %s\n", gpg_strerror (rc));
      return rc;
    }
  if (DBG_HASHING)
    gcry_md_debug (md, "hash.cert");

  rc = ksba_cert_hash (cert, 1, HASH_FNC, md);
  if (rc)
    {
      log_error ("ksba_cert_hash failed: %s\n", gpg_strerror (rc));
      gcry_md_close (md);
      return rc;
    }
  gcry_md_final (md);

  p = ksba_cert_get_sig_val (cert);
  n = gcry_sexp_canon_len (p, 0, NULL, NULL);
  if (!n)
    {
      log_error ("libksba did not return a proper S-Exp\n");
      gcry_md_close (md);
      ksba_free (p);
      return gpg_error (GPG_ERR_BUG);
    }
  if (DBG_CRYPTO)
    {
      int j;
      log_debug ("signature value:");
      for (j=0; j < n; j++)
        log_printf (" %02X", p[j]);
      log_printf ("\n");
    }

  rc = gcry_sexp_sscan ( &s_sig, NULL, (char*)p, n);
  ksba_free (p);
  if (rc)
    {
      log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (rc));
      gcry_md_close (md);
      return rc;
    }

  p = ksba_cert_get_public_key (issuer_cert);
  n = gcry_sexp_canon_len (p, 0, NULL, NULL);
  if (!n)
    {
      log_error ("libksba did not return a proper S-Exp\n");
      gcry_md_close (md);
      ksba_free (p);
      gcry_sexp_release (s_sig);
      return gpg_error (GPG_ERR_BUG);
    }
  rc = gcry_sexp_sscan ( &s_pkey, NULL, (char*)p, n);
  ksba_free (p);
  if (rc)
    {
      log_error ("gcry_sexp_scan failed: %s\n", gpg_strerror (rc));
      gcry_md_close (md);
      gcry_sexp_release (s_sig);
      return rc;
    }

  rc = do_encode_md (md, algo, pk_algo_from_sexp (s_pkey),
                     gcry_pk_get_nbits (s_pkey), s_pkey, &frame);
  if (rc)
    {
      gcry_md_close (md);
      gcry_sexp_release (s_sig);
      gcry_sexp_release (s_pkey);
      return rc;
    }

  /* put hash into the S-Exp s_hash */
  if ( gcry_sexp_build (&s_hash, NULL, "%m", frame) )
    BUG ();
  gcry_mpi_release (frame);


  rc = gcry_pk_verify (s_sig, s_hash, s_pkey);
  if (DBG_X509)
      log_debug ("gcry_pk_verify: %s\n", gpg_strerror (rc));
  gcry_md_close (md);
  gcry_sexp_release (s_sig);
  gcry_sexp_release (s_hash);
  gcry_sexp_release (s_pkey);
  return rc;
}
Ejemplo n.º 13
0
void halide_print(void *user_context, const char *str) {
    log_printf("%s", str);
}
Ejemplo n.º 14
0
/**
 * Send connections to nuauth: between 1 and #CONN_MAX connections
 * in a big packet of format:
 *   [ nu_header + nu_authfield_ipv6 * N ]
 */
int send_user_pckt(nuauth_session_t * session, conn_t * carray[CONN_MAX])
{
	char data[PACKET_SIZE];
	char *pointer;
	unsigned int item;
	struct nu_header *header;
	struct nu_authreq *authreq;
	struct nu_authfield_ipv6 *authfield;
	struct nu_authfield_app *appfield;
	unsigned len;
	const char *appname;
	char *app_ptr;

	session->timestamp_last_sent = time(NULL);
	memset(data, 0, sizeof data);

	header = (struct nu_header *) data;
	header->proto = PROTO_VERSION;
	header->msg_type = USER_REQUEST;
	header->option = 0;
	header->length = sizeof(struct nu_header);
	pointer = (char *) (header + 1);

	for (item = 0; ((item < CONN_MAX) && carray[item] != NULL); item++) {
#if DEBUG
		printf("adding one authreq\n");
#endif
#ifdef LINUX
		/* get application name from inode */
		appname = prg_cache_get(carray[item]->inode);
#else
		appname = "UNKNOWN";
#endif
		header->length +=
		    sizeof(struct nu_authreq) +
		    sizeof(struct nu_authfield_ipv6);

		authreq = (struct nu_authreq *) pointer;
		authreq->packet_seq = session->packet_seq++;
		authreq->packet_length =
		    sizeof(struct nu_authreq) +
		    sizeof(struct nu_authfield_ipv6);

		authfield = (struct nu_authfield_ipv6 *) (authreq + 1);
		authfield->type = IPV6_FIELD;
		authfield->option = 0;
		authfield->src = carray[item]->ip_src;
		authfield->dst = carray[item]->ip_dst;
		authfield->proto = carray[item]->protocol;
		authfield->flags = 0;
		authfield->FUSE = 0;
#ifdef _I386__ENDIAN_H_
#ifdef __DARWIN_LITTLE_ENDIAN
		authfield->sport = carray[item]->port_src;
		authfield->dport = carray[item]->port_dst;
#else
		authfield->sport = htons(carray[item]->port_src);
		authfield->dport = htons(carray[item]->port_dst);
#endif				/* DARWIN LITTLE ENDIAN */
#else
		authfield->sport = htons(carray[item]->port_src);
		authfield->dport = htons(carray[item]->port_dst);
#endif				/* I386 ENDIAN */

		/* application field  */
		appfield = (struct nu_authfield_app *) (authfield + 1);
		appfield->type = APP_FIELD;
		appfield->option = APP_TYPE_NAME;
		app_ptr = (char *) (appfield + 1);
		sasl_encode64(appname, strlen(appname), app_ptr,
			      PROGNAME_BASE64_WIDTH, &len);
		appfield->length = sizeof(struct nu_authfield_app) + len;
		authreq->packet_length += appfield->length;

		/* glue piece together on data if packet is not too long */
		header->length += appfield->length;

		if (session->hash) {
			struct nu_authfield_app *sigfield;
			const char *appsig;
			appsig = prg_cache_getsig(session->hash, carray[item]->inode);
			sigfield = (struct nu_authfield_app *) ((char*)appfield + appfield->length);
			sigfield->type = HASH_FIELD;
			sigfield->option = 0;
			app_ptr = (char *) (sigfield + 1);
			memcpy(app_ptr, appsig, strlen(appsig));
			sigfield->length = sizeof(struct nu_authfield_app) + strlen(appsig);

			authreq->packet_length += sigfield->length;

			/* glue piece together on data if packet is not too long */
			header->length += sigfield->length;
			sigfield->length = htons(sigfield->length);
		}

		assert(header->length < PACKET_SIZE);

		pointer += authreq->packet_length;

		appfield->length = htons(appfield->length);

		authreq->packet_length = htons(authreq->packet_length);
		authfield->length =
		    htons(sizeof(struct nu_authfield_ipv6));
	}
	header->length = htons(header->length);
	if (session->debug_mode) {
		log_printf(DEBUG_LEVEL_INFO, "[+] Send %u new connection(s) to nuauth\n", item);
	}

	/* and send it */
#if XXX
	if (session->tls) {
		if (gnutls_record_send
		    (session->tls, data, pointer - data) <= 0) {
			log_printf(DEBUG_LEVEL_CRITICAL, "write failed\n");
			return 0;
		}
	}
#else
	if (ufwissl_write(session->ufwissl, (char*)data, pointer - data) < 0)
	{
		log_printf(DEBUG_LEVEL_CRITICAL, "write failed\n");
		return 0;
	}
#endif
	return 1;
}
Ejemplo n.º 15
0
int lookup_host(const char *name, char *byte_addr, char *ip_addr) {
  char ip_buffer[256];
//  char byte_buffer[256];
  char *s, *bstate;
  int err, i;
  DNS_entry_t *h;
  apr_sockaddr_t *sa;
  int family;

log_printf(20, "lookup_host: start time=" TT " name=%s\n", time(NULL), name);
if (_cache == NULL) log_printf(20, "lookup_host: _cache == NULL\n");

  if (name[0] == '\0') return(1);  //** Return early if name is NULL

//  ipaddr = (ip_addr == NULL) ? ip_buffer : ip_addr;
//  addr = (byte_addr == NULL) ? byte_buffer : byte_addr;
  
//log_printf(20, "lookup_host: before lock\n");
  apr_thread_mutex_lock(_cache->lock);
//log_printf(20, "lookup_host: after lock\n");
 
  if ((time(NULL) > _cache->restart_time) || (apr_hash_count(_cache->table) > _cache->size)) wipe_entries(_cache);
  
  h = (DNS_entry_t *)apr_hash_get(_cache->table, name, APR_HASH_KEY_STRING);

  if (h != NULL) {  //** Got a hit!!
     if (ip_addr != NULL) strcpy(ip_addr, h->ip_addr);
     if (byte_addr != NULL) memcpy(byte_addr, h->addr, DNS_ADDR_MAX);
     family = h->family;
     apr_thread_mutex_unlock(_cache->lock);
     return(0);
  }
  
  //** If we made it here that means we have to look it up
  err = apr_sockaddr_info_get(&sa, name, APR_INET, 80, 0, _cache->mpool);
//log_printf(20, "lookup_host: apr_sockaddr_info_get=%d\n", err);

  if (err != APR_SUCCESS) {
    apr_thread_mutex_unlock(_cache->lock);
    return(-1);
  }
  h = (DNS_entry_t *)apr_palloc(_cache->mpool, sizeof(DNS_entry_t)); //** This is created withthe pool for easy cleanup
  memset(h, 0, sizeof(DNS_entry_t));

  strncpy(h->name, name, sizeof(h->name));  h->name[sizeof(h->name)-1] = '\0';

  apr_sockaddr_ip_getbuf(ip_buffer, sizeof(ip_buffer), sa);
  strcpy(h->ip_addr, ip_buffer);
  
log_printf(20, "lookup_host: start host=%s address=%s\n", name, ip_buffer);

  h->family = DNS_IPV4;
  i = 0;
  for (s = string_token(ip_buffer, ".", &bstate, &err); err == 0; s = string_token(NULL, ".", &bstate, &err)) {
      h->addr[i] = atoi(s);
//n = h->addr[i];
//log_printf(20, "lookup_host: err=%d i=%d n=%d s=%s\n", err, i, n, s);

      i++;
  }
  if (i>4) h->family = DNS_IPV6;

  //** Add the enry to the table
  apr_hash_set(_cache->table, h->name, APR_HASH_KEY_STRING, h);

  //** Return the address
  if (ip_addr != NULL) strcpy(ip_addr, h->ip_addr);
  if (byte_addr != NULL) memcpy(byte_addr, h->addr, DNS_ADDR_MAX);
  family = h->family;

  apr_thread_mutex_unlock(_cache->lock);

  return(0);
}
Ejemplo n.º 16
0
int main (int argc, char **argv, char **envp)
{
	const char *error_string;
	struct totem_config totem_config;
	int res, ch;
	int background, sched_rr, prio, testonly, move_to_root_cgroup;
	struct stat stat_out;
	enum e_corosync_done flock_err;
	uint64_t totem_config_warnings;
	struct scheduler_pause_timeout_data scheduler_pause_timeout_data;
	long int tmpli;
	char *ep;

	/* default configuration
	 */
	background = 1;
	sched_rr = 1;
	prio = 0;
	testonly = 0;
	move_to_root_cgroup = 1;

	while ((ch = getopt (argc, argv, "fP:pRrtv")) != EOF) {

		switch (ch) {
			case 'f':
				background = 0;
				break;
			case 'p':
				sched_rr = 0;
				break;
			case 'P':
				if (strcmp(optarg, "max") == 0) {
					prio = INT_MIN;
				} else if (strcmp(optarg, "min") == 0) {
					prio = INT_MAX;
				} else {
					errno = 0;

					tmpli = strtol(optarg, &ep, 10);
					if (errno != 0 || *ep != '\0' || tmpli > INT_MAX || tmpli < INT_MIN) {
						fprintf(stderr, "Priority value %s is invalid", optarg);
						logsys_system_fini();
						return EXIT_FAILURE;
					}

					prio = tmpli;
				}
				break;
			case 'R':
				move_to_root_cgroup = 0;
				break;
			case 'r':
				sched_rr = 1;
				break;
			case 't':
				testonly = 1;
				break;
			case 'v':
				printf ("Corosync Cluster Engine, version '%s'\n", VERSION);
				printf ("Copyright (c) 2006-2009 Red Hat, Inc.\n");
				logsys_system_fini();
				return EXIT_SUCCESS;

				break;
			default:
				fprintf(stderr, \
					"usage:\n"\
					"        -f     : Start application in foreground.\n"\
					"        -p     : Do not set realtime scheduling.\n"\
					"        -r     : Set round robin realtime scheduling (default).\n"\
					"        -R     : Do not try move corosync to root cpu cgroup (valid when built with libcgroup)\n" \
					"        -P num : Set priority of process (no effect when -r is used)\n"\
					"        -t     : Test configuration and exit.\n"\
					"        -v     : Display version and SVN revision of Corosync and exit.\n");
				logsys_system_fini();
				return EXIT_FAILURE;
		}
	}


	/*
	 * Other signals are registered later via qb_loop_signal_add
	 */
	(void)signal (SIGSEGV, sigsegv_handler);
	(void)signal (SIGABRT, sigsegv_handler);
#if MSG_NOSIGNAL != 0
	(void)signal (SIGPIPE, SIG_IGN);
#endif

	if (icmap_init() != CS_OK) {
		log_printf (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't initialize configuration component.");
		corosync_exit_error (COROSYNC_DONE_ICMAP);
	}
	set_icmap_ro_keys_flag();

	/*
	 * Initialize the corosync_api_v1 definition
	 */
	api = apidef_get ();

	res = coroparse_configparse(icmap_get_global_map(), &error_string);
	if (res == -1) {
		/*
		 * Logsys can't log properly at this early stage, and we need to get this message out
		 *
		 */
		fprintf (stderr, "%s\n", error_string);
		syslog (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_MAINCONFIGREAD);
	}

	if (stats_map_init(api) != CS_OK) {
		fprintf (stderr, "Corosync Executive couldn't initialize statistics component.\n");
		syslog (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't initialize statistics component.");
		corosync_exit_error (COROSYNC_DONE_STATS);
	}

	res = corosync_log_config_read (&error_string);
	if (res == -1) {
		/*
		 * if we are here, we _must_ flush the logsys queue
		 * and try to inform that we couldn't read the config.
		 * this is a desperate attempt before certain death
		 * and there is no guarantee that we can print to stderr
		 * nor that logsys is sending the messages where we expect.
		 */
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		fprintf(stderr, "%s", error_string);
		syslog (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_LOGCONFIGREAD);
	}

	if (!testonly) {
		log_printf (LOGSYS_LEVEL_NOTICE, "Corosync Cluster Engine ('%s'): started and ready to provide service.", VERSION);
		log_printf (LOGSYS_LEVEL_INFO, "Corosync built-in features:" PACKAGE_FEATURES "");
	}

	/*
	 * Make sure required directory is present
	 */
	res = stat (get_run_dir(), &stat_out);
	if ((res == -1) || (res == 0 && !S_ISDIR(stat_out.st_mode))) {
		log_printf (LOGSYS_LEVEL_ERROR, "Required directory not present %s.  Please create it.", get_run_dir());
		corosync_exit_error (COROSYNC_DONE_DIR_NOT_PRESENT);
	}

	res = chdir(get_run_dir());
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "Cannot chdir to run directory %s.  "
		    "Please make sure it has correct context and rights.", get_run_dir());
		corosync_exit_error (COROSYNC_DONE_DIR_NOT_PRESENT);
	}

	res = totem_config_read (&totem_config, &error_string, &totem_config_warnings);
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_MAINCONFIGREAD);
	}

	if (totem_config_warnings & TOTEM_CONFIG_WARNING_MEMBERS_IGNORED) {
		log_printf (LOGSYS_LEVEL_WARNING, "member section is used together with nodelist. Members ignored.");
	}

	if (totem_config_warnings & TOTEM_CONFIG_WARNING_MEMBERS_DEPRECATED) {
		log_printf (LOGSYS_LEVEL_WARNING, "member section is deprecated.");
	}

	if (totem_config_warnings & TOTEM_CONFIG_WARNING_TOTEM_NODEID_IGNORED) {
		log_printf (LOGSYS_LEVEL_WARNING, "nodeid appears both in totem section and nodelist. Nodelist one is used.");
	}

	if (totem_config_warnings & TOTEM_CONFIG_BINDNETADDR_NODELIST_SET) {
		log_printf (LOGSYS_LEVEL_WARNING, "interface section bindnetaddr is used together with nodelist. "
		    "Nodelist one is going to be used.");
	}

	if (totem_config_warnings != 0) {
		log_printf (LOGSYS_LEVEL_WARNING, "Please migrate config file to nodelist.");
	}

	res = totem_config_keyread (&totem_config, &error_string);
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_MAINCONFIGREAD);
	}

	res = totem_config_validate (&totem_config, &error_string);
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_MAINCONFIGREAD);
	}

	if (testonly) {
		corosync_exit_error (COROSYNC_DONE_EXIT);
	}


	/*
	 * Try to move corosync into root cpu cgroup. Failure is not fatal and
	 * error is deliberately ignored.
	 */
	if (move_to_root_cgroup) {
		(void)corosync_move_to_root_cgroup();
	}

	/*
	 * Set round robin realtime scheduling with priority 99
	 */
	if (sched_rr) {
		if (corosync_set_rr_scheduler () != 0) {
			prio = INT_MIN;
		} else {
			prio = 0;
		}
	}

	if (prio != 0) {
		if (setpriority(PRIO_PGRP, 0, prio) != 0) {
			LOGSYS_PERROR(errno, LOGSYS_LEVEL_WARNING,
				"Could not set priority %d", prio);
		}
	}

	ip_version = totem_config.ip_version;

	totem_config.totem_memb_ring_id_create_or_load = corosync_ring_id_create_or_load;
	totem_config.totem_memb_ring_id_store = corosync_ring_id_store;

	totem_config.totem_logging_configuration = totem_logging_configuration;
	totem_config.totem_logging_configuration.log_subsys_id = _logsys_subsys_create("TOTEM", "totem,"
			"totemip.c,totemconfig.c,totemcrypto.c,totemsrp.c,"
			"totempg.c,totemudp.c,totemudpu.c,totemnet.c,totemknet.c");

	totem_config.totem_logging_configuration.log_level_security = LOGSYS_LEVEL_WARNING;
	totem_config.totem_logging_configuration.log_level_error = LOGSYS_LEVEL_ERROR;
	totem_config.totem_logging_configuration.log_level_warning = LOGSYS_LEVEL_WARNING;
	totem_config.totem_logging_configuration.log_level_notice = LOGSYS_LEVEL_NOTICE;
	totem_config.totem_logging_configuration.log_level_debug = LOGSYS_LEVEL_DEBUG;
	totem_config.totem_logging_configuration.log_level_trace = LOGSYS_LEVEL_TRACE;
	totem_config.totem_logging_configuration.log_printf = _logsys_log_printf;

	logsys_config_apply();

	/*
	 * Now we are fully initialized.
	 */
	if (background) {
		logsys_blackbox_prefork();

		corosync_tty_detach ();

		logsys_blackbox_postfork();

		log_printf (LOGSYS_LEVEL_DEBUG, "Corosync TTY detached");
	}

	/*
	 * Lock all memory to avoid page faults which may interrupt
	 * application healthchecking
	 */
	corosync_mlockall ();

	corosync_poll_handle = qb_loop_create ();

	memset(&scheduler_pause_timeout_data, 0, sizeof(scheduler_pause_timeout_data));
	scheduler_pause_timeout_data.totem_config = &totem_config;
	timer_function_scheduler_timeout (&scheduler_pause_timeout_data);

	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_LOW,
		SIGUSR2, NULL, sig_diag_handler, NULL);
	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_HIGH,
		SIGINT, NULL, sig_exit_handler, NULL);
	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_HIGH,
		SIGQUIT, NULL, sig_exit_handler, NULL);
	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_HIGH,
		SIGTERM, NULL, sig_exit_handler, NULL);

	if (logsys_thread_start() != 0) {
		log_printf (LOGSYS_LEVEL_ERROR, "Can't initialize log thread");
		corosync_exit_error (COROSYNC_DONE_LOGCONFIGREAD);
	}

	if ((flock_err = corosync_flock (corosync_lock_file, getpid ())) != COROSYNC_DONE_EXIT) {
		corosync_exit_error (flock_err);
	}

	/*
	 * if totempg_initialize doesn't have root priveleges, it cannot
	 * bind to a specific interface.  This only matters if
	 * there is more then one interface in a system, so
	 * in this case, only a warning is printed
	 */
	/*
	 * Join multicast group and setup delivery
	 *  and configuration change functions
	 */
	if (totempg_initialize (
		corosync_poll_handle,
		&totem_config) != 0) {

		log_printf (LOGSYS_LEVEL_ERROR, "Can't initialize TOTEM layer");
		corosync_exit_error (COROSYNC_DONE_FATAL_ERR);
	}

	totempg_service_ready_register (
		main_service_ready);

	totempg_groups_initialize (
		&corosync_group_handle,
		deliver_fn,
		confchg_fn);

	totempg_groups_join (
		corosync_group_handle,
		&corosync_group,
		1);

	/*
	 * Drop root privleges to user 'corosync'
	 * TODO: Don't really need full root capabilities;
	 *       needed capabilities are:
	 * CAP_NET_RAW (bindtodevice)
	 * CAP_SYS_NICE (setscheduler)
	 * CAP_IPC_LOCK (mlockall)
	 */
	priv_drop ();

	schedwrk_init (
		serialize_lock,
		serialize_unlock);

	/*
	 * Start main processing loop
	 */
	qb_loop_run (corosync_poll_handle);

	/*
	 * Exit was requested
	 */
	totempg_finalize ();

	/*
	 * free the loop resources
	 */
	qb_loop_destroy (corosync_poll_handle);

	/*
	 * free up the icmap 
	 */

	/*
	 * Remove pid lock file
	 */
	unlink (corosync_lock_file);

	corosync_exit_error (COROSYNC_DONE_EXIT);

	return EXIT_SUCCESS;
}
Ejemplo n.º 17
0
static bool do_test(enum Mode mode)
{
   ALLEGRO_STATE state;
   ALLEGRO_BITMAP *b1;
   ALLEGRO_BITMAP *b2;
   int REPEAT;
   double t0, t1;
   int i;

   al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP);

   b1 = al_load_bitmap("data/mysha.pcx");
   if (!b1) {
      abort_example("Error loading data/mysha.pcx\n");
      return false;
   }

   b2 = al_load_bitmap("data/allegro.pcx");
   if (!b2) {
      abort_example("Error loading data/mysha.pcx\n");
      return false;
   }

   al_set_target_bitmap(b1);
   al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_INVERSE_ALPHA);
   step(mode, b2);

   /* Display the blended bitmap to the screen so we can see something. */
   al_store_state(&state, ALLEGRO_STATE_ALL);
   al_set_target_backbuffer(display);
   al_set_blender(ALLEGRO_ADD, ALLEGRO_ONE, ALLEGRO_ZERO);
   al_draw_bitmap(b1, 0, 0, 0);
   al_flip_display();
   al_restore_state(&state);

   log_printf("Benchmark: %s\n", names[mode]);
   log_printf("Please wait...\n");

   /* Do warmup run and estimate required runs for real test. */
   t0 = current_clock();
   for (i = 0; i < WARMUP; i++) {
      step(mode, b2);
   }
   t1 = current_clock();
   REPEAT = TEST_TIME * 100 / (t1 - t0);

   /* Do the real test. */
   t0 = current_clock();
   for (i = 0; i < REPEAT; i++) {
      step(mode, b2);
   }
   t1 = current_clock();

   log_printf("Time = %g s, %d steps\n",
      t1 - t0, REPEAT);
   log_printf("%s: %g FPS\n", names[mode], REPEAT / (t1 - t0));
   log_printf("Done\n");
   
   al_destroy_bitmap(b1);
   al_destroy_bitmap(b2);
      
   return true;
}
Ejemplo n.º 18
0
static void corosync_totem_stats_updater (void *data)
{
	totempg_stats_t * stats;
	uint32_t total_mtt_rx_token;
	uint32_t total_backlog_calc;
	uint32_t total_token_holdtime;
	int t, prev;
	int32_t token_count;
	const char *cstr;

	stats = api->totem_get_stats();


	stats->srp->firewall_enabled_or_nic_failure = stats->srp->continuous_gather > MAX_NO_CONT_GATHER ? 1 : 0;

	if (stats->srp->continuous_gather > MAX_NO_CONT_GATHER ||
	    stats->srp->continuous_sendmsg_failures > MAX_NO_CONT_SENDMSG_FAILURES) {
		cstr = "";

		if (stats->srp->continuous_sendmsg_failures > MAX_NO_CONT_SENDMSG_FAILURES) {
			cstr = "number of multicast sendmsg failures is above threshold";
		}

		if (stats->srp->continuous_gather > MAX_NO_CONT_GATHER) {
			cstr = "totem is continuously in gather state";
		}

		log_printf (LOGSYS_LEVEL_WARNING,
			"Totem is unable to form a cluster because of an "
			"operating system or network fault (reason: %s). The most common "
			"cause of this message is that the local firewall is "
			"configured improperly.", cstr);
		stats->srp->firewall_enabled_or_nic_failure = 1;
	} else {
		stats->srp->firewall_enabled_or_nic_failure = 0;
	}

	total_mtt_rx_token = 0;
	total_token_holdtime = 0;
	total_backlog_calc = 0;
	token_count = 0;
	t = stats->srp->latest_token;
	while (1) {
		if (t == 0)
			prev = TOTEM_TOKEN_STATS_MAX - 1;
		else
			prev = t - 1;
		if (prev == stats->srp->earliest_token)
			break;
		/* if tx == 0, then dropped token (not ours) */
		if (stats->srp->token[t].tx != 0 ||
			(stats->srp->token[t].rx - stats->srp->token[prev].rx) > 0 ) {
			total_mtt_rx_token += (stats->srp->token[t].rx - stats->srp->token[prev].rx);
			total_token_holdtime += (stats->srp->token[t].tx - stats->srp->token[t].rx);
			total_backlog_calc += stats->srp->token[t].backlog_calc;
			token_count++;
		}
		t = prev;
	}
	if (token_count) {
		stats->srp->mtt_rx_token = (total_mtt_rx_token / token_count);
		stats->srp->avg_token_workload = (total_token_holdtime / token_count);
		stats->srp->avg_backlog_calc = (total_backlog_calc / token_count);
	}

	stats_trigger_trackers();

	api->timer_add_duration (1500 * MILLI_2_NANO_SECONDS, NULL,
		corosync_totem_stats_updater,
		&corosync_stats_timer_handle);
}
Ejemplo n.º 19
0
static int set_usb_online(bool on)
{ 
	if (on) {
		if (!usb_online) {

			/*init */
			auth_init();

			/* sleep for a second to let things settle down */
			sleep(1);

			platform_event_unsignal(&tx_shutdown_event);
			platform_event_unsignal(&rx_shutdown_event);

			usbll_handle = novacom_usbll_create("host", MAX_MTU, 0, 0);

			ep1in_fd = open(ep1in_name, O_RDWR);
			LOG_PRINTF("ep1 %d\n", ep1in_fd);
			if (ep1in_fd < 0) {
				log_printf(LOG_ERROR, "error opening endpoint 1\n");
				return -1;
			}
			fcntl(ep1in_fd, F_SETFD, FD_CLOEXEC);

			ep2out_fd = open(ep2out_name, O_RDWR);
			LOG_PRINTF("ep2 %d\n", ep2out_fd);
			if (ep2out_fd < 0) {
				log_printf(LOG_ERROR, "error opening endpoint 2\n");
				close(ep1in_fd);
				return -1;
			}
			fcntl(ep2out_fd, F_SETFD, FD_CLOEXEC);
 
			usb_online = true;
			platform_event_signal(&usb_online_event);	

			/* create the worker threads */
			LOG_PRINTF("starting worker threads\n");

			platform_create_thread(NULL, &tx_thread_entry, NULL);
			platform_create_thread(NULL, &rx_thread_entry, NULL);
		} else if(false == gadgetfs_online) {
			/* postponed_offline->online */
			platform_event_signal(&usb_online_event);
		}
	} else {
		if (usb_online) {
			//change state before sending out signal!
			usb_online = false;
			platform_event_signal(&usb_online_event);

			/* wait for the existing worker threads to go away */
			LOG_PRINTF("waiting for worker threads to go away\n");
			platform_event_wait(&tx_shutdown_event);
			close(ep1in_fd);
			LOG_PRINTF("closed tx_thread\n");

			platform_event_wait(&rx_shutdown_event);
			close(ep2out_fd);
			LOG_PRINTF("closed rx_thread\n");
			novacom_usbll_destroy(usbll_handle);
			LOG_PRINTF("destroyed novacom usbll_handle\n");

			/* clear auth */
			auth_reset();
		}
	}
	return 0;
}
Ejemplo n.º 20
0
int main(int argc, const char **argv) {

	Options options(argc, argv);
	Timer timer;

	log_setlevel(options.getVerbosity());

	/* Get the number of neutrons, bins and batches */
	int num_neutrons = options.getNumNeutrons();
	int num_bins = options.getNumBins();
	int num_batches = options.getNumBatches();
    int num_threads = options.getNumThreads();
	int num_gen;
	int num_alive;

	log_printf(NORMAL, "Beginning two region problem with %d neutrons, "
			"%d bins, %d batches, %d threads...", num_neutrons, num_bins,
			num_batches, num_threads);

	/* Create a handle for plotting with gnuplot */
	gnuplot_ctrl* handle;


	/* Create a set of plotting flux bins for each batch */
	BatchBinSet* total_flux = new BatchBinSet();
	BatchBinSet* fuel_flux = new BatchBinSet();
	BatchBinSet* moderator_flux = new BatchBinSet();

	total_flux->createBinners(1E-6, 1E7, num_bins, num_batches,
							LOGARITHMIC, FLUX_ENERGY, (char*)"all");
	fuel_flux->createBinners(1E-6, 1E7, num_bins, num_batches,
							LOGARITHMIC, FLUX_ENERGY, (char*)"all");
	moderator_flux->createBinners(1E-6, 1E7, num_bins, num_batches,
							LOGARITHMIC, FLUX_ENERGY, (char*)"all");


	/* Create bins to compute total fission and absorption rates */
	BatchBinSet* tot_fiss_rate = new BatchBinSet();
	BatchBinSet* tot_abs_rate = new BatchBinSet();

	tot_fiss_rate->createBinners(1E-7, 1E7, 1, num_batches, EQUAL,
									FISSION_RATE_ENERGY, (char*)"all");
	tot_abs_rate->createBinners(1E-7, 1E7, 1, num_batches, EQUAL,
									ABSORPTION_RATE_ENERGY, (char*)"all");
	float nu_bar = 2.455;	/* CASMO edit for average # neutrons per fission */

	/* Create bins to compute two group cell-averaged cross-sections */
	BatchBinSet* capture_2G = new BatchBinSet();
	BatchBinSet* absorb_2G = new BatchBinSet();
	BatchBinSet* fission_2G = new BatchBinSet();
	BatchBinSet* elastic_2G = new BatchBinSet();
	BatchBinSet* total_2G = new BatchBinSet();
	BatchBinSet* two_group_flux = new BatchBinSet();

	float two_group_E_ranges[3] = {0.0, 0.625, 1E7};

	capture_2G->createBinners(two_group_E_ranges, 2, num_batches,
							CAPTURE_RATE_ENERGY, (char*)"all");
	absorb_2G->createBinners(two_group_E_ranges, 2, num_batches,
							ABSORPTION_RATE_ENERGY, (char*)"all");
	fission_2G->createBinners(two_group_E_ranges, 2, num_batches,
							FISSION_RATE_ENERGY, (char*)"all");
	elastic_2G->createBinners(two_group_E_ranges, 2, num_batches,
							ELASTIC_RATE_ENERGY, (char*)"all");
	total_2G->createBinners(two_group_E_ranges, 2, num_batches,
							COLLISION_RATE_ENERGY, (char*)"all");
	two_group_flux->createBinners(two_group_E_ranges, 2, num_batches,
									FLUX_ENERGY, (char*)"all");


	/* Create bins to compute two group isotopic cross-sections */
	BatchBinSet* H1_capture_rate_2G = new BatchBinSet();
	BatchBinSet* H1_elastic_rate_2G = new BatchBinSet();
	BatchBinSet* O16_elastic_rate_2G = new BatchBinSet();
	BatchBinSet* ZR90_elastic_rate_2G = new BatchBinSet();

	BatchBinSet* U235_capture_rate_2G = new BatchBinSet();
	BatchBinSet* U235_elastic_rate_2G = new BatchBinSet();
	BatchBinSet* U235_fission_rate_2G = new BatchBinSet();
	BatchBinSet* U238_capture_rate_2G = new BatchBinSet();
	BatchBinSet* U238_elastic_rate_2G = new BatchBinSet();
	BatchBinSet* U238_fission_rate_2G = new BatchBinSet();

	H1_capture_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										CAPTURE_RATE_ENERGY, (char*)"H1");
	H1_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"H1");
	O16_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"O16");
	ZR90_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"ZR90");

	U235_capture_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										CAPTURE_RATE_ENERGY, (char*)"U235");
	U235_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"U235");
	U235_fission_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										FISSION_RATE_ENERGY, (char*)"U235");
	U238_capture_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										CAPTURE_RATE_ENERGY, (char*)"U238");
	U238_elastic_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										ELASTIC_RATE_ENERGY, (char*)"U238");
	U238_fission_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
										FISSION_RATE_ENERGY, (char*)"U238");


	/* Create bins to compute moderator to fuel flux ratios */
	int num_ratios = 13;
	BatchBinSet* fuel_flux_ratio = new BatchBinSet();
	BatchBinSet* moderator_flux_ratio = new BatchBinSet();

	float flux_ratio_E_ranges[14] = {0.0, 0.1, 0.5, 1.0, 6.0, 10.0, 25.0,
									50.0, 100.0, 1000.0, 10000.0, 100000.0,
									500000.0, 10000000.0};

	fuel_flux_ratio->createBinners(flux_ratio_E_ranges, num_ratios,
							num_batches, FLUX_ENERGY, (char*)"all");

	moderator_flux_ratio->createBinners(flux_ratio_E_ranges, num_ratios,
							num_batches, FLUX_ENERGY, (char*)"all");


	/* Create bins to compute the diffusion coefficient for three methods */
	BatchBinSet* coll_rate_2G = new BatchBinSet();
	BatchBinSet* transport_rate_2G = new BatchBinSet();
	BatchBinSet* diffusion_rate_2G = new BatchBinSet();

	coll_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
								COLLISION_RATE_ENERGY, (char*)"all");
	transport_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
								TRANSPORT_RATE_ENERGY, (char*)"all");
	diffusion_rate_2G->createBinners(two_group_E_ranges, 2, num_batches,
								DIFFUSION_RATE_ENERGY, (char*)"all");


	/* 2-region pin cell geometric parameters (units in cm) */
	float r_fuel = 0.4096;
	float r_gap = 0.4178;
	float r_cladding = 0.4750;
	float pitch = 1.26;
	float p2 = pitch * pitch;

	/* 2-region homogenized densities (g/cm^3) and enrichment */
	float rho_fuel = 10.2;
	float rho_cladding = 6.549;
	float rho_coolant = 0.9966;
	float enrichment = 0.03035;

	/* Isotope number densities */
	float N_A = 6.023E23;	/* Avogadro's number (at / mol) */
	float N_U238 = rho_fuel*N_A*(1.0 - enrichment) / ((238.0 *
					(1.0 - enrichment)) + (235.0*enrichment) + (16.0*2.0));
	float N_U235 = rho_fuel*N_A*enrichment / ((238.0 *
					(1.0 - enrichment)) + (235.0*enrichment) + (16.0*2.0));
	float N_O16 = rho_fuel*N_A*2.0 / ((238.0 *
					(1.0 - enrichment)) + (235.0*enrichment) + (16.0*2.0));
	float N_ZR90 = rho_cladding*N_A / 90.0;
	float N_H2O = rho_coolant*N_A / 18.0;
	float N_H1 = rho_coolant*N_A*2.0 / 18.0;

	/* 2-region pin cell volumes (cm^3) */
	float v_fuel = M_PI*r_fuel*r_fuel;
	float v_gap = M_PI*(r_gap*r_gap - r_fuel*r_fuel);
	float v_cladding = M_PI*(r_cladding*r_cladding - r_gap*r_gap);
	float v_coolant = p2 - M_PI*r_cladding*r_cladding;
	float v_moderator = v_gap + v_cladding + v_coolant;
	float v_total = v_fuel + v_moderator;

	/* Compute homogenized moderator number densities using volume weighting */
	N_H2O *= (v_coolant / v_moderator);
	N_H1 *= (v_coolant / v_moderator);
	N_ZR90 *= (v_cladding / v_moderator);

	/* Dancoff factor from CASMO-5 */
	float dancoff = 0.277;

	/* Escape cross-section */
	float sigma_e = 1.0 / (2.0*r_fuel);

	/* Carlvik's two-term rational model */
	float A = (1.0 - dancoff) / dancoff;
	float alpha1 = ((5.0*A + 6.0) - sqrt(A*A + 36.0*A + 36.0)) /
														(2.0*(A+1.0));
	float alpha2 = ((5.0*A + 6.0) + sqrt(A*A + 36.0*A + 36.0)) /
														(2.0*(A+1.0));
	float beta = (((4.0*A + 6.0) / (A + 1.0)) - alpha1) / (alpha2 - alpha1);

	/* Print out the geometry parameters */
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "\t\t\t\tGeometry Parameters (cm)");
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");
	log_printf(NORMAL, "r_fuel = %f", r_fuel);
	log_printf(NORMAL, "r_gap  = %f", r_gap);
	log_printf(NORMAL, "r_cladding = %f", r_cladding);
	log_printf(NORMAL, "pitch = %f", pitch);
	log_printf(NORMAL, "total cell area = %f", p2);
	log_printf(NORMAL, "v_fuel = %f", v_fuel);
	log_printf(NORMAL, "v_gap = %f", v_gap);
	log_printf(NORMAL, "v_cladding = %f", v_cladding);
	log_printf(NORMAL, "v_coolant = %f", v_coolant);
	log_printf(NORMAL, "v_moderator = %f", v_moderator);
	log_printf(NORMAL, "v_total = %f", v_total);
	log_printf(NORMAL, "");

	/* Print to the console the number densities */
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "\t\t\t\tNumber Densities (at/cm^3)");
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");
	log_printf(NORMAL, "H1:\t%1.5e", N_H1);
	log_printf(NORMAL, "H2O:\t%1.5e", N_H2O);
	log_printf(NORMAL, "ZR90:\t%1.5e", N_ZR90);
	log_printf(NORMAL, "U235:\t%1.5e", N_U235);
	log_printf(NORMAL, "U238:\t%1.5e", N_U238);
	log_printf(NORMAL, "O16:\t%1.5e", N_O16);
	log_printf(NORMAL, "");

	/* Print to the console the collision probability parameters */
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "\t\t\tTwo Region Collision Probability Parameters");
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");
	log_printf(NORMAL, "dancoff = %f", dancoff);
	log_printf(NORMAL, "sigma_e = %f", sigma_e);
	log_printf(NORMAL, "A = %f", A);
	log_printf(NORMAL, "alpha1 = %f", alpha1);
	log_printf(NORMAL, "alpha2 = %f", alpha2);
	log_printf(NORMAL, "beta = %f", beta);
	log_printf(NORMAL, "");


	/* Create isotopes*/
	char* delim = (char*)"\t";

	Isotope* H1 = new Isotope();
	H1->setA(1);
	H1->setIsotopeType((char*)"H1");
	H1->loadXS((char*)"pendf/h-1_capture.txt", CAPTURE, delim);
	H1->loadXS((char*)"pendf/h-1_elastic.txt", ELASTIC, delim);
	H1->setElasticAngleType(ISOTROPIC_LAB);
	H1->initializeThermalScattering(1E-6, 15, 1000, 15);

	Isotope* O16 = new Isotope();
	O16->setA(16);
	O16->setIsotopeType((char*)"O16");
	O16->loadXS((char*)"pendf/o-16_elastic.txt", ELASTIC, delim);
	O16->setElasticAngleType(ISOTROPIC_LAB);

	Isotope* ZR90 = new Isotope();
	ZR90->setA(90);
	ZR90->setIsotopeType((char*)"ZR90");
	ZR90->loadXS((char*)"pendf/zr-90_elastic.txt", ELASTIC, delim);
	ZR90->setElasticAngleType(ISOTROPIC_LAB);

	Isotope* U235 = new Isotope();
	U235->setA(235);
	U235->setIsotopeType((char*)"U235");
	U235->loadXS((char*)"pendf/u-235_capture.txt", CAPTURE, delim);
	U235->setOneGroupElasticXS(11.4, ISOTROPIC_LAB);
	U235->loadXS((char*)"pendf/u-235_fission.txt", FISSION, delim);

	Isotope* U238 = new Isotope();
	U238->setA(238);
	U238->setIsotopeType((char*)"U238");
	U238->loadXS((char*)"pendf/u-238_capture.txt", CAPTURE, delim);
	U238->setOneGroupElasticXS(11.3, ISOTROPIC_LAB);
	U238->loadXS((char*)"pendf/u-238_fission.txt", FISSION, delim);


	/* Create Materials */
	Material* moderator = new Material[num_threads];
	Material* fuel = new Material[num_threads];


	/* Create Regions for each thread */
	Region1D* pellet = new Region1D[num_threads];
	Region1D* coolant = new Region1D[num_threads];

	/* Create Fissioners for each thread */
	Fissioner* fissioners = new Fissioner[num_threads];

	/* Create Region class objects for each thread */
	for (int i=0; i < num_threads; i++) {

		/* Initialize Materials for each thread with isotope clones */
		moderator[i].setMaterialName((char*)"moderator");
		fuel[i].setMaterialName((char*)"fuel");

		moderator[i].addIsotope(ZR90->clone(), N_ZR90);
		moderator[i].addIsotope(H1->clone(), N_H1);
		moderator[i].addIsotope(O16->clone(), N_H2O);
		moderator[i].rescaleCrossSections(1E-7, 1E7, 50000, LOGARITHMIC);

		fuel[i].addIsotope(U235->clone(), N_U235);
		fuel[i].addIsotope(U238->clone(), N_U238);
		fuel[i].addIsotope(O16->clone(), N_O16);
		fuel[i].rescaleCrossSections(1E-7, 1E7, 50000, LOGARITHMIC);

		/* Set the two region collision probability parameters */
		pellet[i].setRegionName((char*)"pellet");
		pellet[i].setMaterial(&fuel[i]);
		pellet[i].setAsFuel();
		pellet[i].setOtherPinCellRegion(&coolant[i]);
		pellet[i].setVolume(v_fuel);
		pellet[i].setTwoRegionPinCellParams(sigma_e, beta, alpha1, alpha2);

		coolant[i].setRegionName((char*)"coolant");
		coolant[i].setMaterial(&moderator[i]);
		coolant[i].setAsModerator();
		coolant[i].setOtherPinCellRegion(&pellet[i]);
		coolant[i].setVolume(v_moderator);
		coolant[i].setTwoRegionPinCellParams(sigma_e, beta, alpha1, alpha2);

		/* Set the fissioner class for this thread to have 10MeV maximum and
		 * 5000 sample bins */
		fissioners[i].setEMax(10.0);
		fissioners[i].setNumBins(200);
		fissioners[i].buildCDF();
	}


	/* Run the simulation */
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "\t\t\t\tBeginning Simulation...");
	log_printf(NORMAL, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");

	timer.start();

	omp_set_num_threads(num_threads);
	#pragma omp parallel shared(total_flux, fuel_flux, moderator_flux,\
							fuel_flux_ratio, moderator_flux_ratio,\
							tot_fiss_rate, tot_abs_rate, U235_capture_rate_2G,\
							U235_elastic_rate_2G, U235_fission_rate_2G,\
							U238_capture_rate_2G, U238_elastic_rate_2G,\
							U238_fission_rate_2G, H1_capture_rate_2G,\
							H1_elastic_rate_2G, O16_elastic_rate_2G,\
							ZR90_elastic_rate_2G, fuel, moderator, \
							pellet, coolant, fissioners)
	{
		/* Loop over batches */
		#pragma omp for private(num_gen, num_alive)
		for (int b=0; b < num_batches; b++) {

			int thread_num = omp_get_thread_num();
			log_printf(NORMAL, "Batch: %d\tThread: %d", b, thread_num);

			/* Set the binns for this batch */
			pellet[thread_num].clearBinners();
			pellet[thread_num].addBinner(total_flux->getBinner(b));
			pellet[thread_num].addBinner(fuel_flux->getBinner(b));
			pellet[thread_num].addBinner(fuel_flux_ratio->getBinner(b));
			pellet[thread_num].addBinner(tot_fiss_rate->getBinner(b));
			pellet[thread_num].addBinner(tot_abs_rate->getBinner(b));
			pellet[thread_num].addBinner(U235_capture_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U235_elastic_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U235_fission_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U238_capture_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U238_elastic_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(U238_fission_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(O16_elastic_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(two_group_flux->getBinner(b));
			pellet[thread_num].addBinner(coll_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(transport_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(diffusion_rate_2G->getBinner(b));
			pellet[thread_num].addBinner(capture_2G->getBinner(b));
			pellet[thread_num].addBinner(fission_2G->getBinner(b));
			pellet[thread_num].addBinner(absorb_2G->getBinner(b));
			pellet[thread_num].addBinner(elastic_2G->getBinner(b));
			pellet[thread_num].addBinner(total_2G->getBinner(b));

			coolant[thread_num].clearBinners();
			coolant[thread_num].addBinner(total_flux->getBinner(b));
			coolant[thread_num].addBinner(moderator_flux->getBinner(b));
			coolant[thread_num].addBinner(moderator_flux_ratio->getBinner(b));
			coolant[thread_num].addBinner(tot_fiss_rate->getBinner(b));
			coolant[thread_num].addBinner(tot_abs_rate->getBinner(b));
			coolant[thread_num].addBinner(H1_capture_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(H1_elastic_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(O16_elastic_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(ZR90_elastic_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(two_group_flux->getBinner(b));
			coolant[thread_num].addBinner(coll_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(transport_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(diffusion_rate_2G->getBinner(b));
			coolant[thread_num].addBinner(capture_2G->getBinner(b));
			coolant[thread_num].addBinner(fission_2G->getBinner(b));
			coolant[thread_num].addBinner(absorb_2G->getBinner(b));
			coolant[thread_num].addBinner(elastic_2G->getBinner(b));
			coolant[thread_num].addBinner(total_2G->getBinner(b));

			/* Initialize all neutrons for this batch and add them to slab 1 */
			for (int n=0; n < num_neutrons; n++) {
				neutron* new_neutron = initializeNewNeutron();
				new_neutron->_x = 0.0;
				new_neutron->_mu = (float(rand()) / RAND_MAX) * 2.0 - 1.0;
				new_neutron->_energy = fissioners[thread_num].emitNeutroneV();
				pellet[thread_num].addNeutron(new_neutron);
			}

			/* Loop over all neutrons until they are all dead */
			num_gen = 1;
			num_alive = num_neutrons;

			while (num_alive > 0) {

				log_printf(DEBUG, "batch = %d, thread = %d, gen = %d, "
						"num_alive = %d", b, thread_num, num_gen, num_alive);

				num_gen++;
				num_alive = 0;

				/* Transfer neutrons between regions based on
				 * two region collision probabilities */
				pellet[thread_num].twoRegionNeutronTransferral();
				coolant[thread_num].twoRegionNeutronTransferral();

				/* Update each region's vector of neutrons with those
				 * neutrons which were just transferred */
				pellet[thread_num].initializeTransferredNeutrons();
				coolant[thread_num].initializeTransferredNeutrons();

				/* Move neutrons within each region */
				pellet[thread_num].moveNeutrons();
				coolant[thread_num].moveNeutrons();

				num_alive = pellet[thread_num].getNumNeutrons() +
							coolant[thread_num].getNumNeutrons();
			}
		}
	}

	log_printf(NORMAL, "");

	/* Stop the timer record the timing split for this simulation */
	timer.stop();
	timer.recordSplit("Pset 4 time (sec)");

	/* Compute batch statistics for total flux and flux in fuel, moderator */
	total_flux->computeScaledBatchStatistics(num_neutrons*v_total);
	fuel_flux->computeScaledBatchStatistics(num_neutrons*v_fuel);
	moderator_flux->computeScaledBatchStatistics(num_neutrons*v_moderator);

	/* Compute batch statistics for total fission and absorption rates */
	tot_fiss_rate->computeScaledBatchStatistics(num_neutrons*v_total);
	tot_abs_rate->computeScaledBatchStatistics(num_neutrons*v_total);

	/* Compute batch statistics for cell-averaged macro cross-sections */
	capture_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	fission_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	absorb_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	elastic_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	total_2G->computeScaledBatchStatistics(num_neutrons*v_total);

	/* Compute batch statistics for one group cross-sections */
	H1_capture_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	H1_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	O16_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	ZR90_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U235_capture_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U235_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U235_fission_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U238_capture_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U238_elastic_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	U238_fission_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	two_group_flux->computeScaledBatchStatistics(num_neutrons*v_total);
	coll_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	transport_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);
	diffusion_rate_2G->computeScaledBatchStatistics(num_neutrons*v_total);

	/* Compute k-infinity */
	float fiss_rate_mu = tot_fiss_rate->getBatchMu()[0];
	float fiss_rate_var = tot_fiss_rate->getBatchVariance()[0];
	float abs_rate_mu = tot_abs_rate->getBatchMu()[0];
	float abs_rate_var = tot_abs_rate->getBatchVariance()[0];

	float k_inf = fiss_rate_mu * nu_bar / abs_rate_mu;

	float k_inf_var = (fiss_rate_mu*fiss_rate_mu)*abs_rate_var +
						(abs_rate_mu*abs_rate_mu)*fiss_rate_var +
									fiss_rate_var*abs_rate_var;

	float k_inf_std_dev = sqrt(k_inf_var);

	/* Compute moderator to fuel flux ratios */
	fuel_flux_ratio->computeScaledBatchStatistics(num_neutrons*v_fuel);
	moderator_flux_ratio->computeScaledBatchStatistics(num_neutrons*v_moderator);
	fuel_flux_ratio->computeScaledBatchStatistics(num_neutrons*v_fuel);
	moderator_flux_ratio->computeScaledBatchStatistics(num_neutrons*v_moderator);

	/* Print to the console the total fission rate */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\t\tTotal Fission Rate (Batch Statistics)");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(NORMAL, "");
	log_printf(RESULT, "Tot fission rate = %1.8f\t\tVariance = %1.8f",
									tot_fiss_rate->getBatchMu()[0],
									tot_fiss_rate->getBatchVariance()[0]);
	log_printf(RESULT, "Tot absorption rate = %f\t\tVariance = %f",
									tot_abs_rate->getBatchMu()[0],
									tot_abs_rate->getBatchVariance()[0]);
	log_printf(RESULT, "k_inf = %f\t\tvariance = %1.8f \t\t 2 sigma = %1.8f", k_inf,
													k_inf_var, k_inf_std_dev);
	log_printf(RESULT, "");

	/* Print to the console the moderator/fuel flux ratios */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\t\t\tModerator/Fuel Flux Ratios");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "");

	float ratio;
	for (int i=1; i < num_ratios+1; i++) {

		ratio = moderator_flux_ratio->getBatchMu()[i-1] /
						fuel_flux_ratio->getBatchMu()[i-1];

		log_printf(RESULT, "[%2.e eV - %2.e eV]:\t%f",
				flux_ratio_E_ranges[i-1], flux_ratio_E_ranges[i], ratio);
	}

	log_printf(RESULT, "");


	/* Print to the console the cell-averaged fast to thermal flux ratio */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\t\tCell-Averaged Fast-to-Thermal Flux Ratio");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "");
	double* two_group_flux_mu = two_group_flux->getBatchMu();
	double flux1 = two_group_flux_mu[0];
	double flux2 = two_group_flux_mu[1];
	log_printf(RESULT, "Ratio = %f", flux2 / flux1);
	log_printf(RESULT, "");


	/* Print to the console the two group macroscopic cross-sections */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\tTwo Group Macroscopic Cross-Sections (cm^-1)");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "");

	float xs1, xs2;

	log_printf(RESULT, "\t\t\t[%1.1f eV - %1.3f eV]\t[%1.3f eV - %1.1e eV]",
						two_group_flux->getBinner(0)->getBinEdges()[0],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[2]);

	/* H1 capture */
	xs1 = H1_capture_rate_2G->getBatchMu()[0] / flux1;
	xs2 = H1_capture_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "H1 Capture: \t\t%f\t\t%f", xs1, xs2);

	/* H1 elastic */
	xs1 = H1_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = H1_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "H1 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* O16 elastic */
	xs1 = O16_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = O16_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "O16 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* ZR90 elastic */
	xs1 = ZR90_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = ZR90_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "ZR90 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* U235 capture */
	xs1 = U235_capture_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U235_capture_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U235 Capture: \t\t%f\t\t%f", xs1, xs2);

	/* U235 elastic */
	xs1 = U235_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U235_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U235 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* U235 fission */
	xs1 = U235_fission_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U235_fission_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U235 Fission: \t\t%f\t\t%f", xs1, xs2);

	/* U238 capture */
	xs1 = U238_capture_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U238_capture_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U238 Capture: \t\t%f\t\t%f", xs1, xs2);

	/* U238 elastic */
	xs1 = U238_elastic_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U238_elastic_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U238 Elastic: \t\t%f\t\t%f", xs1, xs2);

	/* U238 fission */
	xs1 = U238_fission_rate_2G->getBatchMu()[0] / flux1;
	xs2 = U238_fission_rate_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "U238 Fission: \t\t%f\t\t%f", xs1, xs2);

	log_printf(RESULT, "");


	/* Print to the console the two group macroscopic cross-sections */
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\tTwo Group Cell-Averaged Macroscopic "
			"Cross-Sections (cm^-1)");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "");

	log_printf(RESULT, "\t\t\t[%1.1f eV - %1.3f eV]\t[%1.3f eV - %1.1e eV]",
						two_group_flux->getBinner(0)->getBinEdges()[0],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[2]);

	/* Flux */
	log_printf(RESULT, "Flux: \t\t\t%f\t\t%f", flux1, flux2);

	/* Capture */
	xs1 = capture_2G->getBatchMu()[0] / flux1;
	xs2 = capture_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Capture: \t\t\t%f\t\t%f", xs1, xs2);

	/* Fission */
	xs1 = fission_2G->getBatchMu()[0] / flux1;
	xs2 = fission_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Fission: \t\t\t%f\t\t%f", xs1, xs2);

	/* Absorption */
	xs1 = absorb_2G->getBatchMu()[0] / flux1;
	xs2 = absorb_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Absorb: \t\t\t%f\t\t%f", xs1, xs2);

	/* Elastic */
	xs1 = elastic_2G->getBatchMu()[0] / flux1;
	xs2 = elastic_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Elastic: \t\t\t%f\t\t%f", xs1, xs2);

	/* Total */
	xs1 = total_2G->getBatchMu()[0] / flux1;
	xs2 = total_2G->getBatchMu()[1] / flux2;
	log_printf(RESULT, "Total: \t\t\t%f\t\t%f", xs1, xs2);
	log_printf(RESULT, "");


	/* Print to the console the two group macroscopic cross-sections */
	log_printf(RESULT, "*******************************************************"
												"*************************");
	log_printf(RESULT, "\t\t\tTwo Group Diffusion Coefficients");
	log_printf(RESULT, "*******************************************************"
												"*************************");
	log_printf(RESULT, "");
	log_printf(RESULT, "\t\t\t[%1.1f eV - %1.3f eV]\t[%1.3f eV - %1.1e eV]",
						two_group_flux->getBinner(0)->getBinEdges()[0],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[1],
						two_group_flux->getBinner(0)->getBinEdges()[2]);

	float sigma_t1, sigma_t2;
	float sigma_tr1, sigma_tr2;
	float D1, D2;

	sigma_t1 = coll_rate_2G->getBatchMu()[0] / flux1;
	sigma_t2 = coll_rate_2G->getBatchMu()[1] / flux2;
	D1 = 1.0 / (3.0 * sigma_t1);
	D2 = 1.0 / (3.0 * sigma_t2);

	log_printf(RESULT, "1/(3*sigma_t):\t\t%f\t\t%f", D1, D2);

	sigma_tr1 = transport_rate_2G->getBatchMu()[0] / flux1;
	sigma_tr2  = transport_rate_2G->getBatchMu()[1] / flux2;
	D1 = 1.0 / (3.0 * sigma_tr1);
	D2 = 1.0 / (3.0 * sigma_tr2);

	log_printf(RESULT, "1/(3*sigma_tr):\t\t%f\t\t%f", D1, D2);

	D1 = diffusion_rate_2G->getBatchMu()[0] / flux1;
	D2 = diffusion_rate_2G->getBatchMu()[1] / flux2;

	log_printf(RESULT, "Diff coeff:\t\t%f\t\t%f", D1, D2);

	log_printf(RESULT, "");


	/* Plot the total neutron flux */
	handle = gnuplot_init();
	gnuplot_set_xlabel(handle, (char*)"Energy (eV)");
	gnuplot_set_ylabel(handle, (char*)"flux");
	gnuplot_set_xrange(handle, 0.005, 1E7);
	gnuplot_cmd(handle, (char*)"set logscale xy");
	gnuplot_cmd(handle, (char*)"set title \"Normalized Flux\"");
	gnuplot_setstyle(handle, (char*)"lines");
	gnuplot_plot_xy(handle, total_flux->getBinner(0)->getBinCenters(),
			total_flux->getBatchMu(), num_bins, (char*)"Total Flux");
	gnuplot_plot_xy(handle, fuel_flux->getBinner(0)->getBinCenters(),
			fuel_flux->getBatchMu(), num_bins, (char*)"Fuel Flux");
	gnuplot_saveplot(handle, (char*)"flux");
	gnuplot_plot_xy(handle, moderator_flux->getBinner(0)->getBinCenters(),
			moderator_flux->getBatchMu(), num_bins, (char*)"Moderator Flux");
	gnuplot_close(handle);


	/* Free all allocated memory */
	delete [] pellet;
	delete [] coolant;
	delete [] fissioners;

	delete [] moderator;
	delete [] fuel;

	delete total_flux;
	delete fuel_flux;
	delete moderator_flux;
	delete tot_fiss_rate;
	delete tot_abs_rate;
	delete fuel_flux_ratio;
	delete moderator_flux_ratio;
	delete H1_capture_rate_2G;
	delete H1_elastic_rate_2G;
	delete O16_elastic_rate_2G;
	delete U235_capture_rate_2G;
	delete U235_elastic_rate_2G;
	delete U235_fission_rate_2G;
	delete U238_capture_rate_2G;
	delete U238_elastic_rate_2G;
	delete U238_fission_rate_2G;
	delete ZR90_elastic_rate_2G;
	delete two_group_flux;
	delete coll_rate_2G;
	delete transport_rate_2G;
	delete diffusion_rate_2G;

	delete H1;
	delete O16;
	delete ZR90;
	delete U235;
	delete U238;

	log_printf(RESULT, "*******************************************************"
													"*************************");
	log_printf(RESULT, "\t\t\t\tTiming Results");
	log_printf(RESULT, "*******************************************************"
													"*************************");
	timer.printSplits();
}
Ejemplo n.º 21
0
int
gui_keyboard_read_cb (void *data, int fd)
{
    int ret, i, accept_paste, cancel_paste, text_added_to_buffer, paste_lines;
    unsigned char buffer[4096];
    
    /* make C compiler happy */
    (void) data;
    (void) fd;
    
    accept_paste = 0;
    cancel_paste = 0;
    text_added_to_buffer = 0;

    if (gui_keyboard_paste_pending)
    {
        ret = read (STDIN_FILENO, buffer, 1);
        if (ret == 0)
        {
            /* no data on stdin, terminal lost */
            log_printf (_("Terminal lost, exiting WeeChat..."));
            hook_signal_send ("quit", WEECHAT_HOOK_SIGNAL_STRING, NULL);
            weechat_quit = 1;
            return WEECHAT_RC_OK;
        }
        if (ret <= 0)
            return WEECHAT_RC_OK;
        
        /* ctrl-Y: accept paste */
        if (buffer[0] == 25)
            accept_paste = 1;
        
        /* ctrl-N: cancel paste */
        if (buffer[0] == 14)
            cancel_paste = 1;
    }
    else
    {
        ret = read (STDIN_FILENO, buffer, sizeof (buffer));
        if (ret == 0)
        {
            /* no data on stdin, terminal lost */
            log_printf (_("Terminal lost, exiting WeeChat..."));
            hook_signal_send ("quit", WEECHAT_HOOK_SIGNAL_STRING, NULL);
            weechat_quit = 1;
            return WEECHAT_RC_OK;
        }
        if (ret < 0)
            return WEECHAT_RC_OK;
        
        for (i = 0; i < ret; i++)
        {
            gui_keyboard_buffer_add (buffer[i]);
        }
        
        text_added_to_buffer = 1;
    }
    
    if (gui_keyboard_paste_pending)
    {
        /* user is ok for pasting text, let's paste! */
        if (accept_paste)
            gui_keyboard_paste_accept ();
        /* user doesn't want to paste text: clear whole buffer! */
        else if (cancel_paste)
            gui_keyboard_paste_cancel ();
        else if (text_added_to_buffer)
            gui_input_text_changed_modifier_and_signal (gui_current_window->buffer);
    }
    else
    {
        /* detect user paste or large amount of text
           if so, ask user what to do */
        if (CONFIG_INTEGER(config_look_paste_max_lines) > 0)
        {
            paste_lines = gui_keyboard_get_paste_lines ();
            if (paste_lines > CONFIG_INTEGER(config_look_paste_max_lines))
            {
                gui_keyboard_paste_pending = 1;
                gui_input_paste_pending_signal ();
            }
        }
    }
    
    gui_keyboard_flush ();
    
    return WEECHAT_RC_OK;
}
Ejemplo n.º 22
0
int remove_skiplist(skiplist_t *sl, skiplist_key_t *key, skiplist_data_t *data)
{
    skiplist_node_t *ptr[SKIPLIST_MAX_LEVEL];
    skiplist_node_t *sn2;
    skiplist_ele_t *se, *se2, *prev;
    int cmp, i, empty_node, found;

    found = 0;
    empty_node = 0;
    memset(ptr, 0, sizeof(ptr));
    cmp = find_key(sl, ptr, key, 0);

    if (cmp != 0) {
        return(1);    //** No match so return
    }

    log_printf(15, "remove_skiplist: list=%p\n", sl);

    se = &(ptr[0]->next[0]->ele);
    if (data == NULL) {  //** Free all the data blocks
        found = 1;
        sl->n_ele--;
        if (se->data != NULL) sl->data_free(se->data);
        se = se->next;
        while (se != NULL) {
            sl->n_ele--;
            sl->data_free(se->data);
            se2 = se;
            se = se->next;
            free(se2);
        }

        empty_node = 1;
    } else {  //** Just free the block in question
        if (se->data == data) {   //** Head element is a match
            found = 1;
            sl->n_ele--;
            if (se->data != NULL) {
                sl->data_free(se->data);
            }
            se->data = NULL;
            if (se->next != NULL) {
                se2 = se->next;
                se->data = se2->data;
                se->next = se2->next;
                free(se2);
            } else {
                empty_node = 1;
            }
        } else {  //** Have to scan the list for a match
            prev = se;
            se = se->next;
            while ((se != NULL) && (found == 0)) {
                if (se->data == data) {
                    found = 1;
                    sl->n_ele--;
                    if (se->data != NULL) sl->data_free(se->data);
                    se2 = se->next;
                    prev->next = se2;
                    free(se);
                } else {
                    prev = se;
                    se = se->next;
                }
            }
        }

    }

    if (empty_node == 1) {
        sn2 = ptr[0]->next[0];
        for (i=0; i<=sn2->level; i++) {
            ptr[i]->next[i] = sn2->next[i];
        }

        if (sn2->level == sl->current_max) {
            i = sl->current_max;
            while ((i>0) && (sl->head->next[i] == NULL)) {
                i--;
            }
            sl->current_max = i;
        }

        sl->n_keys--;
        destroy_skiplist_node(sl, sn2);
    }

    found = (found == 1) ? 0 : 1;
    return(found);
}
Ejemplo n.º 23
0
int main (int argc, char **argv, char **envp)
{
	const char *error_string;
	struct totem_config totem_config;
	int res, ch;
	int background, setprio;
	struct stat stat_out;
	enum e_corosync_done flock_err;
	uint64_t totem_config_warnings;
	struct scheduler_pause_timeout_data scheduler_pause_timeout_data;

	/* default configuration
	 */
	background = 1;
	setprio = 0;

	while ((ch = getopt (argc, argv, "fprv")) != EOF) {

		switch (ch) {
			case 'f':
				background = 0;
				break;
			case 'p':
				break;
			case 'r':
				setprio = 1;
				break;
			case 'v':
				printf ("Corosync Cluster Engine, version '%s'\n", VERSION);
				printf ("Copyright (c) 2006-2009 Red Hat, Inc.\n");
				logsys_system_fini();
				return EXIT_SUCCESS;

				break;
			default:
				fprintf(stderr, \
					"usage:\n"\
					"        -f     : Start application in foreground.\n"\
					"        -p     : Does nothing.    \n"\
					"        -r     : Set round robin realtime scheduling \n"\
					"        -v     : Display version and SVN revision of Corosync and exit.\n");
				logsys_system_fini();
				return EXIT_FAILURE;
		}
	}

	/*
	 * Set round robin realtime scheduling with priority 99
	 * Lock all memory to avoid page faults which may interrupt
	 * application healthchecking
	 */
	if (setprio) {
		corosync_setscheduler ();
	}

	corosync_mlockall ();

	/*
	 * Other signals are registered later via qb_loop_signal_add
	 */
	(void)signal (SIGSEGV, sigsegv_handler);
	(void)signal (SIGABRT, sigabrt_handler);
#if MSG_NOSIGNAL != 0
	(void)signal (SIGPIPE, SIG_IGN);
#endif

	if (icmap_init() != CS_OK) {
		log_printf (LOGSYS_LEVEL_ERROR, "Corosync Executive couldn't initialize configuration component.");
		corosync_exit_error (COROSYNC_DONE_ICMAP);
	}
	set_icmap_ro_keys_flag();

	/*
	 * Initialize the corosync_api_v1 definition
	 */
	api = apidef_get ();

	res = coroparse_configparse(icmap_get_global_map(), &error_string);
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_MAINCONFIGREAD);
	}

	res = corosync_log_config_read (&error_string);
	if (res == -1) {
		/*
		 * if we are here, we _must_ flush the logsys queue
		 * and try to inform that we couldn't read the config.
		 * this is a desperate attempt before certain death
		 * and there is no guarantee that we can print to stderr
		 * nor that logsys is sending the messages where we expect.
		 */
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		fprintf(stderr, "%s", error_string);
		syslog (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_LOGCONFIGREAD);
	}

	log_printf (LOGSYS_LEVEL_NOTICE, "Corosync Cluster Engine ('%s'): started and ready to provide service.", VERSION);
	log_printf (LOGSYS_LEVEL_INFO, "Corosync built-in features:" PACKAGE_FEATURES "");

	/*
	 * Make sure required directory is present
	 */
	res = stat (get_run_dir(), &stat_out);
	if ((res == -1) || (res == 0 && !S_ISDIR(stat_out.st_mode))) {
		log_printf (LOGSYS_LEVEL_ERROR, "Required directory not present %s.  Please create it.", get_run_dir());
		corosync_exit_error (COROSYNC_DONE_DIR_NOT_PRESENT);
	}

	res = chdir(get_run_dir());
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "Cannot chdir to run directory %s.  "
		    "Please make sure it has correct context and rights.", get_run_dir());
		corosync_exit_error (COROSYNC_DONE_DIR_NOT_PRESENT);
	}

	res = totem_config_read (&totem_config, &error_string, &totem_config_warnings);
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_MAINCONFIGREAD);
	}

	if (totem_config_warnings & TOTEM_CONFIG_WARNING_MEMBERS_IGNORED) {
		log_printf (LOGSYS_LEVEL_WARNING, "member section is used together with nodelist. Members ignored.");
	}

	if (totem_config_warnings & TOTEM_CONFIG_WARNING_MEMBERS_DEPRECATED) {
		log_printf (LOGSYS_LEVEL_WARNING, "member section is deprecated.");
	}

	if (totem_config_warnings & TOTEM_CONFIG_WARNING_TOTEM_NODEID_IGNORED) {
		log_printf (LOGSYS_LEVEL_WARNING, "nodeid appears both in totem section and nodelist. Nodelist one is used.");
	}

	if (totem_config_warnings != 0) {
		log_printf (LOGSYS_LEVEL_WARNING, "Please migrate config file to nodelist.");
	}

	res = totem_config_keyread (&totem_config, &error_string);
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_MAINCONFIGREAD);
	}

	res = totem_config_validate (&totem_config, &error_string);
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "%s", error_string);
		corosync_exit_error (COROSYNC_DONE_MAINCONFIGREAD);
	}

	ip_version = totem_config.ip_version;

	totem_config.totem_memb_ring_id_create_or_load = corosync_ring_id_create_or_load;
	totem_config.totem_memb_ring_id_store = corosync_ring_id_store;

	totem_config.totem_logging_configuration = totem_logging_configuration;
	totem_config.totem_logging_configuration.log_subsys_id = _logsys_subsys_create("TOTEM", "totem,"
			"totemmrp.c,totemrrp.c,totemip.c,totemconfig.c,totemcrypto.c,totemsrp.c,"
			"totempg.c,totemiba.c,totemudp.c,totemudpu.c,totemnet.c");

	totem_config.totem_logging_configuration.log_level_security = LOGSYS_LEVEL_WARNING;
	totem_config.totem_logging_configuration.log_level_error = LOGSYS_LEVEL_ERROR;
	totem_config.totem_logging_configuration.log_level_warning = LOGSYS_LEVEL_WARNING;
	totem_config.totem_logging_configuration.log_level_notice = LOGSYS_LEVEL_NOTICE;
	totem_config.totem_logging_configuration.log_level_debug = LOGSYS_LEVEL_DEBUG;
	totem_config.totem_logging_configuration.log_level_trace = LOGSYS_LEVEL_TRACE;
	totem_config.totem_logging_configuration.log_printf = _logsys_log_printf;
	logsys_config_apply();

	/*
	 * Now we are fully initialized.
	 */
	if (background) {
		corosync_tty_detach ();
	}

	corosync_poll_handle = qb_loop_create ();

	memset(&scheduler_pause_timeout_data, 0, sizeof(scheduler_pause_timeout_data));
	scheduler_pause_timeout_data.totem_config = &totem_config;
	timer_function_scheduler_timeout (&scheduler_pause_timeout_data);

	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_LOW,
		SIGUSR2, NULL, sig_diag_handler, NULL);
	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_HIGH,
		SIGINT, NULL, sig_exit_handler, NULL);
	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_HIGH,
		SIGSEGV, NULL, sig_segv_handler, NULL);
	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_HIGH,
		SIGABRT, NULL, sig_abrt_handler, NULL);
	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_HIGH,
		SIGQUIT, NULL, sig_exit_handler, NULL);
	qb_loop_signal_add(corosync_poll_handle, QB_LOOP_HIGH,
		SIGTERM, NULL, sig_exit_handler, NULL);

	if (logsys_thread_start() != 0) {
		log_printf (LOGSYS_LEVEL_ERROR, "Can't initialize log thread");
		corosync_exit_error (COROSYNC_DONE_LOGCONFIGREAD);
	}

	if ((flock_err = corosync_flock (corosync_lock_file, getpid ())) != COROSYNC_DONE_EXIT) {
		corosync_exit_error (flock_err);
	}

	/*
	 * if totempg_initialize doesn't have root priveleges, it cannot
	 * bind to a specific interface.  This only matters if
	 * there is more then one interface in a system, so
	 * in this case, only a warning is printed
	 */
	/*
	 * Join multicast group and setup delivery
	 *  and configuration change functions
	 */
	/* totempg層初期化 */
	totempg_initialize (
		corosync_poll_handle,
		&totem_config);
	/* サービス登録準備処理 */
	totempg_service_ready_register (
		main_service_ready);
	/* グループ初期化 */
	totempg_groups_initialize (
		&corosync_group_handle,
		deliver_fn,
		confchg_fn);
	/* corosync自体のグループ(グループa)への参加 */
	totempg_groups_join (
		corosync_group_handle,
		&corosync_group,
		1);

	/*
	 * Drop root privleges to user 'corosync'
	 * TODO: Don't really need full root capabilities;
	 *       needed capabilities are:
	 * CAP_NET_RAW (bindtodevice)
	 * CAP_SYS_NICE (setscheduler)
	 * CAP_IPC_LOCK (mlockall)
	 */
	priv_drop ();

	schedwrk_init (
		serialize_lock,
		serialize_unlock);

	/*
	 * Start main processing loop
	 */
	qb_loop_run (corosync_poll_handle);

	/*
	 * Exit was requested
	 */
	totempg_finalize ();

	/*
	 * free the loop resources
	 */
	qb_loop_destroy (corosync_poll_handle);

	/*
	 * free up the icmap 
	 */

	/*
	 * Remove pid lock file
	 */
	unlink (corosync_lock_file);

	corosync_exit_error (COROSYNC_DONE_EXIT);

	return EXIT_SUCCESS;
}
Ejemplo n.º 24
0
void sl_no_key_free(skiplist_key_t *key)
{
    log_printf(15, "key p=%p\n", key);
    return;
}
Ejemplo n.º 25
0
static void corosync_totem_stats_updater (void *data)
{
	totempg_stats_t * stats;
	uint32_t total_mtt_rx_token;
	uint32_t total_backlog_calc;
	uint32_t total_token_holdtime;
	int t, prev, i;
	int32_t token_count;
	char key_name[ICMAP_KEYNAME_MAXLEN];

	stats = api->totem_get_stats();

	icmap_set_uint32("runtime.totem.pg.msg_reserved", stats->msg_reserved);
	icmap_set_uint32("runtime.totem.pg.msg_queue_avail", stats->msg_queue_avail);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.orf_token_tx", stats->mrp->srp->orf_token_tx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.orf_token_rx", stats->mrp->srp->orf_token_rx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.memb_merge_detect_tx", stats->mrp->srp->memb_merge_detect_tx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.memb_merge_detect_rx", stats->mrp->srp->memb_merge_detect_rx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.memb_join_tx", stats->mrp->srp->memb_join_tx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.memb_join_rx", stats->mrp->srp->memb_join_rx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.mcast_tx", stats->mrp->srp->mcast_tx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.mcast_retx", stats->mrp->srp->mcast_retx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.mcast_rx", stats->mrp->srp->mcast_rx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.memb_commit_token_tx", stats->mrp->srp->memb_commit_token_tx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.memb_commit_token_rx", stats->mrp->srp->memb_commit_token_rx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.token_hold_cancel_tx", stats->mrp->srp->token_hold_cancel_tx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.token_hold_cancel_rx", stats->mrp->srp->token_hold_cancel_rx);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.operational_entered", stats->mrp->srp->operational_entered);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.operational_token_lost", stats->mrp->srp->operational_token_lost);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.gather_entered", stats->mrp->srp->gather_entered);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.gather_token_lost", stats->mrp->srp->gather_token_lost);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.commit_entered", stats->mrp->srp->commit_entered);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.commit_token_lost", stats->mrp->srp->commit_token_lost);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.recovery_entered", stats->mrp->srp->recovery_entered);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.recovery_token_lost", stats->mrp->srp->recovery_token_lost);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.consensus_timeouts", stats->mrp->srp->consensus_timeouts);
	icmap_set_uint64("runtime.totem.pg.mrp.srp.rx_msg_dropped", stats->mrp->srp->rx_msg_dropped);
	icmap_set_uint32("runtime.totem.pg.mrp.srp.continuous_gather", stats->mrp->srp->continuous_gather);
	icmap_set_uint32("runtime.totem.pg.mrp.srp.continuous_sendmsg_failures",
	    stats->mrp->srp->continuous_sendmsg_failures);

	icmap_set_uint8("runtime.totem.pg.mrp.srp.firewall_enabled_or_nic_failure",
		stats->mrp->srp->continuous_gather > MAX_NO_CONT_GATHER ? 1 : 0);

	if (stats->mrp->srp->continuous_gather > MAX_NO_CONT_GATHER ||
	    stats->mrp->srp->continuous_sendmsg_failures > MAX_NO_CONT_SENDMSG_FAILURES) {
		log_printf (LOGSYS_LEVEL_WARNING,
			"Totem is unable to form a cluster because of an "
			"operating system or network fault. The most common "
			"cause of this message is that the local firewall is "
			"configured improperly.");
		icmap_set_uint8("runtime.totem.pg.mrp.srp.firewall_enabled_or_nic_failure", 1);
	} else {
		icmap_set_uint8("runtime.totem.pg.mrp.srp.firewall_enabled_or_nic_failure", 0);
	}

	for (i = 0; i < stats->mrp->srp->rrp->interface_count; i++) {
		snprintf(key_name, ICMAP_KEYNAME_MAXLEN, "runtime.totem.pg.mrp.rrp.%u.faulty", i);
		icmap_set_uint8(key_name, stats->mrp->srp->rrp->faulty[i]);
	}
	total_mtt_rx_token = 0;
	total_token_holdtime = 0;
	total_backlog_calc = 0;
	token_count = 0;
	t = stats->mrp->srp->latest_token;
	while (1) {
		if (t == 0)
			prev = TOTEM_TOKEN_STATS_MAX - 1;
		else
			prev = t - 1;
		if (prev == stats->mrp->srp->earliest_token)
			break;
		/* if tx == 0, then dropped token (not ours) */
		if (stats->mrp->srp->token[t].tx != 0 ||
			(stats->mrp->srp->token[t].rx - stats->mrp->srp->token[prev].rx) > 0 ) {
			total_mtt_rx_token += (stats->mrp->srp->token[t].rx - stats->mrp->srp->token[prev].rx);
			total_token_holdtime += (stats->mrp->srp->token[t].tx - stats->mrp->srp->token[t].rx);
			total_backlog_calc += stats->mrp->srp->token[t].backlog_calc;
			token_count++;
		}
		t = prev;
	}
	if (token_count) {
		icmap_set_uint32("runtime.totem.pg.mrp.srp.mtt_rx_token", (total_mtt_rx_token / token_count));
		icmap_set_uint32("runtime.totem.pg.mrp.srp.avg_token_workload", (total_token_holdtime / token_count));
		icmap_set_uint32("runtime.totem.pg.mrp.srp.avg_backlog_calc", (total_backlog_calc / token_count));
	}

	cs_ipcs_stats_update();

	api->timer_add_duration (1500 * MILLI_2_NANO_SECONDS, NULL,
		corosync_totem_stats_updater,
		&corosync_stats_timer_handle);
}
Ejemplo n.º 26
0
void sl_no_data_free(skiplist_data_t *data)
{
    log_printf(15, "data p=%p\n", data);
    return;
}
static void gms_exec_message_handler (
                                      void *message,
                                      unsigned int nodeid)
{
    mar_req_header_t              header = {0};
    struct VDECL(req_exec_gms_nodejoin) req_exec_gms_nodejoin = {{0}};
    ClGmsViewNodeT               *node = NULL;
    ClRcT                         rc = CL_OK;
    ClGmsClusterMemberT           thisGmsClusterNode = {0};
    char                          nodeIp[256 * INTERFACE_MAX] = "";
    int                           isLocalMsg = 0;
    int                           verCode = 0;
    ClBufferHandleT               bufferHandle = NULL;

    /* Get the ip address string for the given nodeId */
    strncpy(nodeIp, get_node_ip(nodeid), (256 * INTERFACE_MAX)-1);
    if (strcmp(nodeIp, totemip_print(this_ip)) == 0)
    {
        isLocalMsg = 1;
    }

    /* Unmarshall the incoming message */
    rc = clBufferCreate(&bufferHandle);
    if (rc != CL_OK)
    {
        clLogError(OPN,AIS,
                   "Failed to create buffer while unmarshalling the received message. rc 0x%x",rc);
        return;
    }

    memcpy(&header, message, sizeof(mar_req_header_t));

    rc = clBufferNBytesWrite(bufferHandle, (ClUint8T *)message+sizeof(mar_req_header_t), header.size-sizeof(mar_req_header_t));
    if (rc != CL_OK)
    {
        clLogError(OPN,AIS,
                   "Failed to retrieve data from buffer. rc 0x%x",rc);
        goto out_delete;
    }

    rc = unmarshallReqExecGmsNodeJoin(bufferHandle, &req_exec_gms_nodejoin);
    if (rc != CL_OK)
    {
        clLogError(OPN,AIS,"Failed to unmarshall the data. rc 0x%x",rc);
        goto out_delete;
    }

    verCode = CL_VERSION_CODE(req_exec_gms_nodejoin.version.releaseCode, 
                              req_exec_gms_nodejoin.version.majorVersion,
                              req_exec_gms_nodejoin.version.minorVersion);
    clLog(DBG,OPN,AIS,
          "Received a %d message from version [%d.%d.%d].",req_exec_gms_nodejoin.gmsMessageType,
          req_exec_gms_nodejoin.version.releaseCode, req_exec_gms_nodejoin.version.majorVersion, 
          req_exec_gms_nodejoin.version.minorVersion);
    /* Verify version */
    if (verCode > CL_VERSION_CODE(curVer.releaseCode, curVer.majorVersion, curVer.minorVersion)) {
        /* I received a message from higher version and it dont know
         * how to decode it. So it discarding it. */
        clLog(NOTICE,OPN,AIS,
              "Version mismatch detected. Discarding the message ");
        goto out_delete;
    }

    // message type & message data
    clLog(DBG,OPN,AIS,"message type %d from groupId %d!\n", req_exec_gms_nodejoin.gmsMessageType, req_exec_gms_nodejoin.gmsGroupId);

    /* This message is from same version. So processing it */
    switch (req_exec_gms_nodejoin.gmsMessageType)
    {
    case CL_GMS_CLUSTER_JOIN_MSG:
        {
            ClUint32T minVersion = CL_VERSION_CODE(5, 0, 0);
            clLog(DBG,OPN,AIS,
                  "Received multicast message for cluster join from ioc node [%#x:%#x]",
                  req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeAddress.iocPhyAddress.nodeAddress,
                  req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeAddress.iocPhyAddress.portId);
            clNodeCacheMinVersionGet(NULL, &minVersion);
            if(minVersion >= CL_VERSION_CODE(5, 0, 0) && gAspNativeLeaderElection)
            {
                clLog(DBG, OPN, AIS,
                      "Skipping multicast join since node cache view is used to form the cluster ring");
                goto out_delete;
            }
            node = (ClGmsViewNodeT *) clHeapAllocate(sizeof(ClGmsViewNodeT));
            if (node == NULL)
            {
                clLog (ERROR,OPN,AIS, "clHeapAllocate failed");
                goto out_delete;
            }
            else {
                rc = clVersionVerify(
                                     &(gmsGlobalInfo.config.versionsSupported),
                                     &(req_exec_gms_nodejoin.specificMessage.gmsClusterNode.gmsVersion)
                                     );
                ringVersion.releaseCode =
                    req_exec_gms_nodejoin.specificMessage.gmsClusterNode.gmsVersion.releaseCode;
                ringVersion.majorVersion=
                    req_exec_gms_nodejoin.specificMessage.gmsClusterNode.gmsVersion.majorVersion;
                ringVersion.minorVersion=
                    req_exec_gms_nodejoin.specificMessage.gmsClusterNode.gmsVersion.minorVersion;
                if(rc != CL_OK)
                {
                    ringVersionCheckPassed = CL_FALSE;
                    /* copy the ring version */
                    clGmsCsLeave( &joinCs );
                    clLog (ERROR,OPN,AIS,
                           "Server Version Mismatch detected for this join message");
                    break;
                }

                _clGmsGetThisNodeInfo(&thisGmsClusterNode);
                if( thisGmsClusterNode.nodeId !=
                    req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeId)
                {
                    /* TODO This will never happen... */
                    clGmsCsLeave( &joinCs );
                }

                node->viewMember.clusterMember =
                    req_exec_gms_nodejoin.specificMessage.gmsClusterNode;
                /* If this is local join, then update the IP address */
                if (thisGmsClusterNode.nodeId ==
                    req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeId)
                {
                    memcpy(&node->viewMember.clusterMember.nodeIpAddress,
                           &myAddress, sizeof(ClGmsNodeAddressT));
                }

                rc = _clGmsEngineClusterJoin(req_exec_gms_nodejoin.gmsGroupId,
                                             req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeId,
                                             node);
            }
        }
        break;
    case CL_GMS_CLUSTER_EJECT_MSG:
        clLog (DBG,OPN,AIS,
               "Received cluster eject multicast message from ioc node [%#x:%#x]",
               req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeAddress.iocPhyAddress.nodeAddress,
               req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeAddress.iocPhyAddress.portId);
        /* inform the member about the eject by invoking the ejection
         *  callback registered with the reason UKNOWN */
        /* The below logic is same for the leave as well so we just
         *  fall through the case */
        _clGmsGetThisNodeInfo(&thisGmsClusterNode);
        if( req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeId ==
            thisGmsClusterNode.nodeId)
        {
            rc = _clGmsCallClusterMemberEjectCallBack(
                                                      req_exec_gms_nodejoin.ejectReason);
            if( rc != CL_OK )
            {
                clLog(ERROR,OPN,AIS,"_clGmsCallEjectCallBack failed with"
                      "rc:0x%x",rc);
            }
        }
    case CL_GMS_CLUSTER_LEAVE_MSG:
        clLog(DBG,OPN,AIS,
              "Received cluster leave multicast message from ioc node [%#x:%#x]",
              req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeAddress.iocPhyAddress.nodeAddress,
              req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeAddress.iocPhyAddress.portId);
        rc = _clGmsEngineClusterLeave(req_exec_gms_nodejoin.gmsGroupId,
                                      req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeId);
        break;
    case CL_GMS_GROUP_CREATE_MSG:
        clLog(DBG,OPN,AIS,
              "Received group create multicast message from ioc node [%#x:%#x]",
              req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberAddress.iocPhyAddress.nodeAddress,
              req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberAddress.iocPhyAddress.portId);

        rc = _clGmsEngineGroupCreate(req_exec_gms_nodejoin.specificMessage.groupMessage.groupData.groupName,
                                     req_exec_gms_nodejoin.specificMessage.groupMessage.groupData.groupParams,
                                     req_exec_gms_nodejoin.contextHandle, isLocalMsg);
        break;
    case CL_GMS_GROUP_DESTROY_MSG:
        clLog(DBG,OPN,AIS,
              "Received group destroy multicast message from ioc node [%#x:%#x]",
              req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberAddress.iocPhyAddress.nodeAddress,
              req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberAddress.iocPhyAddress.portId);

        rc = _clGmsEngineGroupDestroy(req_exec_gms_nodejoin.specificMessage.groupMessage.groupData.groupId,
                                      req_exec_gms_nodejoin.specificMessage.groupMessage.groupData.groupName,
                                      req_exec_gms_nodejoin.contextHandle, isLocalMsg);
        break;
    case CL_GMS_GROUP_JOIN_MSG:
        clLog(DBG,OPN,AIS,
              "Received group join multicast message from ioc node [%#x:%#x]",
              req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberAddress.iocPhyAddress.nodeAddress,
              req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberAddress.iocPhyAddress.portId);

        node = (ClGmsViewNodeT *) clHeapAllocate(sizeof(ClGmsViewNodeT));
        if (!node)
        {
            log_printf (LOG_LEVEL_NOTICE, "clHeapAllocate failed");
            goto out_delete;
        }
        else {
            /* FIXME: Need to verify version */
            memcpy(&node->viewMember.groupMember,&req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode,
                   sizeof(ClGmsGroupMemberT));
            memcpy(&node->viewMember.groupData, &req_exec_gms_nodejoin.specificMessage.groupMessage.groupData,
                   sizeof(ClGmsGroupInfoT));
            rc = _clGmsEngineGroupJoin(req_exec_gms_nodejoin.specificMessage.groupMessage.groupData.groupId,
                                       node, req_exec_gms_nodejoin.contextHandle, isLocalMsg);
        }
        break;
    case CL_GMS_GROUP_LEAVE_MSG:
        clLog(DBG,OPN,AIS,
              "Received group leave multicast message from ioc node [%#x:%#x]",
              req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberAddress.iocPhyAddress.nodeAddress,
              req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberAddress.iocPhyAddress.portId);

        rc = _clGmsEngineGroupLeave(req_exec_gms_nodejoin.specificMessage.groupMessage.groupData.groupId,
                                    req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberId,
                                    req_exec_gms_nodejoin.contextHandle, isLocalMsg);
        break;
    case CL_GMS_COMP_DEATH:
        clLog(DBG,OPN,AIS,
              "Received comp death multicast message");
        rc = _clGmsRemoveMemberOnCompDeath(req_exec_gms_nodejoin.specificMessage.groupMessage.gmsGroupNode.memberId);
        break;
    case CL_GMS_LEADER_ELECT_MSG:
        clLog(DBG,OPN,AIS,
              "Received leader elect multicast message from ioc node [%#x:%#x]",
              req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeAddress.iocPhyAddress.nodeAddress,
              req_exec_gms_nodejoin.specificMessage.gmsClusterNode.nodeAddress.iocPhyAddress.portId);
        rc = _clGmsEnginePreferredLeaderElect(req_exec_gms_nodejoin.specificMessage.gmsClusterNode, 
                                              req_exec_gms_nodejoin.contextHandle,
                                              isLocalMsg);
        break;
    case CL_GMS_SYNC_MESSAGE:
        clLog(DBG,OPN,AIS,
              "Received gms synch multicast message");
        rc = _clGmsEngineGroupInfoSync((ClGmsGroupSyncNotificationT *)(req_exec_gms_nodejoin.dataPtr));
        clHeapFree(((ClGmsGroupSyncNotificationT *)req_exec_gms_nodejoin.dataPtr)->groupInfoList);
        clHeapFree(((ClGmsGroupSyncNotificationT *)req_exec_gms_nodejoin.dataPtr)->groupMemberList);
        clHeapFree(req_exec_gms_nodejoin.dataPtr);
        break;

    case CL_GMS_GROUP_MCAST_MSG:
        _clGmsEngineMcastMessageHandler(
                                        &(req_exec_gms_nodejoin.specificMessage.mcastMessage.groupInfo.gmsGroupNode),
                                        &(req_exec_gms_nodejoin.specificMessage.mcastMessage.groupInfo.groupData),
                                        req_exec_gms_nodejoin.specificMessage.mcastMessage.userDataSize,
                                        req_exec_gms_nodejoin.dataPtr);
        break;
    default:
        clLogMultiline(ERROR,OPN,AIS,
                       "Openais GMS wrapper received Message wih invalid [MsgType=%x]. \n"
                       "This could be because of multicast port clashes.",
                       req_exec_gms_nodejoin.gmsMessageType);
        goto out_delete;
    }
    clLog(TRACE,OPN,AIS,
          "Processed the received message. Returning");
    out_delete:
    clBufferDelete(&bufferHandle);
}
Ejemplo n.º 28
0
void sl_simple_free(skiplist_data_t *data)
{
    log_printf(15, "p=%p\n", data);
    free(data);
}
Ejemplo n.º 29
0
/*
 * Generic use ranged attack function			-Thoric & Tricops
 */
ch_ret ranged_attack( char_data * ch, string argument, obj_data * weapon, obj_data * projectile, short dt, short range )
{
   string arg, arg1, temp;

   if( !argument.empty(  ) && argument[0] == '\'' )
   {
      one_argument( argument, temp );
      argument = temp;
   }

   argument = one_argument( argument, arg );
   argument = one_argument( argument, arg1 );

   if( arg.empty(  ) )
   {
      ch->print( "Where?  At who?\r\n" );
      return rNONE;
   }

   /*
    * get an exit or a victim 
    */
   short dir = -1;
   exit_data *pexit;
   char_data *victim = nullptr;
   if( !( pexit = find_door( ch, arg, true ) ) )
   {
      if( !( victim = ch->get_char_room( arg ) ) )
      {
         ch->print( "Aim in what direction?\r\n" );
         return rNONE;
      }
      else
      {
         if( ch->who_fighting(  ) == victim )
         {
            ch->print( "They are too close to release that type of attack!\r\n" );
            return rNONE;
         }
      }
   }
   else
      dir = pexit->vdir;

   /*
    * check for ranged attacks from private rooms, etc 
    */
   if( !victim )
   {
      if( ch->in_room->flags.test( ROOM_PRIVATE ) || ch->in_room->flags.test( ROOM_SOLITARY ) )
      {
         ch->print( "You cannot perform a ranged attack from a private room.\r\n" );
         return rNONE;
      }
      if( ch->in_room->tunnel > 0 )
      {
         if( ( int )ch->in_room->people.size(  ) >= ch->in_room->tunnel )
         {
            ch->print( "This room is too cramped to perform such an attack.\r\n" );
            return rNONE;
         }
      }
   }

   skill_type *skill = nullptr;
   if( IS_VALID_SN( dt ) )
      skill = skill_table[dt];

   if( pexit && !pexit->to_room )
   {
      ch->print( "Are you expecting to fire through a wall!?\r\n" );
      return rNONE;
   }

   /*
    * Check for obstruction 
    */
   if( pexit && IS_EXIT_FLAG( pexit, EX_CLOSED ) )
   {
      if( IS_EXIT_FLAG( pexit, EX_SECRET ) || IS_EXIT_FLAG( pexit, EX_DIG ) )
         ch->print( "Are you expecting to fire through a wall!?\r\n" );
      else
         ch->print( "Are you expecting to fire through a door!?\r\n" );
      return rNONE;
   }

   /*
    * Keeps em from firing through a wall but can still fire through an arrow slit or window, Marcus 
    */
   if( pexit )
   {
      if( ( IS_EXIT_FLAG( pexit, EX_FORTIFIED ) || IS_EXIT_FLAG( pexit, EX_HEAVY )
            || IS_EXIT_FLAG( pexit, EX_MEDIUM ) || IS_EXIT_FLAG( pexit, EX_LIGHT ) || IS_EXIT_FLAG( pexit, EX_CRUMBLING ) )
          && !IS_EXIT_FLAG( pexit, EX_WINDOW ) && !IS_EXIT_FLAG( pexit, EX_ASLIT ) )
      {
         ch->print( "Are you expecting to fire through a wall!?\r\n" );
         return rNONE;
      }
   }

   char_data *vch = nullptr;
   if( pexit && !arg1.empty(  ) )
   {
      if( !( vch = scan_for_vic( ch, pexit, arg1 ) ) )
      {
         ch->print( "You cannot see your target.\r\n" );
         return rNONE;
      }

      /*
       * don't allow attacks on mobs that are in a no-missile room --Shaddai 
       */
      if( vch->in_room->flags.test( ROOM_NOMISSILE ) )
      {
         ch->print( "You can't get a clean shot off.\r\n" );
         return rNONE;
      }

      /*
       * can't properly target someone heavily in battle 
       */
      if( vch->num_fighting > MAX_FIGHT )
      {
         ch->print( "There is too much activity there for you to get a clear shot.\r\n" );
         return rNONE;
      }
   }

   if( vch )
   {
      if( !vch->CAN_PKILL(  ) || !ch->CAN_PKILL(  ) )
      {
         ch->print( "You can't do that!\r\n" );
         return rNONE;
      }
      if( vch && is_safe( ch, vch ) )
         return rNONE;
   }

   room_index *was_in_room = ch->in_room;
   const char *stxt = "burst of energy";
   if( projectile )
   {
      projectile->separate(  );
      if( pexit )
      {
         if( weapon )
         {
            act( AT_GREY, "You fire $p $T.", ch, projectile, dir_name[dir], TO_CHAR );
            act( AT_GREY, "$n fires $p $T.", ch, projectile, dir_name[dir], TO_ROOM );
         }
         else
         {
            act( AT_GREY, "You throw $p $T.", ch, projectile, dir_name[dir], TO_CHAR );
            act( AT_GREY, "$n throw $p $T.", ch, projectile, dir_name[dir], TO_ROOM );
         }
      }
      else
      {
         if( weapon )
         {
            act( AT_GREY, "You fire $p at $N.", ch, projectile, victim, TO_CHAR );
            act( AT_GREY, "$n fires $p at $N.", ch, projectile, victim, TO_NOTVICT );
            act( AT_GREY, "$n fires $p at you!", ch, projectile, victim, TO_VICT );
         }
         else
         {
            act( AT_GREY, "You throw $p at $N.", ch, projectile, victim, TO_CHAR );
            act( AT_GREY, "$n throws $p at $N.", ch, projectile, victim, TO_NOTVICT );
            act( AT_GREY, "$n throws $p at you!", ch, projectile, victim, TO_VICT );
         }
      }
   }
   else if( skill )
   {
      if( skill->noun_damage && skill->noun_damage[0] != '\0' )
         stxt = skill->noun_damage;
      else
         stxt = skill->name;
      /*
       * a plain "spell" flying around seems boring 
       */
      if( !str_cmp( stxt, "spell" ) )
         stxt = "magical burst of energy";
      if( skill->type == SKILL_SPELL )
      {
         if( pexit )
         {
            act( AT_MAGIC, "You release $t $T.", ch, aoran( stxt ), dir_name[dir], TO_CHAR );
            act( AT_MAGIC, "$n releases $s $t $T.", ch, stxt, dir_name[dir], TO_ROOM );
         }
         else
         {
            act( AT_MAGIC, "You release $t at $N.", ch, aoran( stxt ), victim, TO_CHAR );
            act( AT_MAGIC, "$n releases $s $t at $N.", ch, stxt, victim, TO_NOTVICT );
            act( AT_MAGIC, "$n releases $s $t at you!", ch, stxt, victim, TO_VICT );
         }
      }
   }
   else
   {
      bug( "%s: no projectile, no skill dt %d", __func__, dt );
      return rNONE;
   }

   /*
    * victim in same room 
    */
   if( victim )
   {
      check_illegal_pk( ch, victim );
      check_attacker( ch, victim );
      return ranged_got_target( ch, victim, weapon, projectile, 0, dt, stxt, AT_MAGIC );
   }

   /*
    * assign scanned victim 
    */
   victim = vch;

   /*
    * reverse direction text from move_char 
    */
   const char *dtxt = rev_exit( pexit->vdir );
   int dist = 0;

   while( dist <= range )
   {
      ch->from_room(  );
      if( !ch->to_room( pexit->to_room ) )
         log_printf( "char_to_room: %s:%s, line %d.", __FILE__, __func__, __LINE__ );

      if( IS_EXIT_FLAG( pexit, EX_CLOSED ) )
      {
         /*
          * whadoyahknow, the door's closed 
          */
         if( projectile )
            ch->printf( "&wYou see your %s pierce a door in the distance to the %s.", projectile->myobj(  ).c_str(  ), dir_name[dir] );
         else
            ch->printf( "&wYou see your %s hit a door in the distance to the %s.", stxt, dir_name[dir] );
         if( projectile )
            act_printf( AT_GREY, ch, projectile, nullptr, TO_ROOM, "$p flies in from %s and implants itself solidly in the %sern door.", dtxt, dir_name[dir] );
         else
            act_printf( AT_GREY, ch, nullptr, nullptr, TO_ROOM, "%s flies in from %s and implants itself solidly in the %sern door.", aoran( stxt ), dtxt, dir_name[dir] );
         break;
      }

      /*
       * no victim? pick a random one 
       */
      if( !victim )
      {
         list < char_data * >::iterator ich;
         for( ich = ch->in_room->people.begin(  ); ich != ch->in_room->people.end(  ); ++ich )
         {
            vch = *ich;

            if( ( ( ch->isnpc(  ) && !vch->isnpc(  ) ) || ( !ch->isnpc(  ) && vch->isnpc(  ) ) ) && number_bits( 1 ) == 0 )
            {
               victim = vch;
               break;
            }
         }
         if( victim && is_safe( ch, victim ) )
         {
            ch->from_room(  );
            if( !ch->to_room( was_in_room ) )
               log_printf( "char_to_room: %s:%s, line %d.", __FILE__, __func__, __LINE__ );
            return rNONE;
         }
      }

      /*
       * In the same room as our victim? 
       */
      if( victim && ch->in_room == victim->in_room )
      {
         if( projectile )
            act( AT_GREY, "$p flies in from $T.", ch, projectile, dtxt, TO_ROOM );
         else
            act( AT_GREY, "$t flies in from $T.", ch, aoran( stxt ), dtxt, TO_ROOM );

         /*
          * get back before the action starts 
          */
         ch->from_room(  );
         if( !ch->to_room( was_in_room ) )
            log_printf( "char_to_room: %s:%s, line %d.", __FILE__, __func__, __LINE__ );

         check_illegal_pk( ch, victim );
         check_attacker( ch, victim );
         return ranged_got_target( ch, victim, weapon, projectile, dist, dt, stxt, AT_GREY );
      }

      if( dist == range )
      {
         if( projectile )
         {
            act( AT_GREY, "Your $t falls harmlessly to the ground to the $T.", ch, projectile->myobj(  ).c_str(  ), dir_name[dir], TO_CHAR );
            act( AT_GREY, "$p flies in from $T and falls harmlessly to the ground here.", ch, projectile, dtxt, TO_ROOM );
            if( projectile->in_obj )
               projectile->from_obj(  );
            if( projectile->carried_by )
               projectile->from_char(  );
            projectile->to_room( ch->in_room, ch );
         }
         else
         {
            act( AT_MAGIC, "Your $t fizzles out harmlessly to the $T.", ch, stxt, dir_name[dir], TO_CHAR );
            act( AT_MAGIC, "$t flies in from $T and fizzles out harmlessly.", ch, aoran( stxt ), dtxt, TO_ROOM );
         }
         break;
      }

      if( !( pexit = ch->in_room->get_exit( dir ) ) )
      {
         if( projectile )
         {
            act( AT_GREY, "Your $t hits a wall and bounces harmlessly to the ground to the $T.", ch, projectile->myobj(  ).c_str(  ), dir_name[dir], TO_CHAR );
            act( AT_GREY, "$p strikes the $Tsern wall and falls harmlessly to the ground.", ch, projectile, dir_name[dir], TO_ROOM );
            if( projectile->in_obj )
               projectile->from_obj(  );
            if( projectile->carried_by )
               projectile->from_char(  );
            projectile->to_room( ch->in_room, ch );
         }
         else
         {
            act( AT_MAGIC, "Your $t harmlessly hits a wall to the $T.", ch, stxt, dir_name[dir], TO_CHAR );
            act( AT_MAGIC, "$t strikes the $Tsern wall and falls harmlessly to the ground.", ch, aoran( stxt ), dir_name[dir], TO_ROOM );
         }
         break;
      }
      if( projectile )
         act( AT_GREY, "$p flies in from $T.", ch, projectile, dtxt, TO_ROOM );
      else
         act( AT_MAGIC, "$t flies in from $T.", ch, aoran( stxt ), dtxt, TO_ROOM );
      ++dist;
   }

   ch->from_room(  );
   if( !ch->to_room( was_in_room ) )
      log_printf( "char_to_room: %s:%s, line %d.", __FILE__, __func__, __LINE__ );

   if( projectile->carried_by == ch )
      projectile->extract(  );
   return rNONE;
}
Ejemplo n.º 30
0
/**
 * @brief Compute \f$ k_{eff} \f$ from the total, fission and scattering
 *        reaction rates and leakage.
 * @details This method computes the current approximation to the
 *          multiplication factor on this iteration as follows:
 *          \f$ k_{eff} = \frac{\displaystyle\sum_{i \in I}
 *                        \displaystyle\sum_{g \in G} \nu \Sigma^F_g \Phi V_{i}}
 *                        {\displaystyle\sum_{i \in I}
 *                        \displaystyle\sum_{g \in G} (\Sigma^T_g \Phi V_{i} -
 *                        \Sigma^S_g \Phi V_{i} - L_{i,g})} \f$
 */
void CPUSolver::computeKeff() {

  int tid;
  Material* material;
  FP_PRECISION* sigma;
  FP_PRECISION volume;

  FP_PRECISION total = 0.0;
  FP_PRECISION fission = 0.0;
  FP_PRECISION scatter = 0.0;

  FP_PRECISION* FSR_rates = new FP_PRECISION[_num_FSRs];
  FP_PRECISION* group_rates = new FP_PRECISION[_num_threads * _num_groups];

  /* Loop over all FSRs and compute the volume-weighted total rates */
  #pragma omp parallel for private(tid, volume, \
    material, sigma) schedule(guided)
  for (int r=0; r < _num_FSRs; r++) {

    tid = omp_get_thread_num() * _num_groups;
    volume = _FSR_volumes[r];
    material = _FSR_materials[r];
    sigma = material->getSigmaT();

    for (int e=0; e < _num_groups; e++)
      group_rates[tid+e] = sigma[e] * _scalar_flux(r,e);

    FSR_rates[r]=pairwise_sum<FP_PRECISION>(&group_rates[tid], _num_groups);
    FSR_rates[r] *= volume;
  }

  /* Reduce total rates across FSRs */
  total = pairwise_sum<FP_PRECISION>(FSR_rates, _num_FSRs);

  /* Loop over all FSRs and compute the volume-weighted fission rates */
  #pragma omp parallel for private(tid, volume, \
    material, sigma) schedule(guided)
  for (int r=0; r < _num_FSRs; r++) {

    tid = omp_get_thread_num() * _num_groups;
    volume = _FSR_volumes[r];
    material = _FSR_materials[r];
    sigma = material->getNuSigmaF();

    for (int e=0; e < _num_groups; e++)
      group_rates[tid+e] = sigma[e] * _scalar_flux(r,e);

    FSR_rates[r]=pairwise_sum<FP_PRECISION>(&group_rates[tid], _num_groups);
    FSR_rates[r] *= volume;
  }

  /* Reduce fission rates across FSRs */
  fission = pairwise_sum<FP_PRECISION>(FSR_rates, _num_FSRs);

  /* Loop over all FSRs and compute the volume-weighted scattering rates */
  #pragma omp parallel for private(tid, volume, \
    material) schedule(guided)
  for (int r=0; r < _num_FSRs; r++) {

    tid = omp_get_thread_num() * _num_groups;
    volume = _FSR_volumes[r];
    material = _FSR_materials[r];

    FSR_rates[r] = 0.;

    for (int G=0; G < _num_groups; G++) {
      for (int g=0; g < _num_groups; g++)
        group_rates[tid+g] = material->getSigmaSByGroupInline(g,G)
                             * _scalar_flux(r,g);

      FSR_rates[r]+=pairwise_sum<FP_PRECISION>(&group_rates[tid], _num_groups);
    }

    FSR_rates[r] *= volume;
  }

  /* Reduce scattering rates across FSRs */
  scatter = pairwise_sum<FP_PRECISION>(FSR_rates, _num_FSRs);

  /* Reduce leakage array across Tracks, energy groups, polar angles */
  int size = 2 * _tot_num_tracks * _polar_times_groups;
  _leakage = pairwise_sum<FP_PRECISION>(_boundary_leakage, size) * 0.5;

  _k_eff = fission / (total - scatter + _leakage);

  log_printf(DEBUG, "tot = %f, fiss = %f, scatt = %f, leakage = %f,"
             "k_eff = %f", total, fission, scatter, _leakage, _k_eff);

  delete [] FSR_rates;
  delete [] group_rates;

  return;
}