void build_rr_graph (enum e_route_type route_type, struct s_det_routing_arch
         det_routing_arch, struct s_segment_inf *segment_inf, t_timing_inf 
         timing_inf) {

/* Builds the routing resource graph needed for routing.  Does all the   *
 * necessary allocation and initialization.  If route_type is DETAILED   *
 * then the routing graph built is for detailed routing, otherwise it is *
 * for GLOBAL routing.                                                   */

 int nodes_per_clb, nodes_per_pad, nodes_per_chan;
 int **rr_node_indices;
 int Fc_output, Fc_input, Fc_pad;
 int **pads_to_tracks;
 struct s_ivec **tracks_to_clb_ipin, *tracks_to_pads;

/* [0..pins_per_clb-1][0..3][0..Fc_output-1].  List of tracks this pin *
 * connects to.  Second index is the side number (see pr.h).  If a pin *
 * is not an output or input, respectively, or doesn't connect to      *
 * anything on this side, the [ipin][iside][0] element is OPEN.        */

 int ***clb_opin_to_tracks, ***clb_ipin_to_tracks;
 t_seg_details *seg_details_x, *seg_details_y;  /* [0 .. nodes_per_chan-1] */


 nodes_per_clb = num_class + pins_per_clb;
 nodes_per_pad = 4 * io_rat;    /* SOURCE, SINK, OPIN, and IPIN */

 if (route_type == GLOBAL) {
    nodes_per_chan = 1;
 }
 else {
    nodes_per_chan = chan_width_x[0];
 }

 seg_details_x = alloc_and_load_seg_details (nodes_per_chan, segment_inf, 
                 det_routing_arch.num_segment, nx);

 seg_details_y = alloc_and_load_seg_details (nodes_per_chan, segment_inf, 
                 det_routing_arch.num_segment, ny);

#ifdef DEBUG
 dump_seg_details (seg_details_x, nodes_per_chan, "x.echo");
 dump_seg_details (seg_details_y, nodes_per_chan, "y.echo");
#endif

/* To set up the routing graph I need to choose an order for the rr_indices. *
 * For each (i,j) slot in the FPGA, the index order is [source+sink]/pins/   *
 * chanx/chany. The dummy source and sink are ordered by class number or pad *
 * number; the pins are ordered by pin number or pad number, and the channel *
 * segments are ordered by track number.  Track 1 is closest to the "owning" *
 * block; i.e. it is towards the left of y-chans and the bottom of x-chans.  *
 *                                                                           *
 * The maximize cache effectiveness, I put all the rr_nodes associated with  *
 * a block together (this includes the "owned" channel segments).  I start   *
 * at (0,0) (empty), go to (1,0), (2,0) ... (0,1) and so on.                 */

/* NB:  Allocates data structures for fast index computations -- more than *
 * just rr_node_indices are allocated by this routine.                     */

 rr_node_indices = alloc_and_load_rr_node_indices (nodes_per_clb, 
         nodes_per_pad, nodes_per_chan, seg_details_x, seg_details_y);

 num_rr_nodes = rr_node_indices[nx+1][ny+1];

 if (det_routing_arch.Fc_type == ABSOLUTE) {
    Fc_output = min (det_routing_arch.Fc_output, nodes_per_chan);
    Fc_input = min (det_routing_arch.Fc_input, nodes_per_chan);
    Fc_pad = min (det_routing_arch.Fc_pad, nodes_per_chan);
 }
 else {    /* FRACTIONAL */
    Fc_output = nint (nodes_per_chan * det_routing_arch.Fc_output);
    Fc_output = max (1, Fc_output);
    Fc_input = nint (nodes_per_chan * det_routing_arch.Fc_input);
    Fc_input = max (1, Fc_input);
    Fc_pad = nint (nodes_per_chan * det_routing_arch.Fc_pad);
    Fc_pad = max (1, Fc_pad);
 }

 alloc_and_load_switch_block_conn (nodes_per_chan, 
        det_routing_arch.switch_block_type);

 clb_opin_to_tracks = alloc_and_load_clb_pin_to_tracks (DRIVER, nodes_per_chan,
        Fc_output);

 clb_ipin_to_tracks = alloc_and_load_clb_pin_to_tracks (RECEIVER,
        nodes_per_chan, Fc_input);
 
 tracks_to_clb_ipin = alloc_and_load_tracks_to_clb_ipin (nodes_per_chan,
        Fc_input, clb_ipin_to_tracks);

 pads_to_tracks = alloc_and_load_pads_to_tracks (nodes_per_chan, Fc_pad);
 
 tracks_to_pads = alloc_and_load_tracks_to_pads (pads_to_tracks, 
          nodes_per_chan, Fc_pad);

 rr_edge_done = (boolean *) my_calloc (num_rr_nodes, sizeof (boolean));

 alloc_and_load_rr_graph (rr_node_indices, clb_opin_to_tracks,
       tracks_to_clb_ipin, pads_to_tracks, tracks_to_pads, Fc_output,
       Fc_input, Fc_pad, nodes_per_chan, route_type, det_routing_arch, 
       seg_details_x, seg_details_y);

 free (rr_edge_done);
 free_rr_node_indices (rr_node_indices);
 free_matrix3 (clb_opin_to_tracks, 0, pins_per_clb-1, 0, 3, 0, sizeof(int));
 free_matrix3 (clb_ipin_to_tracks, 0, pins_per_clb-1, 0, 3, 0, sizeof(int));
 free_ivec_matrix (tracks_to_clb_ipin, 0, nodes_per_chan-1, 0, 3);
 free_ivec_vector (tracks_to_pads, 0, nodes_per_chan-1);
 free_matrix (pads_to_tracks, 0, io_rat-1, 0, sizeof(int));
 free_switch_block_conn (nodes_per_chan);
 free_edge_list_hard (&free_edge_list_head);

 save_segment_type_and_length_info (seg_details_x, nodes_per_chan,
                                    seg_details_y, nodes_per_chan);

 free_seg_details (seg_details_x, nodes_per_chan);
 free_seg_details (seg_details_y, nodes_per_chan);

 add_rr_graph_C_from_switches (timing_inf.ipin_cblock_C); 

/* dump_rr_graph ("rr_graph.echo"); */
 check_rr_graph (route_type, det_routing_arch.num_switch);
}
Exemplo n.º 2
0
  static int read_ethtool_info(struct ifreq *ifr, int fd, SFLAdaptor *adaptor)
  {
    // Try to get the ethtool info for this interface so we can infer the
    // ifDirection and ifSpeed. Learned from openvswitch (http://www.openvswitch.org).
    int changed = NO;
    struct ethtool_cmd ecmd = { 0 };
    ecmd.cmd = ETHTOOL_GSET;
    ifr->ifr_data = (char *)&ecmd;
    if(ioctl(fd, SIOCETHTOOL, ifr) >= 0) {
      uint32_t direction = ecmd.duplex ? 1 : 2;
      if(direction != adaptor->ifDirection) {
	changed = YES;
      }
      adaptor->ifDirection = direction;
      uint64_t ifSpeed_mb = ecmd.speed;
      // ethtool_cmd_speed(&ecmd) is available in newer systems and uses the
      // speed_hi field too,  but we would need to run autoconf-style
      // tests to see if it was there and we are trying to avoid that.
      if(ifSpeed_mb == (uint16_t)-1 ||
	 ifSpeed_mb == (uint32_t)-1) {
	// unknown
	if(adaptor->ifSpeed != 0) {
	  changed = YES;
	}
	adaptor->ifSpeed = 0;
      }
      else {
	uint64_t ifSpeed_bps = ifSpeed_mb * 1000000;
	if(adaptor->ifSpeed != ifSpeed_bps) {
	  changed = YES;
	}
	adaptor->ifSpeed = ifSpeed_bps;
      }
#if (HSP_ETHTOOL_STATS || HSF_DOCKER)
      // see if the ethtool stats block can give us multicast/broadcast counters too
      HSPAdaptorNIO *adaptorNIO = (HSPAdaptorNIO *)adaptor->userData;
      adaptorNIO->et_nfound=0;
      adaptorNIO->et_nctrs = ethtool_num_counters(ifr, fd);
      if(adaptorNIO->et_nctrs) {
	struct ethtool_gstrings *ctrNames;
	uint32_t bytes = sizeof(*ctrNames) + (adaptorNIO->et_nctrs * ETH_GSTRING_LEN);
	ctrNames = (struct ethtool_gstrings *)my_calloc(bytes);
	ctrNames->cmd = ETHTOOL_GSTRINGS;
	ctrNames->string_set = ETH_SS_STATS;
	ctrNames->len = adaptorNIO->et_nctrs;
	ifr->ifr_data = (char *)ctrNames;
	if(ioctl(fd, SIOCETHTOOL, ifr) >= 0) {
	  // copy out one at a time to make sure we have null-termination
	  char cname[ETH_GSTRING_LEN+1];
	  cname[ETH_GSTRING_LEN] = '\0';
	  for(int ii=0; ii < adaptorNIO->et_nctrs; ii++) {
	    memcpy(cname, &ctrNames->data[ii * ETH_GSTRING_LEN], ETH_GSTRING_LEN);
	    if(debug) myLog(LOG_INFO, "ethtool counter %s is at index %d", cname, ii);
	    // then see if this is one of the ones we want,
	    // and record the index if it is.
#ifdef HSP_ETHTOOL_STATS
	    if(staticStringsIndexOf(HSP_ethtool_mcasts_in_names, cname) != -1) {
	      adaptorNIO->et_idx_mcasts_in = ii+1;
	      adaptorNIO->et_nfound++;
	    }
	    else if(staticStringsIndexOf(HSP_ethtool_mcasts_out_names, cname) != -1) {
	      adaptorNIO->et_idx_mcasts_out = ii+1;
	      adaptorNIO->et_nfound++;
	    }
	    else if(staticStringsIndexOf(HSP_ethtool_bcasts_in_names, cname) != -1) {
	      adaptorNIO->et_idx_bcasts_in = ii+1;
	      adaptorNIO->et_nfound++;
	    }
	    else if(staticStringsIndexOf(HSP_ethtool_bcasts_out_names, cname) != -1) {
	      adaptorNIO->et_idx_bcasts_out = ii+1;
	      adaptorNIO->et_nfound++;
	    }
#endif
#ifdef HSF_DOCKER
	    if(staticStringsIndexOf(HSP_ethtool_peer_ifindex_names, cname) != -1) {
	      // Now go ahead and make the call to get the peer_ifindex.
	      struct ethtool_stats *et_stats = (struct ethtool_stats *)my_calloc(bytes);
	      et_stats->cmd = ETHTOOL_GSTATS;
	      et_stats->n_stats = adaptorNIO->et_nctrs;
	      ifr->ifr_data = (char *)et_stats;
	      if(ioctl(fd, SIOCETHTOOL, ifr) >= 0) {
		adaptorNIO->peer_ifIndex = et_stats->data[ii];
		if(debug) myLog(LOG_INFO, "Interface %s (ifIndex=%u) has peer_ifindex=%u", 
				adaptor->deviceName,
				adaptor->ifIndex,
				adaptorNIO->peer_ifIndex);
	      }
	    }
#endif
	  }
	}
	my_free(ctrNames);
      }
#endif
    }
    return changed;
  }
Exemplo n.º 3
0
UTStringArray *strArrayNew() {
    return (UTStringArray *)my_calloc(sizeof(UTStringArray));
}
Exemplo n.º 4
0
static inline void same_cell_sse_intrinsics(DOUBLE * x0, DOUBLE * y0, DOUBLE * z0, const int64_t N0,
                                            const DOUBLE sqr_rpmax, const DOUBLE sqr_rpmin, const int nbin, const DOUBLE rupp_sqr[] , const DOUBLE pimax
                                            ,const SSE_FLOATS m_rupp_sqr[] 
#ifdef OUTPUT_RPAVG
                                            ,const SSE_FLOATS m_kbin[]
                                            ,DOUBLE src_rpavg[]
#endif                         
                                            ,uint64_t *src_npairs)
{
    uint64_t *npairs = my_calloc(sizeof(*npairs), nbin);
#ifdef OUTPUT_RPAVG
    DOUBLE rpavg[nbin];
    for(int i=0;i<nbin;i++) {
        rpavg[i] = ZERO;
    }
#endif    

    for(int64_t i=0;i<N0;i++) {
        const DOUBLE xpos = *x0++;
        const DOUBLE ypos = *y0++;
        const DOUBLE zpos = *z0++;
        
		DOUBLE *x1 = x0;
		DOUBLE *y1 = y0;
		DOUBLE *z1 = z0;

		int64_t j = i+1;		
		for(;j<=(N0 - SSE_NVEC);j+=SSE_NVEC){

#ifdef OUTPUT_RPAVG
            union int4{
                SSE_INTS m_ibin;
                int ibin[SSE_NVEC];
            };
            union int4 union_rpbin;
            
            union float4{
                SSE_FLOATS m_Dperp;
                DOUBLE Dperp[SSE_NVEC];
            };
            union float4 union_mDperp;
#endif
            const SSE_FLOATS m_xpos = SSE_SET_FLOAT(xpos);
            const SSE_FLOATS m_ypos = SSE_SET_FLOAT(ypos);
            const SSE_FLOATS m_zpos = SSE_SET_FLOAT(zpos);

            const SSE_FLOATS m_x1 = SSE_LOAD_FLOATS_UNALIGNED(x1);
			const SSE_FLOATS m_y1 = SSE_LOAD_FLOATS_UNALIGNED(y1);
			const SSE_FLOATS m_z1 = SSE_LOAD_FLOATS_UNALIGNED(z1);

			x1 += SSE_NVEC;
			y1 += SSE_NVEC;
			z1 += SSE_NVEC;

            const SSE_FLOATS m_pimax = SSE_SET_FLOAT(pimax);
            /* const SSE_FLOATS m_zero  = SSE_SET_FLOAT(ZERO); */
            
            //set constant := sqr_rpmax
			const SSE_FLOATS m_sqr_rpmax = SSE_SET_FLOAT(sqr_rpmax);
			//set constant := sqr_rpmin
			const SSE_FLOATS m_sqr_rpmin = SSE_SET_FLOAT(sqr_rpmin);
			

			const SSE_FLOATS m_sqr_xdiff = SSE_SQUARE_FLOAT(SSE_SUBTRACT_FLOATS(m_x1, m_xpos));
            const SSE_FLOATS m_sqr_ydiff = SSE_SQUARE_FLOAT(SSE_SUBTRACT_FLOATS(m_y1, m_ypos));
            const SSE_FLOATS m_zdiff = SSE_SUBTRACT_FLOATS(m_z1, m_zpos);
            
            SSE_FLOATS r2  = SSE_ADD_FLOATS(m_sqr_xdiff,m_sqr_ydiff);
            SSE_FLOATS m_mask_left;
			{
                const SSE_FLOATS m_pimax_mask = SSE_COMPARE_FLOATS_LT(m_zdiff,m_pimax);
                if(SSE_TEST_COMPARISON(m_pimax_mask) == 0) {
                    j = N0;
                    break;
                }
                
                const SSE_FLOATS m_rpmin_mask = SSE_COMPARE_FLOATS_GE(r2, m_sqr_rpmin);
                const SSE_FLOATS m_rpmax_mask = SSE_COMPARE_FLOATS_LT(r2,m_sqr_rpmax);
                const SSE_FLOATS m_rp_mask = SSE_BITWISE_AND(m_rpmin_mask, m_rpmax_mask);
                m_mask_left = SSE_BITWISE_AND(m_pimax_mask, m_rp_mask);
				if(SSE_TEST_COMPARISON(m_mask_left) == 0) {
					continue;
				}
				r2 = SSE_BLEND_FLOATS_WITH_MASK(m_sqr_rpmax, r2, m_mask_left);
            }
                
#ifdef OUTPUT_RPAVG
            union_mDperp.m_Dperp = SSE_SQRT_FLOAT(r2);
            SSE_FLOATS m_rpbin = SSE_SET_FLOAT(ZERO);
#endif

			for(int kbin=nbin-1;kbin>=1;kbin--) {
				SSE_FLOATS m1 = SSE_COMPARE_FLOATS_GE(r2,m_rupp_sqr[kbin-1]);
				SSE_FLOATS m_bin_mask = SSE_BITWISE_AND(m1,m_mask_left);
				m_mask_left = SSE_COMPARE_FLOATS_LT(r2,m_rupp_sqr[kbin-1]);
				int test2  = SSE_TEST_COMPARISON(m_bin_mask);
				npairs[kbin] += SSE_BIT_COUNT_INT(test2);
#ifdef OUTPUT_RPAVG
                m_rpbin = SSE_BLEND_FLOATS_WITH_MASK(m_rpbin,m_kbin[kbin], m_bin_mask);
#endif
				int test3 = SSE_TEST_COMPARISON(m_mask_left);
				if(test3 == 0) {
					break;
				}
			}

#ifdef OUTPUT_RPAVG
            union_rpbin.m_ibin = SSE_TRUNCATE_FLOAT_TO_INT(m_rpbin);
            //protect the unroll pragma in case compiler is not icc.
#if  __INTEL_COMPILER
#pragma unroll(NVEC)
#endif
            for(int jj=0;jj<NVEC;jj++) {
                const int kbin = union_rpbin.ibin[jj];
                const DOUBLE r = union_mDperp.Dperp[jj];
                rpavg[kbin] += r;
            }
#endif//OUTPUT_RPAVG
            
		}			

		for(;j<N0;j++) {
			const DOUBLE dx = *x1++ - xpos;
			const DOUBLE dy = *y1++ - ypos;
			const DOUBLE dz = *z1++ - zpos;
            if(dz >= pimax) break;
            
			const DOUBLE r2 = dx*dx + dy*dy;
			if(r2 >= sqr_rpmax || r2 < sqr_rpmin) continue;
#ifdef OUTPUT_RPAVG
            const DOUBLE r = SQRT(r2);
#endif            
			for(int kbin=nbin-1;kbin>=1;kbin--){
				if(r2 >= rupp_sqr[kbin-1]) {
					npairs[kbin]++;
#ifdef OUTPUT_RPAVG
                    rpavg[kbin] += r;
#endif                    
					break;
				}
			}//searching for kbin loop
		}
    }

	for(int i=0;i<nbin;i++) {
		src_npairs[i] += npairs[i];
#ifdef OUTPUT_RPAVG
        src_rpavg[i] += rpavg[i];
#endif        
        
	}
	free(npairs);
}
Exemplo n.º 5
0
void
check_route(enum e_route_type route_type,
	    int num_switch,
	    t_ivec ** fb_opins_used_locally)
{

/* This routine checks that a routing:  (1) Describes a properly         *
 * connected path for each net, (2) this path connects all the           *
 * pins spanned by that net, and (3) that no routing resources are       *
 * oversubscribed (the occupancy of everything is recomputed from        *
 * scratch).                                                             */

    int inet, ipin, max_pins, inode, prev_node;
    boolean valid, connects;
    boolean *connected_to_route;	/* [0 .. num_rr_nodes-1] */
    struct s_trace *tptr;
    boolean *pin_done;

    printf("\nChecking to ensure routing is legal ...\n");

/* Recompute the occupancy from scratch and check for overuse of routing *
 * resources.  This was already checked in order to determine that this  *
 * is a successful routing, but I want to double check it here.          */

    recompute_occupancy_from_scratch(fb_opins_used_locally);
    valid = feasible_routing();
    if(valid == FALSE)
	{
	    printf
		("Error in check_route -- routing resources are overused.\n");
	    exit(1);
	}

    check_locally_used_fb_opins(fb_opins_used_locally, route_type);

    connected_to_route = (boolean *) my_calloc(num_rr_nodes, sizeof(boolean));

    max_pins = 0;
    for(inet = 0; inet < num_nets; inet++)
	max_pins = max(max_pins, (net[inet].num_sinks + 1));

    pin_done = (boolean *) my_malloc(max_pins * sizeof(boolean));

/* Now check that all nets are indeed connected. */

    for(inet = 0; inet < num_nets; inet++)
	{

	    if(net[inet].is_global)	/* Skip global nets. */
		continue;

	    for(ipin = 0; ipin < (net[inet].num_sinks + 1); ipin++)
		pin_done[ipin] = FALSE;

/* Check the SOURCE of the net. */

	    tptr = trace_head[inet];
	    if(tptr == NULL)
		{
		    printf("Error in check_route:  net %d has no routing.\n",
			   inet);
		    exit(1);
		}

	    inode = tptr->index;
	    check_node_and_range(inode, route_type);
	    check_switch(tptr, num_switch);
	    connected_to_route[inode] = TRUE;	/* Mark as in path. */

	    check_source(inode, inet);
	    pin_done[0] = TRUE;

	    prev_node = inode;
	    tptr = tptr->next;

/* Check the rest of the net */

	    while(tptr != NULL)
		{
		    inode = tptr->index;
		    check_node_and_range(inode, route_type);
		    check_switch(tptr, num_switch);

		    if(rr_node[prev_node].type == SINK)
			{
			    if(connected_to_route[inode] == FALSE)
				{
				    printf
					("Error in check_route.  Node %d does not link "
					 "into the existing routing for net %d.\n",
					 inode, inet);
				    exit(1);
				}
			}

		    else
			{
			    connects = check_adjacent(prev_node, inode);
			    if(!connects)
				{
				    printf
					("Error in check_route while checking net %d.\n",
					 inet);
				    printf
					("Non-adjacent segments in traceback.\n");
				    exit(1);
				}

			    if(connected_to_route[inode]
			       && rr_node[inode].type != SINK)
				{

				    /* Note:  Can get multiple connections to the same logically-equivalent     *
				     * SINK in some logic blocks.                                               */

				    printf
					("Error in check_route:  net %d routing is not a tree.\n",
					 inet);
				    exit(1);
				}

			    connected_to_route[inode] = TRUE;	/* Mark as in path. */

			    if(rr_node[inode].type == SINK)
				check_sink(inode, inet, pin_done);

			}	/* End of prev_node type != SINK */
		    prev_node = inode;
		    tptr = tptr->next;
		}		/* End while */

	    if(rr_node[prev_node].type != SINK)
		{
		    printf("Error in check_route.  Net %d does not end\n",
			   inet);
		    printf("with a SINK.\n");
		    exit(1);
		}

	    for(ipin = 0; ipin < (net[inet].num_sinks + 1); ipin++)
		{
		    if(pin_done[ipin] == FALSE)
			{
			    printf
				("Error in check_route.  Net %d does not \n",
				 inet);
			    printf("connect to pin %d.\n", ipin);
			    exit(1);
			}
		}

	    reset_flags(inet, connected_to_route);

	}			/* End for each net */

    free(pin_done);
    free(connected_to_route);
    printf("Completed routing consistency check successfully.\n\n");
}
Exemplo n.º 6
0
int readInterfaces(HSP *sp)
{
  if(sp->adaptorList == NULL) sp->adaptorList = adaptorListNew();
  else adaptorListMarkAll(sp->adaptorList);

  // Walk the interfaces and collect the non-loopback interfaces so that we
  // have a list of MAC addresses for each interface (usually only 1).
  //
  // May need to come back and run a variation of this where we supply
  // a domain and collect the virtual interfaces for that domain in a
  // similar way.  It looks like we do that by just parsing the numbers
  // out of the interface name.
  
  int fd = socket (PF_INET, SOCK_DGRAM, 0);
  if (fd < 0) {
    fprintf (stderr, "error opening socket: %d (%s)\n", errno, strerror(errno));
    return 0;
  }

// just need to get the device names a different way...
int nddsize = getkerninfo(KINFO_NDD,NULL,0,0);
if(nddsize <= 0) {
close(fd);
return 0;
}
struct kinfo_ndd *ndd = my_calloc(nddsize);
if(getkerninfo(KINFO_NDD, (char *)ndd, &nddsize, 0) < 0) {
 my_free(ndd);
close(fd);
return  0;
}
int count = nddsize / sizeof(struct kinfo_ndd);
for(int i=0; i < count; i++) {
  if((ndd[i].ndd_type == NDD_ETHER ||
      ndd[i].ndd_type == NDD_ISO88023) &&
     ndd[i].ndd_addrlen == 6) {


//  FILE *procFile = fopen("/proc/net/dev", "r");
//   if(procFile) {
    struct ifreq ifr;
    memset(&ifr, 0, sizeof(ifr));
//    char line[MAX_PROC_LINE_CHARS];
//    while(fgets(line, MAX_PROC_LINE_CHARS, procFile)) {
//      if(debug) myLog(LOG_INFO, "/proc/net/dev line: %s", line);
      // the device name is always the token before the ":"
      char *devName = ndd[i].ndd_alias; // strtok(line, ":");
      if(devName) {
	// devName = trimWhitespace(devName);
	if(devName && strlen(devName) < IFNAMSIZ) {
	  // we set the ifr_name field to make our queries
	  strcpy(ifr.ifr_name, devName);

	  if(debug > 1) {
	    myLog(LOG_INFO, "reading interface %s", devName);
	  }

	  // Get the flags for this interface
	  if(ioctl(fd,SIOCGIFFLAGS, &ifr) != 0) {
	    myLog(LOG_ERR, "device %s Get SIOCGIFFLAGS failed : %s",
		  devName,
		  strerror(errno));
	  }
	  else {
	    int up = (ifr.ifr_flags & IFF_UP) ? YES : NO;
	    int loopback = (ifr.ifr_flags & IFF_LOOPBACK) ? YES : NO;
	    int promisc =  (ifr.ifr_flags & IFF_PROMISC) ? YES : NO;
	    int bond_master = NO; // (ifr.ifr_flags & IFF_MASTER) ? YES : NO;
	    //int hasBroadcast = (ifr.ifr_flags & IFF_BROADCAST);
	    //int pointToPoint = (ifr.ifr_flags & IFF_POINTOPOINT);

	    // used to igore loopback interfaces here, but now those
	    // are filtered at the point where we roll together the
	    // counters.
	    if(up) {
	       // Get the MAC Address for this interface

	      
#if 0
	      if(ioctl(fd,SIOCGIFHWADDR, &ifr) != 0) {
		myLog(LOG_ERR, "device %s Get SIOCGIFHWADDR failed : %s",
		      devName,
		      strerror(errno));
	      }

	      // for now just assume that each interface has only one MAC.  It's not clear how we can
	      // learn multiple MACs this way anyhow.  It seems like there is just one per ifr record.
	      // find or create a new "adaptor" entry
#endif
	      SFLAdaptor *adaptor = adaptorListAdd(sp->adaptorList, devName, (u_char *)ndd[i].ndd_addr, sizeof(HSPAdaptorNIO));


	      // clear the mark so we don't free it below
	      adaptor->marked = NO;

	      // this flag might belong in the adaptorNIO struct
	      adaptor->promiscuous = promisc;

	      // remember some useful flags in the userData structure
	      HSPAdaptorNIO *adaptorNIO = (HSPAdaptorNIO *)adaptor->userData;
	      adaptorNIO->loopback = loopback;
	      adaptorNIO->bond_master = bond_master;
	      adaptorNIO->vlan = HSP_VLAN_ALL; // may be modified below

	      // Try and get the ifIndex for this interface
	      if((adaptor->ifIndex = if_nametoindex(devName) ) == 0/*ioctl(fd,SIOCGIFINDEX, &ifr) != 0*/) {
		// only complain about this if we are debugging
		if(debug) {
		  myLog(LOG_ERR, "device %s Get SIOCGIFINDEX failed : %s",
			devName,
			strerror(errno));
		}
	      }
	      else {
		// adaptor->ifIndex = ifr.ifr_ifindex;
	      }
	      
	      // Try to get the IP address for this interface
	      if(ioctl(fd,SIOCGIFADDR, &ifr) != 0) {
		// only complain about this if we are debugging
		if(debug) {
		  myLog(LOG_ERR, "device %s Get SIOCGIFADDR failed : %s",
			devName,
			strerror(errno));
		}
	      }
	      else {
		if (ifr.ifr_addr.sa_family == AF_INET) {
		  struct sockaddr_in *s = (struct sockaddr_in *)&ifr.ifr_addr;
		  // IP addr is now s->sin_addr
		  adaptorNIO->ipAddr.type = SFLADDRESSTYPE_IP_V4;
		  adaptorNIO->ipAddr.address.ip_v4.addr = s->sin_addr.s_addr;
		}
		//else if (ifr.ifr_addr.sa_family == AF_INET6) {
		// not sure this ever happens - on a linux system IPv6 addresses
		// are picked up from /proc/net/if_inet6
		// struct sockaddr_in6 *s = (struct sockaddr_in6 *)&ifr.ifr_addr;
		// IP6 addr is now s->sin6_addr;
		//}
	      }
	      
#if 0
	      // Try to get the ethtool info for this interface so we can infer the
	      // ifDirection and ifSpeed. Learned from openvswitch (http://www.openvswitch.org).
	      struct ethtool_cmd ecmd = { 0 };
	      ecmd.cmd = ETHTOOL_GSET;
	      ifr.ifr_data = (char *)&ecmd;
	      if(ioctl(fd, SIOCETHTOOL, &ifr) == 0) {
		adaptor->ifDirection = ecmd.duplex ? 1 : 2;
		uint64_t ifSpeed_mb = ecmd.speed;
		// ethtool_cmd_speed(&ecmd) is available in newer systems and uses the
		// speed_hi field too,  but we would need to run autoconf-style
		// tests to see if it was there and we are trying to avoid that.
		if(ifSpeed_mb == (uint16_t)-1 ||
		   ifSpeed_mb == (uint32_t)-1) {
		  // unknown
		  adaptor->ifSpeed = 0;
		}
		else {
		  adaptor->ifSpeed = ifSpeed_mb * 1000000;
		}
	      }
#endif
	    }
	  }
	}
      }
    }
    //fclose(procFile);
  }
  
my_free(ndd);
ndd = NULL;
  close (fd);

  // now remove and free any that are still marked
  adaptorListFreeMarked(sp->adaptorList);

  // check in case any of the survivors are specific
  // to a particular VLAN
  readVLANs(sp);

  // now that we have the evidence gathered together, we can
  // set the L3 address priorities (used for auto-selecting
  // the sFlow-agent-address if requrired to by the config.
  setAddressPriorities(sp);

  // now we can read IPv6 addresses too - they come from a
  // different place. Depending on the address priorities this
  // may cause the adaptor's best-choice ipAddress to be
  // overwritten.
  readIPv6Addresses(sp);

  return sp->adaptorList->num_adaptors;
}
Exemplo n.º 7
0
 static void *agentCB_alloc(void *magic, SFLAgent *agent, size_t bytes)
 {
   return my_calloc(bytes);
 }
Exemplo n.º 8
0
/*!*****************************************************************************
 *******************************************************************************
\note  compute_kinematics
\date  June 99
   
\remarks 

       computes kinematic variables

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

    none

 ******************************************************************************/
static void
compute_kinematics(void)
{
  int i,j,r,o;
  static int firsttime = TRUE;
  static SL_DJstate *temp;
  static Matrix last_J;
  static Matrix last_Jbase;
  
  if (firsttime) {
    temp=(SL_DJstate *)my_calloc((unsigned long)(n_dofs+1),sizeof(SL_DJstate),MY_STOP);
    last_J      = my_matrix(1,6*n_endeffs,1,n_dofs);
    last_Jbase  = my_matrix(1,6*n_endeffs,1,2*N_CART);
  }

  /* compute the desired link positions */
  linkInformationDes(joint_des_state,&base_state,&base_orient,endeff,
		     joint_cog_mpos_des,joint_axis_pos_des,joint_origin_pos_des,
		     link_pos_des,Alink_des,Adof_des);

  /* the desired endeffector information */
  for (i=1; i<=N_CART; ++i) {
    for (j=1; j<=n_endeffs; ++j) {
      cart_des_state[j].x[i] = link_pos_des[link2endeffmap[j]][i];
    }
  }

  /* the desired quaternian of the endeffector */
  for (j=1; j<=n_endeffs; ++j) {
    linkQuat(Alink_des[link2endeffmap[j]],&(cart_des_orient[j]));
  }


  /* addititional link information */
  linkInformation(joint_state,&base_state,&base_orient,endeff,
		  joint_cog_mpos,joint_axis_pos,joint_origin_pos,
		  link_pos,Alink,Adof);

  /* create the endeffector information */
  for (i=1; i<=N_CART; ++i) {
    for (j=1; j<=n_endeffs; ++j) {
      cart_state[j].x[i] = link_pos[link2endeffmap[j]][i];
    }
  }

  /* the quaternian of the endeffector */
  for (j=1; j<=n_endeffs; ++j) {
    linkQuat(Alink[link2endeffmap[j]],&(cart_orient[j]));
  }

  /* the COG position */
  compute_cog();

  /* the jacobian */
  jacobian(link_pos,joint_origin_pos,joint_axis_pos,J);
  baseJacobian(link_pos,joint_origin_pos,joint_axis_pos,Jbase);

  jacobian(link_pos_des,joint_origin_pos_des,joint_axis_pos_des,Jdes);
  baseJacobian(link_pos_des,joint_origin_pos_des,joint_axis_pos_des,Jbasedes);

  /* numerical time derivative of Jacobian */
  if (!firsttime) {
    mat_sub(J,last_J,dJdt);
    mat_mult_scalar(dJdt,(double)ros_servo_rate,dJdt);
    mat_sub(Jbase,last_Jbase,dJbasedt);
    mat_mult_scalar(dJbasedt,(double)ros_servo_rate,dJbasedt);
  }
  mat_equal(J,last_J);
  mat_equal(Jbase,last_Jbase);

  /* compute the cartesian velocities and accelerations */

  for (j=1; j<=n_endeffs; ++j) {

    for (i=1; i<=N_CART; ++i) {

      cart_state[j].xd[i]     = 0.0;
      cart_state[j].xdd[i]    = 0.0;

      cart_orient[j].ad[i]     = 0.0;
      cart_orient[j].add[i]    = 0.0;

      cart_des_state[j].xd[i] = 0.0;
      cart_des_orient[j].ad[i] = 0.0;

      /* contributations from the joints */
      for (r=1; r<=n_dofs; ++r) {
	cart_state[j].xd[i]     += J[(j-1)*6+i][r] * joint_state[r].thd;
	cart_orient[j].ad[i]    += J[(j-1)*6+i+3][r] * joint_state[r].thd;

	cart_des_state[j].xd[i] += Jdes[(j-1)*6+i][r] *joint_des_state[r].thd;
	cart_des_orient[j].ad[i]+= Jdes[(j-1)*6+i+3][r] * joint_des_state[r].thd;

	cart_state[j].xdd[i]    += J[(j-1)*6+i][r] * joint_state[r].thdd + 
	  dJdt[(j-1)*6+i][r] * joint_state[r].thd;
	cart_orient[j].add[i]   += J[(j-1)*6+i+3][r] * joint_state[r].thdd + 
	  dJdt[(j-1)*6+i+3][r] * joint_state[r].thd;
      }

      /* contributations from the base */
      for (r=1; r<=N_CART; ++r) {
	cart_state[j].xd[i]     += Jbase[(j-1)*6+i][r] * base_state.xd[r];
	cart_orient[j].ad[i]    += Jbase[(j-1)*6+i+3][r] * base_state.xd[r];

	cart_state[j].xd[i]     += Jbase[(j-1)*6+i][3+r] * base_orient.ad[r];
	cart_orient[j].ad[i]    += Jbase[(j-1)*6+i+3][3+r] * base_orient.ad[r];

	cart_des_state[j].xd[i]     += Jbasedes[(j-1)*6+i][r] * base_state.xd[r];
	cart_des_orient[j].ad[i]    += Jbasedes[(j-1)*6+i+3][r] * base_state.xd[r];

	cart_des_state[j].xd[i]     += Jbasedes[(j-1)*6+i][3+r] * base_orient.ad[r];
	cart_des_orient[j].ad[i]    += Jbasedes[(j-1)*6+i+3][3+r] * base_orient.ad[r];

	cart_state[j].xdd[i]    += Jbase[(j-1)*6+i][r] * base_state.xdd[r] + 
	  dJbasedt[(j-1)*6+i][r] * base_state.xd[r];
	cart_orient[j].add[i]   += Jbase[(j-1)*6+i+3][r] * base_state.xdd[r] + 
	  dJbasedt[(j-1)*6+i+3][r] * base_state.xd[r];

	cart_state[j].xdd[i]    += Jbase[(j-1)*6+i][3+r] * base_orient.add[r] + 
	  dJbasedt[(j-1)*6+i][3+r] * base_orient.ad[r];
	cart_orient[j].add[i]   += Jbase[(j-1)*6+i+3][3+r] * base_orient.add[r] + 
	  dJbasedt[(j-1)*6+i+3][3+r] * base_orient.ad[r];
      }

    }

    /* compute quaternion derivatives */
    quatDerivatives(&(cart_orient[j]));
    quatDerivatives(&(cart_des_orient[j]));
    for (r=1; r<=N_QUAT; ++r)
      cart_des_orient[j].qdd[r] = 0.0; // we don't have dJdes_dt so far

  }

  /* reset first time flag */
  firsttime = FALSE;

}
Exemplo n.º 9
0
void count_routing_transistors (int num_switch, float R_minW_nmos,
                                float R_minW_pmos) {

    /* Counts how many transistors are needed to implement the FPGA routing      *
     * resources.  Call this only when an rr_graph exists.  It does not count    *
     * the transistors used in logic blocks, but it counts the transistors in    *
     * the input connection block multiplexers and in the output pin drivers and *
     * pass transistors.  NB:  this routine assumes pass transistors always      *
     * generate two edges (one forward, one backward) between two nodes.         *
     * Physically, this is what happens -- make sure your rr_graph does it.      *
     *                                                                           *
     * I assume a minimum width transistor takes 1 unit of area.  A double-width *
     * transistor takes the twice the diffusion width, but the same spacing, so  *
     * I assume it takes 1.5x the area of a minimum-width transitor.  I always   *
     * design tri-state buffers as a buffer followed by a pass transistor.       *
     * I make Rbuffer = Rpass_transitor = 1/2 Rtri-state_buffer.                 *
     * I make the pull-up and pull-down sides of the buffer the same strength -- *
     * i.e. I make the p transistor R_minW_pmos / R_minW_nmos wider than the n   *
     * transistor.                                                               *
     *                                                                           *
     * I generate two area numbers in this routine:  ntrans_sharing and          *
     * ntrans_no_sharing.  ntrans_sharing exactly reflects what the timing       *
     * analyzer, etc. works with -- each switch is a completely self contained   *
     * pass transistor or tri-state buffer.  In the case of tri-state buffers    *
     * this is rather pessimisitic.  The inverter chain part of the buffer (as   *
     * opposed to the pass transistor + SRAM output part) can be shared by       *
     * several switches in the same location.  Obviously all the switches from   *
     * an OPIN can share one buffer.  Also, CHANX and CHANY switches at the same *
     * spot (i,j) on a single segment can share a buffer.  For a more realistic  *
     * area number I assume all buffered switches from a node that are at the    *
     * *same (i,j) location* can share one buffer.  Only the lowest resistance   *
     * (largest) buffer is implemented.  In practice, you might want to build    *
     * something that is 1.5x or 2x the largest buffer, so this may be a bit     *
     * optimistic (but I still think it's pretty reasonable).                    */


    int *num_inputs_to_cblock;  /* [0..num_rr_nodes-1], but all entries not    */
    /* corresponding to IPINs will be 0.           */

    boolean *cblock_counted;          /* [0..max(nx,ny)] -- 0th element unused. */
    float *shared_buffer_trans;       /* [0..max_nx,ny)] */
    float *unsharable_switch_trans, *sharable_switch_trans; /* [0..num_switch-1] */

    t_rr_type from_rr_type, to_rr_type;
    int from_node, to_node, iedge, num_edges, maxlen;
    int iswitch, i, j, iseg, max_inputs_to_cblock;
    float input_cblock_trans, shared_opin_buffer_trans;
    const float trans_sram_bit = 6.;

    /* Two variables below are the accumulator variables that add up all the    *
     * transistors in the routing.  Make doubles so that they don't stop        *
     * incrementing once adding a switch makes a change of less than 1 part in  *
     * 10^7 to the total.  If this still isn't good enough (adding 1 part in    *
     * 10^15 will still be thrown away), compute the transistor count in        *
     * "chunks", by adding up inodes 1 to 1000, 1001 to 2000 and then summing   *
     * the partial sums together.                                               */

    double ntrans_sharing, ntrans_no_sharing;


    /* Buffers from the routing to the ipin cblock inputs, and from the ipin    *
     * cblock outputs to the logic block, respectively.  Assume minimum size n  *
     * transistors, and ptransistors sized to make the pull-up R = pull-down R. */

    float trans_track_to_cblock_buf;
    float trans_cblock_to_lblock_buf;


    ntrans_sharing = 0.;
    ntrans_no_sharing = 0.;
    max_inputs_to_cblock = 0;

    /* Assume the two buffers below are 4x minimum drive strength (enough to *
     * drive a fanout of up to 16 pretty nicely -- should cover a reasonable *
     * wiring C plus the fanout.                                             */

    trans_track_to_cblock_buf = trans_per_buf (R_minW_nmos/4., R_minW_nmos,
                                R_minW_pmos);

    trans_cblock_to_lblock_buf = trans_per_buf (R_minW_nmos/4., R_minW_nmos,
                                 R_minW_pmos);

    /* trans_track_to_cblock_buf = 1. + trans_per_R (R_minW_nmos, R_minW_pmos);
     trans_cblock_to_lblock_buf = 1. + trans_per_R (R_minW_nmos, R_minW_pmos); */

    num_inputs_to_cblock = (int *) my_calloc (num_rr_nodes, sizeof (int));

    maxlen = max (nx, ny) + 1;
    cblock_counted = (boolean *) my_calloc (maxlen, sizeof (boolean));
    shared_buffer_trans = (float *) my_calloc (maxlen, sizeof (float));

    unsharable_switch_trans = alloc_and_load_unsharable_switch_trans (num_switch,
                              trans_sram_bit, R_minW_nmos);

    sharable_switch_trans = alloc_and_load_sharable_switch_trans (num_switch,
                            trans_sram_bit, R_minW_nmos, R_minW_pmos);

    for (from_node=0; from_node<num_rr_nodes; from_node++) {

        from_rr_type = rr_node[from_node].type;

        switch (from_rr_type) {

        case CHANX:
        case CHANY:
            num_edges = rr_node[from_node].num_edges;

            for (iedge=0; iedge<num_edges; iedge++) {

                to_node = rr_node[from_node].edges[iedge];
                to_rr_type = rr_node[to_node].type;

                switch (to_rr_type) {

                case CHANX:
                case CHANY:
                    iswitch = rr_node[from_node].switches[iedge];

                    if (switch_inf[iswitch].buffered) {
                        iseg = seg_index_of_sblock (from_node, to_node);
                        shared_buffer_trans[iseg] = max (shared_buffer_trans[iseg],
                                                         sharable_switch_trans[iswitch]);

                        ntrans_no_sharing += unsharable_switch_trans[iswitch] +
                                             sharable_switch_trans[iswitch];
                        ntrans_sharing += unsharable_switch_trans[iswitch];
                    }
                    else if (from_node < to_node) {

                        /* Pass transistor shared by two edges -- only count once.  *
                         * Also, no part of a pass transistor is sharable.          */

                        ntrans_no_sharing += unsharable_switch_trans[iswitch];
                        ntrans_sharing += unsharable_switch_trans[iswitch];
                    }
                    break;

                case IPIN:
                    num_inputs_to_cblock[to_node]++;
                    max_inputs_to_cblock = max (max_inputs_to_cblock,
                                                num_inputs_to_cblock[to_node]);

                    iseg = seg_index_of_cblock (from_rr_type, to_node);

                    if (cblock_counted[iseg] == FALSE) {
                        cblock_counted[iseg] = TRUE;
                        ntrans_sharing += trans_track_to_cblock_buf;
                        ntrans_no_sharing += trans_track_to_cblock_buf;
                    }
                    break;

                default:
                    printf ("Error in count_routing_transistors:  Unexpected \n"
                            "connection from node %d (type %d) to node %d (type %d).\n",
                            from_node, from_rr_type, to_node, to_rr_type);
                    exit (1);
                    break;

                }   /* End switch on to_rr_type. */

            }   /* End for each edge. */

            /* Now add in the shared buffer transistors, and reset some flags. */

            if (from_rr_type == CHANX) {
                for (i=rr_node[from_node].xlow-1; i<=rr_node[from_node].xhigh; i++) {
                    ntrans_sharing += shared_buffer_trans[i];
                    shared_buffer_trans[i] = 0.;
                }

                for (i=rr_node[from_node].xlow; i<=rr_node[from_node].xhigh; i++)
                    cblock_counted[i] = FALSE;

            }
            else {  /* CHANY */
                for (j=rr_node[from_node].ylow-1; j<=rr_node[from_node].yhigh; j++) {
                    ntrans_sharing += shared_buffer_trans[j];
                    shared_buffer_trans[j] = 0.;
                }

                for (j=rr_node[from_node].ylow; j<=rr_node[from_node].yhigh; j++)
                    cblock_counted[j] = FALSE;

            }
            break;

        case OPIN:
            num_edges = rr_node[from_node].num_edges;
            shared_opin_buffer_trans = 0.;

            for (iedge=0; iedge<num_edges; iedge++) {
                iswitch = rr_node[from_node].switches[iedge];
                ntrans_no_sharing += unsharable_switch_trans[iswitch] +
                                     sharable_switch_trans[iswitch];
                ntrans_sharing += unsharable_switch_trans[iswitch];

                shared_opin_buffer_trans = max (shared_opin_buffer_trans,
                                                sharable_switch_trans[iswitch]);
            }

            ntrans_sharing += shared_opin_buffer_trans;
            break;

        default:
            break;

        }  /* End switch on from_rr_type */
    }  /* End for all nodes */

    free (cblock_counted);
    free (shared_buffer_trans);
    free (unsharable_switch_trans);
    free (sharable_switch_trans);

    /* Now add in the input connection block transistors. */

    input_cblock_trans = get_cblock_trans (num_inputs_to_cblock,
                                           max_inputs_to_cblock, trans_cblock_to_lblock_buf, trans_sram_bit);

    free (num_inputs_to_cblock);

    ntrans_sharing += input_cblock_trans;
    ntrans_no_sharing += input_cblock_trans;

    printf ("\nRouting area (in minimum width transistor areas):\n");
    printf ("Assuming no buffer sharing (pessimistic). Total: %#g  Per clb: "
            "%#g\n", ntrans_no_sharing, ntrans_no_sharing / (float) (nx * ny));
    printf ("Assuming buffer sharing (slightly optimistic). Total: %#g  Per clb: "
            "%#g\n\n", ntrans_sharing, ntrans_sharing / (float) (nx * ny));
}
Exemplo n.º 10
0
void get_sources(ParamCoLoRe *par)
{
  //////
  // Uses the gaussian matter density field to obtain a
  // poisson sampling of point sources (returns an integer array
  // with the number of sources in each cell).
  int ii,nthr;
  lint *np_tot_thr;
#ifdef _HAVE_OMP
  nthr=omp_get_max_threads();
#else //_HAVE_OMP
  nthr=1;
#endif //_HAVE_OMP
  np_tot_thr=my_calloc(nthr,sizeof(lint));

  print_info("*** Getting point sources\n");
  if(NodeThis==0) timer(0);
  print_info("Poisson-sampling\n");
#ifdef _HAVE_OMP
#pragma omp parallel default(none)		\
  shared(par,np_tot_thr,IThread0)
#endif //_HAVE_OMP
  {
    lint iz;
#ifdef _HAVE_OMP
    int ithr=omp_get_thread_num();
#else //_HAVE_OMP
    int ithr=0;
#endif //_HAVE_OMP
    double dx=par->l_box/par->n_grid;
    double cell_vol=dx*dx*dx;
    int ngx=2*(par->n_grid/2+1);
    unsigned int seed_thr=par->seed_rng+IThread0+ithr;
    gsl_rng *rng_thr=init_rng(seed_thr);

#ifdef _HAVE_OMP
#pragma omp for schedule(static)
#endif //_HAVE_OMP
    for(iz=0;iz<par->nz_here;iz++) {
      int iy;
      lint indexz=iz*((lint)(ngx*par->n_grid));
      double z0=(iz+par->iz0_here+0.5)*dx-par->pos_obs[2];
      for(iy=0;iy<par->n_grid;iy++) {
	int ix;
	lint indexy=iy*ngx;
	double y0=(iy+0.5)*dx-par->pos_obs[1];
	for(ix=0;ix<par->n_grid;ix++) {
	  int npp=0;
	  double dz_rsd=0;
	  lint index=ix+indexy+indexz;
	  double x0=(ix+0.5)*dx-par->pos_obs[1];
	  double r=sqrt(x0*x0+y0*y0+z0*z0);
	  double redshift=z_of_r(par,r);
	  double ndens=ndens_of_z(par,redshift);
	  if(ndens>0) {
	    double bias=bias_of_z(par,redshift);
	    double gfb=dgrowth_of_r(par,r)*bias;
	    double lambda=ndens*cell_vol*
	      exp(gfb*(par->grid_dens[index]-0.5*gfb*par->sigma2_gauss));
	    npp=rng_poisson(lambda,rng_thr);
	    dz_rsd=par->grid_rvel[index]*vgrowth_of_r(par,r);
	  }

	  par->grid_rvel[index]=dz_rsd;
	  par->nsources[index]=npp;
	  np_tot_thr[ithr]+=npp;
	}
      }
    }//end omp for

    end_rng(rng_thr);
  }//end omp parallel
  if(NodeThis==0) timer(2);

  par->nsources_this=0;
  for(ii=0;ii<nthr;ii++)
    par->nsources_this+=np_tot_thr[ii];

  par->nsources_total=0;
#ifdef _HAVE_MPI
  MPI_Allreduce(&(par->nsources_this),&(par->nsources_total),1,LINT_MPI,MPI_SUM,MPI_COMM_WORLD);
#else //_HAVE_MPI
  par->nsources_total=par->nsources_this;
#endif //_HAVE_MPI

  print_info("  There will be %ld particles in total\n",(long)(par->nsources_total));
  //#ifdef _DEBUG
  //  printf("Node %d has %ld particles\n",NodeThis,(long)(par->nsources_this));
  //#endif //_DEBUG

  for(ii=nthr-1;ii>0;ii--) {
    int jj;
    lint nh=0;
    for(jj=0;jj<ii;jj++)
      nh+=np_tot_thr[jj];
    np_tot_thr[ii]=nh;
  }
  np_tot_thr[0]=0;
  //np_tot_thr now contains the id of the first particle in the thread

#ifdef _SPREC
  fftwf_free(par->grid_dens_f);
#else //_SPREC
  fftw_free(par->grid_dens_f);
#endif //_SPREC
  par->grid_dens_f=NULL;
  par->gals=my_malloc(par->nsources_this*sizeof(Gal));

  if(NodeThis==0) timer(0);
  print_info("Assigning coordinates\n");
#ifdef _HAVE_OMP
#pragma omp parallel default(none)		\
  shared(par,IThread0,np_tot_thr)
#endif //_HAVE_OMP
  {
    lint iz;
#ifdef _HAVE_OMP
    int ithr=omp_get_thread_num();
#else //_HAVE_OMP
    int ithr=0;
#endif //_HAVE_OMP
    double dx=par->l_box/par->n_grid;
    int ngx=2*(par->n_grid/2+1);
    unsigned int seed_thr=par->seed_rng+IThread0+ithr;
    gsl_rng *rng_thr=init_rng(seed_thr);

#ifdef _HAVE_OMP
#pragma omp for schedule(static)
#endif //_HAVE_OMP
    for(iz=0;iz<par->nz_here;iz++) {
      int iy;
      lint indexz=iz*((lint)(ngx*par->n_grid));
      double z0=(iz+par->iz0_here)*dx-par->pos_obs[2];
      for(iy=0;iy<par->n_grid;iy++) {
	int ix;
	lint indexy=iy*ngx;
	double y0=iy*dx-par->pos_obs[1];
	for(ix=0;ix<par->n_grid;ix++) {
	  double x0=ix*dx-par->pos_obs[1];
	  lint index=ix+indexy+indexz;
	  int npp=par->nsources[index];
	  if(npp>0) {
	    int ip;
	    double dz_rsd=par->grid_rvel[index];
	    for(ip=0;ip<npp;ip++) {
	      double cth,phi,r;
	      lint pid=np_tot_thr[ithr];
	      double x=x0+dx*rng_01(rng_thr);
	      double y=y0+dx*rng_01(rng_thr);
	      double z=z0+dx*rng_01(rng_thr);
	      cart2sph(x,y,z,&r,&cth,&phi);
	      par->gals[pid].ra=RTOD*phi;
	      par->gals[pid].dec=90-RTOD*acos(cth);
	      par->gals[pid].z0=z_of_r(par,r);
	      par->gals[pid].dz_rsd=dz_rsd;
	      np_tot_thr[ithr]++;
	    }
	  }
	}
      }
    }//end omp for
    end_rng(rng_thr);
  }//end omp parallel
  if(NodeThis==0) timer(2);

  free(np_tot_thr);
  print_info("\n");
}
Exemplo n.º 11
0
/*!*****************************************************************************
 *******************************************************************************
\note  init_sensor_processing
\date  May 2000
   
\remarks 

          Initializes all sensory processing

 *******************************************************************************
 Function Parameters: [in]=input,[out]=output

     none

 ******************************************************************************/
int
init_sensor_processing(void)

{
  
  int i,j;
  FILE      *in;
  char       string[100];
  static int firsttime = TRUE;

  if (firsttime) {
    firsttime = FALSE;
    joint_lin_rot     = my_matrix(1,n_dofs,1,6);
    pos_polar         = my_vector(1,n_dofs);
    load_polar        = my_vector(1,n_dofs);
    joint_raw_state   = (SL_Jstate *) 
      my_calloc((unsigned long)(n_dofs+1),sizeof(SL_Jstate),MY_STOP);
    misc_raw_sensor   = (double *) 
      my_calloc((unsigned long)(n_misc_sensors+1),sizeof(double),MY_STOP);
    fth = (Filter *)
      my_calloc((unsigned long)(n_dofs+1),sizeof(Filter),MY_STOP);
    fthd = (Filter *)
      my_calloc((unsigned long)(n_dofs+1),sizeof(Filter),MY_STOP);
    fthdd = (Filter *)
      my_calloc((unsigned long)(n_dofs+1),sizeof(Filter),MY_STOP);
    fload = (Filter *)
      my_calloc((unsigned long)(n_dofs+1),sizeof(Filter),MY_STOP);
    fmisc_sensor = (Filter *)
      my_calloc((unsigned long)(n_misc_sensors+1),sizeof(Filter),MY_STOP);
  }

  /* initalizes translation to and from units */
  if (!init_user_sensor_processing())
    return FALSE;

  /* initialize filtering */
  if (!init_filters())
    return FALSE;

  /* read several variables from files */

  /* first, get the calibration values for dealing with the linear to
     rotary conversion */
  if (!read_sensor_calibration(config_files[SENSORCALIBRATION],
      joint_lin_rot,pos_polar,load_polar))
    return FALSE;

  /* second, get the max, min , and offsets of the position sensors */
  if (!read_sensor_offsets(config_files[SENSOROFFSETS]))
    return FALSE;

  /* third, get the filter cutoff values for all variable */
  if (!read_sensor_filters(config_files[SENSORFILTERS]))
    return FALSE;

  /* add function to man pages */
  addToMan("where_off","sensor readings without offsets",where_off);
  addToMan("where_raw","raw sensor readings",where_raw);
  addToMan("monitor_min_max","records min/max values of sensors",monitor_min_max);

  if (!real_robot_flag)
    addToMan("toggle_filter","toggles sensor filtering on and off",toggle_filter);


  /* make raw variables available for output */

  for (i=1; i<=n_dofs; ++i) {
    sprintf(string,"%s_rth",joint_names[i]);
    addVarToCollect((char *)&(joint_raw_state[i].th),string,"rad", DOUBLE,FALSE);
    sprintf(string,"%s_rthd",joint_names[i]);
    addVarToCollect((char *)&(joint_raw_state[i].thd),string,"rad/s", DOUBLE,FALSE);
    sprintf(string,"%s_rload",joint_names[i]);
    addVarToCollect((char *)&(joint_raw_state[i].load),string,"Nm", DOUBLE,FALSE);
  }

  for (i=1; i<=n_misc_sensors; ++i) {
    sprintf(string,"%s_r",misc_sensor_names[i]);
    addVarToCollect((char *)&(misc_raw_sensor[i]),string,"-", DOUBLE,FALSE);
  }
  

  return TRUE;
  
}
Exemplo n.º 12
0
void jackknife_it(int N_Jackknife, char *Polygon_File, int *Galaxy_Sector_Ids, int *Galaxy_Jackknife_Ids, int Ngal, double *ra, double *dec, double *area_tot,
		  double *x,double *y,double *z)
{

  fprintf(stderr,"jackknife_it> In Jackknife Function\n");
	
  int Nmax=1E6;
  int n_masks;
  int i=0,j=0,k=0;
  char *polygons_tag,*polygon_tag,*single_tag,*caps_tag, *weight_tag, *str_tag,*pixel_tag;	
  FILE *fp1;
  int  cap_counter=0;
  int count=0,flag=0;
  int nitems,nread;
  char buffer[MAXBUFSIZE];
  struct timeval t0,t1;
  
  /* double *x,*y,*z; */
  /* x=(double *)calloc(Ngal,sizeof(double)); */
  /* y=(double *)calloc(Ngal,sizeof(double)); */
  /* z=(double *)calloc(Ngal,sizeof(double)); */
  /* for(i=0;i<Ngal;i++){ */
  /*   x[i]=sin((90.-dec[i]) * PI/180.)*cos(ra[i] * PI/180.) ; */
  /*   y[i]=sin((90.-dec[i]) * PI/180.)*sin(ra[i] * PI/180.) ; */
  /*   z[i]=cos((90.-dec[i]) * PI/180.) ; */
  /* } */


  polygons_tag = malloc(9*sizeof(char));
  polygon_tag = malloc(8*sizeof(char));
  caps_tag = malloc(6*sizeof(char));
  weight_tag = malloc(8*sizeof(char));
  str_tag = malloc(6*sizeof(char));
  single_tag = malloc(2*sizeof(char));
  pixel_tag = malloc(7*sizeof(char));

  fp1=my_fopen(Polygon_File,"r");
  fscanf(fp1,"%d %s\n",&n_masks,polygons_tag);
  fprintf(stderr,"jackknife_it> There are %d masks.\n",n_masks);


  int *mask_id,pixel,n_circ;
  double *weight,*area;
  double x_poly,y_poly,z_poly,dot_poly;
  
  area=my_calloc(sizeof(*area),n_masks);
  weight=my_calloc(sizeof(*weight),n_masks);
  mask_id=my_calloc(sizeof(*mask_id),n_masks);

  char check[100];
  fscanf(fp1,"%s",check);	
  while(strncmp("polygon",check,100)!=0)
    fscanf(fp1,"%s",check);


  i=0;
  nitems = 10;
  /* fscanf(fp1,"%d %s %d %s %lf %s %d %s %lf %s", */
  /* 	 &mask_id[i],single_tag,&n_circ,caps_tag,&weight[i],weight_tag,&pixel,pixel_tag,&area[i],str_tag);	 */


  fgets(buffer,MAXBUFSIZE,fp1);
  nread=sscanf(buffer,"%d %s %d %s %lf %s %d %s %lf %s",
	       &mask_id[i],single_tag,&n_circ,caps_tag,&weight[i],weight_tag,&pixel,pixel_tag,&area[i],str_tag);
  assert(nread==nitems);
  
  if(strncmp("str):",str_tag,5)!=0)  {
    fprintf(stderr,"jackknife_it> str_tag = %s\n",str_tag);	
    fprintf(stderr,"jackknife_it> You are using a different format than I expected.\n");
    fprintf(stderr,"jackknife_it> You are missing a field.  I cannot fix this. You have asked too much of me.\n");
    
    return ;
  }

  /* for (k=0;k<n_circ;k++) { */
  /*   fscanf(fp1,"%lf %lf %lf %lf ",&x_poly,&y_poly,&z_poly,&dot_poly); */
  /* } */


  for(k=0;k<n_circ;k++) {
    fgets(buffer,MAXBUFSIZE,fp1);
  }

  nitems=11;
  gettimeofday(&t0,NULL);
  for(i=1;i<n_masks;i++) {
    
    /* fscanf(fp1,"%s %d %s %d %s %lf %s %d %s %lf %s", */
    /* 	   polygon_tag,&mask_id[i],single_tag,&n_circ,caps_tag,&weight[i],weight_tag,&pixel,pixel_tag,&area[i],str_tag); */

    fgets(buffer,MAXBUFSIZE,fp1);
    nread=sscanf(buffer,"%s %d %s %d %s %lf %s %d %s %lf %s",
    	   polygon_tag,&mask_id[i],single_tag,&n_circ,caps_tag,&weight[i],weight_tag,&pixel,pixel_tag,&area[i],str_tag);

    /* nitems=4; */
    /* nread=sscanf(buffer,"%*s %d %*s %d %*s %lf %*s %*d %*s %lf", */
    /* 	   &mask_id[i],&n_circ,&weight[i],&area[i]); */

    assert(nread==nitems);
    
    /* cap_counter+=n_circ; */
    /* for (k=0;k<n_circ;k++) { */
    /*   fscanf(fp1,"%lf %lf %lf %lf ",&x_poly,&y_poly,&z_poly,&dot_poly); */
    /* } */

    for(k=0;k<n_circ;k++) {
      fgets(buffer,MAXBUFSIZE,fp1);
    }
  }
  gettimeofday(&t1,NULL);
  fprintf(stderr,"fscanf time = %6.2lf sec\n",ADD_DIFF_TIME(t0,t1));


  double *sector_area,*sector_weight;
  int *unique_ids,*jackknife_number;
  *area_tot=0;
  int ids;

  sector_area=(double *)calloc(n_masks,sizeof(double));
  sector_weight=(double *)calloc(n_masks,sizeof(double));
  unique_ids=(int *)calloc(n_masks,sizeof(int));
  jackknife_number=(int *)calloc(n_masks,sizeof(int));


  flag=count=ids=0;
  for(i=0;i<n_masks;i++)
    unique_ids[i]=-1;


  double *xaverage,*yaverage,*zaverage;
  double *sect_center_ra,*sect_center_dec;
  sect_center_ra=(double *)calloc(n_masks,sizeof(double));
  sect_center_dec=(double *)calloc(n_masks,sizeof(double));
  xaverage=(double *)calloc(n_masks,sizeof(double));
  yaverage=(double *)calloc(n_masks,sizeof(double));
  zaverage=(double *)calloc(n_masks,sizeof(double));



  int n_unique_ids=0;
  flag=0;


  double triple_loop_time=0.0;

  gettimeofday(&t0,NULL);
  for(i=0;i<n_masks;i++){ 
    for(k=0;k<Ngal;k++){
      if(mask_id[i]==Galaxy_Sector_Ids[k]){
	for(j=0;j<n_masks;j++){
	  if((mask_id[i]==unique_ids[j])){
	    sector_area[j]+= area[i];
                                                
	    flag=1;
	  }
	}

	if((flag==0)){
	  unique_ids[count]=mask_id[i];
	  sector_area[count]=area[i];
	  sector_weight[count]=weight[i];
	  count++;
	}

	flag=0;
	break;
      }
    }
  }
  gettimeofday(&t1,NULL);
  triple_loop_time += ADD_DIFF_TIME(t0,t1);

	
  fprintf(stderr,"There are %d unique_ids...triple_loop_time = %6.2lf sec\n",count,triple_loop_time);
  n_unique_ids=count;

  for(i=0;i<n_unique_ids;i++){
    xaverage[i]=-1.;
    yaverage[i]=-1.;
    zaverage[i]=-1.;

  }

  gettimeofday(&t0,NULL);
  for(i=0;i<n_unique_ids;i++){
    for(j=0;j<Ngal;j++){
      if(Galaxy_Sector_Ids[j]==unique_ids[i]){
                                
	xaverage[i]+=x[j];
	yaverage[i]+=y[j];
	zaverage[i]+=z[j];
	flag++;

      }
    }

    if(flag==0){
      fprintf(stderr,"Something terrible has happened with xaverage sector id[%d]=%d\n",i,unique_ids[i]);
    }

    xaverage[i]/=flag;
    yaverage[i]/=flag;
    zaverage[i]/=flag;

    flag=0;
  }
  gettimeofday(&t1,NULL);
  triple_loop_time += ADD_DIFF_TIME(t0,t1);

  
  for(i=0;i<n_unique_ids;i++) {
    if(xaverage[i]==-1. || yaverage[i]==-1. || zaverage[i]==-1)
      fprintf(stderr,"Something terrible has happened with sector_id[%d]=%d\n",i,unique_ids[i]);
    
  }


  for(i=0;i<n_unique_ids;i++){
    sect_center_ra[i]=180./PI*atan2(yaverage[i],xaverage[i]);
    sect_center_dec[i]=90.- 180./PI * acos(zaverage[i]/SQRT(SQR(xaverage[i]) + SQR(yaverage[i]) + SQR(zaverage[i])));

  }




  if((n_masks - n_unique_ids) < 2)
    fprintf(stderr,"Jackknife_it> WARNING: You are using a mangle file with the polygon id's instead of the sector id's. Make sure your galaxy file is consitent.\n");
	


#define MULTIPLE_ARRAY_EXCHANGER(type,a,i,j) { SGLIB_ARRAY_ELEMENTS_EXCHANGER(double,sect_center_ra,i,j); SGLIB_ARRAY_ELEMENTS_EXCHANGER(double,sector_area,i,j); SGLIB_ARRAY_ELEMENTS_EXCHANGER(double,sector_weight,i,j);SGLIB_ARRAY_ELEMENTS_EXCHANGER(int,unique_ids,i,j);SGLIB_ARRAY_ELEMENTS_EXCHANGER(double,sect_center_dec,i,j)}


  //	SGLIB_ARRAY_QUICK_SORT(int,unique_ids, count, SGLIB_NUMERIC_COMPARATOR , MULTIPLE_ARRAY_EXCHANGER);
  SGLIB_ARRAY_QUICK_SORT(double,sect_center_ra, count, SGLIB_NUMERIC_COMPARATOR , MULTIPLE_ARRAY_EXCHANGER);

  for(i=0;i<count;i++){
    *area_tot+=sector_area[i];
  }
	
  double area_bin=*area_tot/N_Jackknife;

  fprintf(stderr,"Total area = %lf, Jackknife area=%lf\n",*area_tot,area_bin);

  *area_tot=0;
   double dec_max=65.,dec_min=-4.;
   int n_dec_bins=floor(SQRT(N_Jackknife));
   double dec_bins_size=(dec_max-dec_min)/n_dec_bins;


      for(j=0;j<n_dec_bins;j++){
                for(i=0;i<n_unique_ids;i++){

                        if((sect_center_dec[i] >=(dec_min + j*dec_bins_size)) && (sect_center_dec[i] < (dec_min + (j+1)*dec_bins_size))){

                                *area_tot+=sector_area[i];
                                jackknife_number[i]=(int)floor(*area_tot/area_bin);

                                if(jackknife_number[i]==N_Jackknife){
                                        fprintf(stderr,"Jackknife binning slight screw up.  Hacking the Fix\n");
                                        jackknife_number[i]=N_Jackknife-1;
                                }
                        }
                }
        }








 
  

  for(i=0;i<Ngal;i++){
    for(j=0;j<n_unique_ids;j++){
      if(Galaxy_Sector_Ids[i]==unique_ids[j]){
	Galaxy_Jackknife_Ids[i]=jackknife_number[j];
								
	break;
      }
    }
	
  }

	

  fclose(fp1);
  /* free(x); */
  /* free(y); */
  /* free(z); */
  free(sect_center_ra);
  free(sect_center_dec);
  free(area);
  free(weight);
  free(mask_id);
  free(sector_area);
  free(sector_weight);
  free(unique_ids);
  free(jackknife_number);
  free(xaverage);
  free(yaverage);
  free(zaverage);

  free(polygons_tag);
  free(polygon_tag);
  free(caps_tag);
  free(weight_tag);
  free(str_tag);
  free(single_tag);
  free(pixel_tag);

}
Exemplo n.º 13
0
int liberty_hash_enter_oid(liberty_hash_table *ht, char *name, si2drObjectIdT  oid)
{
	liberty_hash_bucket *hb;
	int hash_num;
	
	if( name == NULL || *name == 0 )
	{
		return -1;
	}
	if( ht->case_insensitive )
		hash_num = liberty_hash_name_hash_nocase(name, ht->size);
	else
		hash_num = liberty_hash_name_hash(name, ht->size);

	for(hb = ht->table[hash_num]; hb; hb = hb->next)
	{
		if( ht->case_insensitive )
		{
			if( strcasecmp(hb->name,name) == 0 )
			{
				return -2;
			}
		}
		else
		{
			if( strcmp(hb->name,name) == 0 )
			{
				return -2;
			}
		}
		
	}
	
	hb = (liberty_hash_bucket *)my_calloc(sizeof(liberty_hash_bucket),1);
	hb->name = name;
	hb->item = oid;

	hb->next = ht->table[hash_num];
	ht->table[hash_num] = hb;

	if( ht->all_last == (liberty_hash_bucket*)NULL )
	{
		ht->all_last = hb;
		ht->all_list = hb;
	}
	else
	{
		ht->all_list->all_prev = hb;
		hb->all_next = ht->all_list;
		ht->all_list = hb;
	}
	
	ht->entry_count++;
	ht->counts[hash_num]++;

	if( ht->longest_bucket_string < ht->counts[hash_num] )
		ht->longest_bucket_string = ht->counts[hash_num];

	if( ht->auto_resize && ht->longest_bucket_string > ht->threshold )
	{
		int biggest_size = (ht->size > ht->entry_count ? ht->size : ht->entry_count);
		int next_size = liberty_hash_get_next_higher_prime(biggest_size);
		if( next_size > ht->size )
		{
			liberty_hash_resize_hash_table(ht, next_size);
			if( ht->longest_bucket_string > ht->threshold )
			{
				ht->threshold = ht->longest_bucket_string + 3; /* we don't want to get too radical! */
			}
		}
	}
	
	return 0;

}
Exemplo n.º 14
0
static void bitgen_print_stats(t_block *clb, int num_clusters) {

	/* Prints out one cluster (clb).  Both the external pins and the *
	 * internal connections are printed out.                         */

	int ipin, icluster, itype, inet;/*, iblk;*/
	/*int unabsorbable_ffs;*/
	int total_nets_absorbed;
	boolean * nets_absorbed;

	int *num_clb_types, *num_clb_inputs_used, *num_clb_outputs_used;

	nets_absorbed = NULL;
	num_clb_types = num_clb_inputs_used = num_clb_outputs_used = NULL;

	num_clb_types = (int*) my_calloc(num_types, sizeof(int));
	num_clb_inputs_used = (int*) my_calloc(num_types, sizeof(int));
	num_clb_outputs_used = (int*) my_calloc(num_types, sizeof(int));


	nets_absorbed = (boolean *) my_calloc(num_logical_nets, sizeof(boolean));
	for (inet = 0; inet < num_logical_nets; inet++) {
		nets_absorbed[inet] = TRUE;
	}

#if 0

/*counting number of flipflops which cannot be absorbed to check the optimality of the packer wrt CLB density*/

	unabsorbable_ffs = 0;
	for (iblk = 0; iblk < num_logical_blocks; iblk++) {
		if (strcmp(logical_block[iblk].model->name, "latch") == 0) {
			if (vpack_net[logical_block[iblk].input_nets[0][0]].num_sinks > 1
					|| strcmp(
							logical_block[vpack_net[logical_block[iblk].input_nets[0][0]].node_block[0]].model->name,
							"names") != 0) {
				unabsorbable_ffs++;
			}
		}
	}
	vpr_printf(TIO_MESSAGE_INFO, "\n");
	vpr_printf(TIO_MESSAGE_INFO, "%d FFs in input netlist not absorbable (ie. impossible to form BLE).\n", unabsorbable_ffs);
#endif

	/* Counters used only for statistics purposes. */

	for (icluster = 0; icluster < num_clusters; icluster++) {
		for (ipin = 0; ipin < clb[icluster].type->num_pins; ipin++) {
			if (clb[icluster].nets[ipin] != OPEN) {
				nets_absorbed[clb[icluster].nets[ipin]] = FALSE;
				if (clb[icluster].type->class_inf[clb[icluster].type->pin_class[ipin]].type
						== RECEIVER) {
					num_clb_inputs_used[clb[icluster].type->index]++;
				} else if (clb[icluster].type->class_inf[clb[icluster].type->pin_class[ipin]].type
						== DRIVER) {
					num_clb_outputs_used[clb[icluster].type->index]++;
				}
			}
		}
		num_clb_types[clb[icluster].type->index]++;
	}

	for (itype = 0; itype < num_types; itype++) {
		if (num_clb_types[itype] == 0) {
			vpr_printf(TIO_MESSAGE_INFO, "\t%s: # blocks: %d, average # input + clock pins used: %g, average # output pins used: %g\n",
					type_descriptors[itype].name, num_clb_types[itype], 0.0, 0.0);
		} else {
			vpr_printf(TIO_MESSAGE_INFO, "\t%s: # blocks: %d, average # input + clock pins used: %g, average # output pins used: %g\n",
					type_descriptors[itype].name, num_clb_types[itype],
					(float) num_clb_inputs_used[itype] / (float) num_clb_types[itype],
					(float) num_clb_outputs_used[itype] / (float) num_clb_types[itype]);
		}
	}

	total_nets_absorbed = 0;
	for (inet = 0; inet < num_logical_nets; inet++) {
		if (nets_absorbed[inet] == TRUE) {
			total_nets_absorbed++;
		}
	}
	vpr_printf(TIO_MESSAGE_INFO, "Absorbed logical nets %d out of %d nets, %d nets not absorbed.\n",
			total_nets_absorbed, num_logical_nets, num_logical_nets - total_nets_absorbed);
	free(nets_absorbed);
	free(num_clb_types);
	free(num_clb_inputs_used);
	free(num_clb_outputs_used);
	/* TODO: print more stats */
}
Exemplo n.º 15
0
void load_internal_users()
{
  char *p = NULL, *ln = NULL, *hand = NULL, *ip = NULL, *port = NULL, *pass = NULL, *q = NULL;
  char *hosts = NULL, buf[2048] = "", *attr = NULL, tmp[51] = "";
  int i, hublevel = 0;
  struct bot_addr *bi = NULL;
  struct userrec *u = NULL;

  /* hubs */
  strlcpy(buf, settings.hubs, sizeof(buf));
  p = buf;
  while (p) {
    ln = p;
    p = strchr(p, ',');
    if (p)
      *p++ = 0;
    hand = ln;
    ip = NULL;
    port = NULL;
    u = NULL;
    for (i = 0; ln; i++) {
      switch (i) {
        case 0:
          hand = ln;
          break;
        case 1:
          ip = ln;
          break;
        case 2:
          port = ln;
          hublevel++;		/* We must increment this even if it is already added */
          if (!get_user_by_handle(userlist, hand)) {
            userlist = adduser(userlist, hand, "none", "-", USER_OP, 1);
            u = get_user_by_handle(userlist, hand);

            simple_snprintf(tmp, sizeof(tmp), "%li [internal]", (long)now);
            set_user(&USERENTRY_ADDED, u, tmp);

            bi = (struct bot_addr *) my_calloc(1, sizeof(struct bot_addr));

            bi->address = strdup(ip);
            bi->telnet_port = atoi(port) ? atoi(port) : 0;
            bi->relay_port = bi->telnet_port;
            bi->hublevel = hublevel;
            if (conf.bot->hub && (!bi->hublevel) && (!strcasecmp(hand, conf.bot->nick)))
              bi->hublevel = 99;
            bi->uplink = (char *) my_calloc(1, 1);
            set_user(&USERENTRY_BOTADDR, u, bi);
            /* set_user(&USERENTRY_PASS, get_user_by_handle(userlist, hand), SALT2); */
          }
          break;
        default:
          break;
      }
      if (ln && (ln = strchr(ln, ' ')))
        *ln++ = 0;
    }
  }

  /* perm owners */
  owner[0] = 0;

  strlcpy(buf, settings.owners, sizeof(buf));
  p = buf;
  while (p) {
    ln = p;
    p = strchr(p, ',');
    if (p)
      *p++ = 0;
    hand = ln;
    pass = NULL;
    attr = NULL;
    hosts = NULL;
    for (i = 0; ln; i++) {
      switch (i) {
        case 0:
          hand = ln;
          break;
        case 1:
          pass = ln;

          if (ln && (ln = strchr(ln, ' ')))
            *ln++ = 0;

          hosts = ln;
          if (owner[0])
            strlcat(owner, ",", 121);
          strlcat(owner, hand, 121);
          if (!get_user_by_handle(userlist, hand)) {
            userlist = adduser(userlist, hand, "none", "-", USER_ADMIN | USER_OWNER | USER_MASTER | USER_OP | USER_PARTY | USER_HUBA | USER_CHUBA, 0);
            u = get_user_by_handle(userlist, hand);
            set_user(&USERENTRY_PASS, u, pass);
            simple_snprintf(tmp, sizeof(tmp), "%li [internal]", (long)now);
            set_user(&USERENTRY_ADDED, u, tmp);
            while (hosts) {
              char x[1024] = "";

              if ((ln = strchr(ln, ' ')))
                *ln++ = 0;

              if ((q = strchr(hosts, '!'))) {	/* skip over nick they provided ... */
                q++;
                if (*q == '*' || *q == '?')		/* ... and any '*' or '?' */
                  q++;
                hosts = q;
              }

              simple_snprintf(x, sizeof(x), "-telnet!%s", hosts);
              set_user(&USERENTRY_HOSTS, u, x);
              hosts = ln;
            }
          }
          break;
        default:
          break;
      }
      if (ln && (ln = strchr(ln, ' ')))
        *ln++ = 0;
    }
  }

  // Add HQ in if needed
  if (!backgrd && term_z) {
    strlcat(owner, ",HQ", sizeof(owner));
  }

}
Exemplo n.º 16
0
Arquivo: misc.c Projeto: kirune/wraith
void showhelp(int idx, struct flag_record *flags, const char *string)
{
  struct flag_record fr = {FR_GLOBAL | FR_CHAN, 0, 0, 0 };
  size_t help_siz = strlen(string) + 1000 + 1;
  char *helpstr = (char *) my_calloc(1, help_siz);
  char tmp[2] = "", flagstr[10] = "";
  bool ok = 1;

  while (string && string[0]) {
    if (*string == '%') {
      if (!strncmp(string + 1, "{+", 2)) {
        while (*string && *string != '+') {
          string++;
        }
        flagstr[0] = 0;
        while (*string && *string != '}') {
          simple_snprintf(tmp, sizeof(tmp), "%c", *string);
          strlcat(flagstr, tmp, sizeof(flagstr));
          string++;
        }
        string++;
        break_down_flags(flagstr, &fr, NULL);
        if (flagrec_ok(&fr, flags)) {
          ok = 1;
          while (*string && *string != '%') {
            simple_snprintf(tmp, sizeof(tmp), "%c", *string);
            strlcat(helpstr, tmp, help_siz);
            string++;
          }
          if (!strncmp(string + 1, "{-", 2)) {
            ok = 1;
            while (*string && *string != '}') {
              string++;
            }
            string++;
          }
        } else {
          ok = 0;
        }
      } else if (!strncmp(string + 1, "{-", 2)) {
        ok = 1;
        while (*string && *string != '}') {
          string++;
        }
        string++;
      } else if (*string == '{') {
        while (*string && *string != '}') {
          string++;
        }
      } else if (*(string + 1) == 'd') {
        string += 2;
        if (dcc[idx].u.chat->channel >= 0)
          strlcat(helpstr, settings.dcc_prefix, help_siz);
      } else if (*(string + 1) == '%') {
        string += 2;
        strlcat(helpstr, "%", help_siz);
      } else {
        if (ok) {
          simple_snprintf(tmp, sizeof(tmp), "%c", *string);
          strlcat(helpstr, tmp, help_siz);
        }
        string++;
      }
    } else {
      if (ok) {
        simple_snprintf(tmp, sizeof(tmp), "%c", *string);
        strlcat(helpstr, tmp, help_siz);
      }
      string++;
    }
  }
  helpstr[strlen(helpstr)] = 0;
  if (helpstr[0]) dumplots(idx, "", helpstr);
  free(helpstr);
}
Exemplo n.º 17
0
/* do_chanset() set (options) on (chan)
 * USES DO_LOCAL|DO_NET bits.
 */
int do_chanset(char *result, struct chanset_t *chan, const char *options, int flags)
{
  int ret = OK;

  if (flags & DO_NET) {
    size_t bufsiz = 0;
         /* malloc(options,chan,'cset ',' ',+ 1) */
    if (chan)
      bufsiz = strlen(options) + strlen(chan->dname) + 5 + 1 + 1;
    else
      bufsiz = strlen(options) + 1 + 5 + 1 + 1;
    
    char *buf = (char*) my_calloc(1, bufsiz);

    strlcat(buf, "cset ", bufsiz);
    if (chan)
      strlcat(buf, chan->dname, bufsiz);
    else
      strlcat(buf, "*", bufsiz);
    strlcat(buf, " ", bufsiz);
    strlcat(buf, options, bufsiz);
    putlog(LOG_DEBUG, "*", "sending out cset: %s", buf);
    putallbots(buf); 
    free(buf);
  }

  if (flags & DO_LOCAL) {
    bool cmd = (flags & CMD);
    struct chanset_t *ch = NULL;
    int all = chan ? 0 : 1;

    if (chan)
      ch = chan;
    else
      ch = chanset_default; //First iteration changes default, then move on to all chans

    while (ch) {
      const char **item = NULL;
      int items = 0;

      if (SplitList(result, options, &items, &item) == OK) {
        ret = channel_modify(result, ch, items, (char **) item, cmd);
      } else 
        ret = ERROR;


      free(item);

      if (all) {
        if (ret == ERROR) /* just bail if there was an error, no sense in trying more */
          return ret;

        if (ch == chanset_default)
          ch = chanset;
        else
          ch = ch->next;
      } else {
        ch = NULL;
      }
    }
  }
  return ret;
}
Exemplo n.º 18
0
Arquivo: misc.c Projeto: kirune/wraith
int updatebin(int idx, char *par, int secs)
{
  if (!par || !par[0]) {
    logidx(idx, "Not enough parameters.");
    return 1;
  }

  size_t path_siz = strlen(binname) + strlen(par) + 2;
  char *path = (char *) my_calloc(1, path_siz);
  char *newbin = NULL, buf[DIRMAX] = "";
  const char* argv[5];
  int i;

  strlcpy(path, binname, path_siz);
  newbin = strrchr(path, '/');
  if (!newbin) {
    free(path);
    logidx(idx, STR("Don't know current binary name"));
    return 1;
  }
  newbin++;
  if (strchr(par, '/')) {
    *newbin = 0;
    logidx(idx, STR("New binary must be in %s and name must be specified without path information"), path);
    free(path);
    return 1;
  }
  strcpy(newbin, par);
  if (!strcmp(path, binname)) {
    free(path);
    logidx(idx, STR("Can't update with the current binary"));
    return 1;
  }
  if (!can_stat(path)) {
    logidx(idx, STR("%s can't be accessed"), path);
    free(path);
    return 1;
  }
  if (fixmod(path)) {
    logidx(idx, STR("Can't set mode 0600 on %s"), path);
    free(path);
    return 1;
  }

  /* Check if the new binary is compatible */
  int initialized_code = check_bin_initialized(path);
  if (initialized_code == 2) {
    logidx(idx, STR("New binary is corrupted or the wrong architecture/operating system."));
    free(path);
    return 1;
  } else if (initialized_code == 1 && !check_bin_compat(path)) {
    logidx(idx, STR("New binary must be initialized as pack structure has been changed in new version."));
    free(path);
    return 1;
  }


  /* make a backup just in case. */

  simple_snprintf(buf, sizeof(buf), STR("%s/.bin.old"), conf.datadir);
  copyfile(binname, buf);

  write_settings(path, -1, 0, initialized_code ? 0 : 1);	/* re-write the binary with our packdata */

  Tempfile *conffile = new Tempfile("conf");

  if (writeconf(NULL, conffile->fd, CONF_ENC)) {
    logidx(idx, STR("Failed to write temporary config file for update."));
    delete conffile;
    return 1;
  }

  /* The binary should return '2' when ran with -2, if not it's probably corrupt. */
  putlog(LOG_DEBUG, "*", STR("Running for update binary test: %s -2"), path);
  argv[0] = path;
  argv[1] = "-2";
  argv[2] = 0;
  i = simple_exec(argv);
  if (i == -1 || WEXITSTATUS(i) != 2) {
    logidx(idx, STR("Couldn't restart new binary (error %d)"), i);
    delete conffile;
    return i;
  }

  /* now to send our config to the new binary */
  putlog(LOG_DEBUG, "*", STR("Running for update conf: %s -4 %s"), path, conffile->file);
  argv[0] = path;
  argv[1] = "-4";
  argv[2] = conffile->file;
  argv[3] = 0;
  i = simple_exec(argv);
  delete conffile;
  if (i == -1 || WEXITSTATUS(i) != 6) { /* 6 for successfull config read/write */
    logidx(idx, STR("Couldn't pass config to new binary (error %d)"), i);
    return i;
  }

  if (movefile(path, binname)) {
    logidx(idx, STR("Can't rename %s to %s"), path, binname);
    free(path);
    return 1;
  }

  if (updating == UPDATE_EXIT) {	  /* dont restart/kill/spawn bots, just die ! */
    printf(STR("* Moved binary to: %s\n"), binname);
    fatal(STR("Binary updated."), 0);
  }
  if (updating == UPDATE_AUTO) {
    /* Make all other bots do a soft restart */
    conf_checkpids(conf.bots);
    conf_killbot(conf.bots, NULL, NULL, SIGHUP);

    if (conf.bot->pid)
      kill(conf.bot->pid, SIGHUP);
    exit(0);
  }

  if (!conf.bot->hub && secs > 0) {
    /* Make all other bots do a soft restart */
    conf_checkpids(conf.bots);
    conf_killbot(conf.bots, NULL, NULL, SIGHUP);
    
    /* invoked with -u */
    if (updating == UPDATE_AUTO) {
      if (conf.bot->pid)
        kill(conf.bot->pid, SIGHUP);
      exit(0);
    }
    /* this odd statement makes it so specifying 1 sec will restart other bots running
     * and then just restart with no delay */
    updating = UPDATE_AUTO;
    if (secs > 1) {
      egg_timeval_t howlong;
      howlong.sec = secs;
      howlong.usec = 0;
      timer_create_complex(&howlong, STR("restarting for update"), (Function) restart, (void *) (long) idx, 0);
    } else
      restart(idx);

    return 0;
  } else
    restart(idx);	/* no timer */

 /* this should never be reached */
  return 2;
}
Exemplo n.º 19
0
static void load_rr_indexed_data_T_values(int index_start,
		int num_indices_to_load, t_rr_type rr_type, int nodes_per_chan,
		t_ivec *** L_rr_node_indices, t_segment_inf * segment_inf) {

	/* Loads the average propagation times through segments of each index type  *
	 * for either all CHANX segment types or all CHANY segment types.  It does  *
	 * this by looking at all the segments in one channel in the middle of the  *
	 * array and averaging the R and C values of all segments of the same type  *
	 * and using them to compute average delay values for this type of segment. */

	int itrack, iseg, inode, cost_index, iswitch;
	float *C_total, *R_total; /* [0..num_rr_indexed_data - 1] */
	int *num_nodes_of_index; /* [0..num_rr_indexed_data - 1] */
	float Rnode, Cnode, Rsw, Tsw;

	num_nodes_of_index = (int *) my_calloc(num_rr_indexed_data, sizeof(int));
	C_total = (float *) my_calloc(num_rr_indexed_data, sizeof(float));
	R_total = (float *) my_calloc(num_rr_indexed_data, sizeof(float));

	/* Get average C and R values for all the segments of this type in one      *
	 * channel segment, near the middle of the array.                           */

	for (itrack = 0; itrack < nodes_per_chan; itrack++) {
		inode = get_rr_node_index((nx + 1) / 2, (ny + 1) / 2, rr_type, itrack,
				L_rr_node_indices);
		cost_index = rr_node[inode].cost_index;
		num_nodes_of_index[cost_index]++;
		C_total[cost_index] += rr_node[inode].C;
		R_total[cost_index] += rr_node[inode].R;
	}

	for (cost_index = index_start;
			cost_index < index_start + num_indices_to_load; cost_index++) {

		if (num_nodes_of_index[cost_index] == 0) { /* Segments don't exist. */
			rr_indexed_data[cost_index].T_linear = OPEN;
			rr_indexed_data[cost_index].T_quadratic = OPEN;
			rr_indexed_data[cost_index].C_load = OPEN;
		} else {
			Rnode = R_total[cost_index] / num_nodes_of_index[cost_index];
			Cnode = C_total[cost_index] / num_nodes_of_index[cost_index];
			iseg = rr_indexed_data[cost_index].seg_index;
			iswitch = segment_inf[iseg].wire_switch;
			Rsw = switch_inf[iswitch].R;
			Tsw = switch_inf[iswitch].Tdel;

			if (switch_inf[iswitch].buffered) {
				rr_indexed_data[cost_index].T_linear = Tsw + Rsw * Cnode
						+ 0.5 * Rnode * Cnode;
				rr_indexed_data[cost_index].T_quadratic = 0.;
				rr_indexed_data[cost_index].C_load = 0.;
			} else { /* Pass transistor */
				rr_indexed_data[cost_index].C_load = Cnode;

				/* See Dec. 23, 1997 notes for deriviation of formulae. */

				rr_indexed_data[cost_index].T_linear = Tsw + 0.5 * Rsw * Cnode;
				rr_indexed_data[cost_index].T_quadratic = (Rsw + Rnode) * 0.5
						* Cnode;
			}
		}
	}

	free(num_nodes_of_index);
	free(C_total);
	free(R_total);
}
Exemplo n.º 20
0
static BOOL initAgent(HSP *sp)
{
	time_t now;
	HSPCollector *collector;
	SFLReceiver *receiver;
	uint32_t receiverIndex;
	SFLDataSource_instance dsi;
	uint32_t pollingInterval;
	HSPSFlow *sf = sp->sFlow;
	WSADATA WSAData;
	int WSARes = 0;

	myLog(LOG_INFO,"creating sfl agent\n");
	if (sf->collectors == NULL) {
		myLog(LOG_ERR,"No collectors defined\n");
		return FALSE;
	}
	assert(sf->agentIP.type);

	WORD word = MAKEWORD(2, 2);
	WSARes = WSAStartup(word,&WSAData);
	if (WSARes != 0) {
		myLog(LOG_ERR,"WSAStartup failed: %d",WSARes);
		exit(WSARes);
	}
	// open the sockets if not open already - one for v4 and another for v6
    if (sp->socket4 <= 0) {
		if ((sp->socket4 = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
			myLog(LOG_ERR,"socket error");
		}
	}
	if (sp->socket6 <= 0) {
		if ((sp->socket6 = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) == -1) {
			myLog(LOG_ERR,"socket error");
		}
	}
	time(&now);
	sf->agent = (SFLAgent *)my_calloc(sizeof(SFLAgent));
	sfl_agent_init(sf->agent,
				   &sf->agentIP,
				   sf->subAgentId,
				   now,
				   now,
				   sp,
				   agentCB_alloc,
				   agentCB_free,
				   agentCB_error,
				   agentCB_sendPkt);
	// just one receiver - we are serious about making this lightweight for now
	collector = sf->collectors;
	receiver = sfl_agent_addReceiver(sf->agent);
	receiverIndex = HSP_SFLOW_RECEIVER_INDEX;
    
	// set the default receiver owner string
	sfl_receiver_set_sFlowRcvrOwner(receiver, "HyperV sFlow Agent");
    
	// set the timeout to infinity
	sfl_receiver_set_sFlowRcvrTimeout(receiver, 0xFFFFFFFF);

	// receiver address/port - set it for the first collector,  but
	// actually we'll send the same feed to all collectors.  This step
	// may not be necessary at all when we are using the sendPkt callback.
	sfl_receiver_set_sFlowRcvrAddress(receiver, &collector->ipAddr);
	sfl_receiver_set_sFlowRcvrPort(receiver, collector->udpPort);
    
	pollingInterval = sf->sFlowSettings ? sf->sFlowSettings->pollingInterval : SFL_DEFAULT_POLLING_INTERVAL;
	// add a single poller to represent the whole physical host
	if (pollingInterval > 0) {
		// ds_class = <physicalEntity>, ds_index = <my physical>, ds_instance = 0
		SFL_DS_SET(dsi, SFL_DSCLASS_PHYSICAL_ENTITY, HSP_DEFAULT_PHYSICAL_DSINDEX, 0);  
		sf->poller = sfl_agent_addPoller(sf->agent, &dsi, sp, agentCB_getCounters);
		sfl_poller_set_sFlowCpInterval(sf->poller, pollingInterval);
		sfl_poller_set_sFlowCpReceiver(sf->poller, receiverIndex);
	}
    return TRUE;
}
Exemplo n.º 21
0
/* Returns a token list of the text for a given string. */
t_token *GetTokensFromString(INP const char* inString, OUTP int * num_tokens) {
	const char *cur;
	t_token * tokens;
	int i, in_string_index, prev_in_string_index;
	boolean has_null;
	enum e_token_type cur_token_type, new_token_type;

	*num_tokens = i = 0;
	cur_token_type = TOKEN_NULL;

	if (inString == NULL) {
		return NULL;
	};

	cur = inString;

	/* Count number of tokens */
	while (*cur) {
		new_token_type = GetTokenTypeFromChar(cur_token_type, *cur);
		if (new_token_type != cur_token_type) {
			cur_token_type = new_token_type;
			if (new_token_type != TOKEN_NULL) {
				i++;
			}
		}
		++cur;
	}
	*num_tokens = i;

	if (*num_tokens > 0) {
		tokens = (t_token*)my_calloc(*num_tokens + 1, sizeof(t_token));
	} else {
		return NULL;
	}

	/* populate tokens */
	i = 0;
	in_string_index = 0;
	has_null = TRUE;
	prev_in_string_index = 0;
	cur_token_type = TOKEN_NULL;

	cur = inString;

	while (*cur) {

		new_token_type = GetTokenTypeFromChar(cur_token_type, *cur);
		if (new_token_type != cur_token_type) {
			if (!has_null) {
				tokens[i - 1].data[in_string_index - prev_in_string_index] =
						'\0'; /* NULL the end of the data string */
				has_null = TRUE;
			}
			if (new_token_type != TOKEN_NULL) {
				tokens[i].type = new_token_type;
				tokens[i].data = my_strdup(inString + in_string_index);
				prev_in_string_index = in_string_index;
				has_null = FALSE;
				i++;
			}
			cur_token_type = new_token_type;
		}
		++cur;
		in_string_index++;
	}

	assert(i == *num_tokens);

	tokens[*num_tokens].type = TOKEN_NULL;
	tokens[*num_tokens].data = NULL;

	/* Return the list */
	return tokens;
}
Exemplo n.º 22
0
void ServiceMain(int argc, char** argv) 
{ 
	ServiceStatus.dwServiceType        = SERVICE_WIN32; 
	ServiceStatus.dwCurrentState       = SERVICE_START_PENDING; 
	ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	ServiceStatus.dwWin32ExitCode      = 0; 
	ServiceStatus.dwServiceSpecificExitCode = 0; 
	ServiceStatus.dwCheckPoint         = 0;
	ServiceStatus.dwWaitHint           = 0;
	if (isService) {
		hStatus = RegisterServiceCtrlHandler(HSP_SERVICE_NAME, 
											 (LPHANDLER_FUNCTION)ControlHandler); 

		if (hStatus == 0) 
		{ 
			return; 
		}
	}
	// Test for only one instance is running
	HANDLE mutex = CreateMutex(NULL, TRUE, instanceMutexName);
	DWORD err = GetLastError();
	if (mutex != NULL && err == ERROR_ALREADY_EXISTS ||
		mutex == NULL && err == ERROR_ACCESS_DENIED) {
			// Mutex found, so another instance is running
		if (hStatus != 0) {
			ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			ServiceStatus.dwWin32ExitCode = ERROR_SINGLE_INSTANCE_APP;
			SetServiceStatus(hStatus, &ServiceStatus);
		} else {
			myLog(LOG_ERR, "%s.ServiceMain: only one instance can run, existing instance found", HSP_SERVICE_NAME);
		}
		return;
	} else {
		ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
		if (hStatus != 0) {
			// We are the first instance, report the running status to SCM. 
			SetServiceStatus (hStatus, &ServiceStatus);
		}
	}
	wchar_t programDataDir[MAX_PATH];
	if (!initialiseProgramDataDir(programDataDir, MAX_PATH)) {
		*programDataDir = NULL;
	}
	char mbcLogFilename[MAX_PATH];
	if (isService && *programDataDir != NULL) {
		//set the log file name to the default.
		size_t dirLen = 0;
		if (0 == wcstombs_s(&dirLen, mbcLogFilename, MAX_PATH, programDataDir, wcslen(programDataDir))) {
			PathAppend(mbcLogFilename, HSP_DEFAULT_LOGFILE);
			logFilename = mbcLogFilename;
		} else {
			logFilename = NULL;
		}
	}
	if (logFilename != NULL) {
        // Logging on
     	errno_t error = fopen_s(&logFile, logFilename, "wt");
        if (error != 0) {
			logFile = stderr;
			myLog(LOG_ERR, "%s.ServiceMain: could not open log file %s: error %d\n", HSP_SERVICE_NAME, logFilename, error);
        }
		logFilename = NULL;
    }
	myLog(debug, "-------------Starting %s %s--------------", HSP_SERVICE_NAME, HSP_VERSION);
	fflush(logFile);

	HSP sp = { 0 };
	// look up host-id fields at startup only (hostname
	// may change dynamically so will have to revisit this $$$)
	sp.host_hid.hostname.str = (char *)my_calloc(SFL_MAX_HOSTNAME_CHARS+1);
	sp.host_hid.os_release.str = (char *)my_calloc(SFL_MAX_OSRELEASE_CHARS+1);
	readHidCounters(&sp, &sp.host_hid);
	
	sp.nio_polling_secs = HSP_NIO_POLLING_SECS_32BIT;

	readInterfaces(&sp, TRUE);
	if (!readConfig(&sp)) {
		myLog(LOG_ERR, "%s.ServiceMain: invalid configuration", HSP_SERVICE_NAME);
		if (hStatus != 0) {
			ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			ServiceStatus.dwWin32ExitCode = ERROR_INVALID_PARAMETER;
			SetServiceStatus(hStatus, &ServiceStatus);
		}
		return;
	}
	sp.hyperV = testForHyperv();
	if (sp.hyperV) {
		myLog(debug, "%s.ServiceMain Hyper-V services are running", HSP_SERVICE_NAME);
		if (programDataDir == NULL || !initialiseProgramDataFiles(&sp, programDataDir)) {
			myLog(LOG_ERR, "%s.ServiceMain: cannot initialise switch port and VM state files", HSP_SERVICE_NAME);
			if (hStatus != 0) {
				ServiceStatus.dwCurrentState = SERVICE_STOPPED;
				ServiceStatus.dwWin32ExitCode = ERROR_FILE_NOT_FOUND;
				SetServiceStatus(hStatus, &ServiceStatus);
			}
			return;
		}
		readGuidStore(sp.f_vmStore, sp.vmStoreFile, &sp.vmStore, &sp.maxDsIndex);
		readGuidStore(sp.f_portStore, sp.portStoreFile, &sp.portStore, &sp.maxIfIndex);
	}
	openFilter(&sp); //try to initialise the sFlow filter for sampling
	initAgent(&sp);

	// initialize the clock so we can detect second boundaries
	sp.clk = time(NULL);
 
    // main loop
	BOOL dataAvailable = true;
	uint32_t currReadNum = 0;
    while (ServiceStatus.dwCurrentState == SERVICE_RUNNING && dataAvailable)
	{
		// check for second boundaries and generate ticks for the sFlow library
		time_t now = time(NULL);
		if ((now < sp.clk) || (now - sp.clk) > HSP_MAX_TICKS) {
			// avoid a busy-loop of ticks if time jumps
			myLog(LOG_INFO, "%s.ServiceMain: time jump detected", HSP_SERVICE_NAME);
			sp.clk = now - 1;
		}
		while (sp.clk < now) { //only happens on second boundary
			//start critical
			if (sp.sFlow->sFlowSettings) {
				// update polling interval here if config has changed.
				tick(&sp);
			}
			//end critical
			sp.clk++;
		}
		DWORD result;
		//process a queued counter poller
		processQueuedPoller(&sp);
		//timeout is set so that we loop around checking for ticks and samples
		//several times/s.
		//calculate timeout 200 if the counter poller queue is empty, 0 otherwise
		DWORD timeout = sp.pollerQHead == NULL ? HSP_TIMEOUT : 0;
		if (HSP_FILTER_ACTIVE(sp.filter)) {
			result = WaitForSingleObject(sp.filter.overlaps[currReadNum].hEvent, 
										 timeout);
			if (result == WAIT_OBJECT_0) {
				dataAvailable = sp.filter.overlaps[currReadNum].Internal == ERROR_SUCCESS;
				if (dataAvailable && sp.filter.overlaps[currReadNum].InternalHigh > 0) {
					//process the sample info in sp.filter.buffers[currReadNum]
					readPackets(&sp, sp.filter.buffers[currReadNum]);
				}
				// Re-queue this read
				queueRead(sp.filter.dev,
					      sp.filter.buffers[currReadNum], 
					      sizeof(sp.filter.buffers[currReadNum]), 
						  &sp.filter.overlaps[currReadNum]);
				//set the next buffer to read
				currReadNum = (currReadNum+1)%numConcurrentReads;
			}
		} else {
			Sleep(timeout);
		}
	}
    return; 
}
Exemplo n.º 23
0
static inline void same_cell_avx_intrinsics(DOUBLE *x0, DOUBLE *y0, DOUBLE *z0, const int64_t N0,
                                            const DOUBLE sqr_rpmax, const DOUBLE sqr_rpmin, const int nbin, const DOUBLE *rupp_sqr, const DOUBLE pimax
                                            ,const AVX_FLOATS *m_rupp_sqr
#ifdef OUTPUT_RPAVG
                                            ,const AVX_FLOATS *m_kbin
                                            ,DOUBLE *src_rpavg
#endif                         
                                            ,uint64_t *src_npairs)
{
    uint64_t *npairs = my_calloc(sizeof(*npairs), nbin);
#ifdef OUTPUT_RPAVG
    DOUBLE rpavg[nbin];
    for(int i=0;i<nbin;i++) {
        rpavg[i] = ZERO;
    }
#endif    
    
    for(int64_t i=0;i<N0;i++) {
        const DOUBLE xpos = *x0++;
        const DOUBLE ypos = *y0++;
        const DOUBLE zpos = *z0++;

        DOUBLE *x1 = x0;
        DOUBLE *y1 = y0;
        DOUBLE *z1 = z0;

		int64_t j = i+1;
		for(;j<=(N0 - AVX_NVEC);j+=AVX_NVEC){

#ifdef OUTPUT_RPAVG
            union int8 {
                AVX_INTS m_ibin;
                int ibin[AVX_NVEC];
            };
            union int8 union_rpbin;
            
            union float8{
                AVX_FLOATS m_Dperp;
                DOUBLE Dperp[AVX_NVEC];
            };
            union float8 union_mDperp;
#endif
            const AVX_FLOATS m_xpos = AVX_SET_FLOAT(xpos);
            const AVX_FLOATS m_ypos = AVX_SET_FLOAT(ypos);
            const AVX_FLOATS m_zpos = AVX_SET_FLOAT(zpos);


            const AVX_FLOATS m_x1 = AVX_LOAD_FLOATS_UNALIGNED(x1);
			const AVX_FLOATS m_y1 = AVX_LOAD_FLOATS_UNALIGNED(y1);
			const AVX_FLOATS m_z1 = AVX_LOAD_FLOATS_UNALIGNED(z1);
            
			x1 += AVX_NVEC;
			y1 += AVX_NVEC;
			z1 += AVX_NVEC;

            const AVX_FLOATS m_pimax = AVX_SET_FLOAT(pimax);
            const AVX_FLOATS m_sqr_rpmax = m_rupp_sqr[nbin-1];
            const AVX_FLOATS m_sqr_rpmin = m_rupp_sqr[0];
            
			const AVX_FLOATS m_sqr_xdiff = AVX_SQUARE_FLOAT(AVX_SUBTRACT_FLOATS(m_x1, m_xpos));
            const AVX_FLOATS m_sqr_ydiff = AVX_SQUARE_FLOAT(AVX_SUBTRACT_FLOATS(m_y1, m_ypos));
            const AVX_FLOATS m_zdiff = AVX_SUBTRACT_FLOATS(m_z1, m_zpos);
            
            AVX_FLOATS r2  = AVX_ADD_FLOATS(m_sqr_xdiff,m_sqr_ydiff);
            AVX_FLOATS m_mask_left;
            
            //Do all the distance cuts using masks here in new scope
            {
                //the z2 arrays are sorted in increasing order. which means
                //the z2 value will increase in any future iteration of j.
                //that implies the zdiff values are also monotonically increasing
                //Therefore, if none of the zdiff values are less than pimax, then
                //no future iteration in j can produce a zdiff value less than pimax.
                //The code terminates the j-loop early in that case (and also sets
                //j equal to first->nelements to ensure that the remainder loop
                //does not run either.
                AVX_FLOATS m_mask_pimax = AVX_COMPARE_FLOATS(m_zdiff,m_pimax,_CMP_LT_OS);
                if(AVX_TEST_COMPARISON(m_mask_pimax) == 0) {
                    //If the execution reaches here -> then none of the AVX_NVEC zdiff values
                    //are smaller than pimax. We can terminate the j-loop now.
                    
                    //set j so that the remainder loop does not run
                    j = N0;
                    //break out of the j-loop
                    break;
                }
                
                /* //Create a mask with true bits when  0 <= zdiff < pimax. */
                /* m_mask_pimax = AVX_BITWISE_AND(AVX_COMPARE_FLOATS(m_zdiff,m_zero,_CMP_GE_OS),m_mask_pimax); */
                const AVX_FLOATS m_rpmax_mask = AVX_COMPARE_FLOATS(r2, m_sqr_rpmax, _CMP_LT_OS);
                const AVX_FLOATS m_rpmin_mask = AVX_COMPARE_FLOATS(r2, m_sqr_rpmin, _CMP_GE_OS);
                const AVX_FLOATS m_rp_mask = AVX_BITWISE_AND(m_rpmax_mask,m_rpmin_mask);
                
                //Create a combined mask by bitwise and of m1 and m_mask_left.
                //This gives us the mask for all sqr_rpmin <= r2 < sqr_rpmax
                m_mask_left = AVX_BITWISE_AND(m_mask_pimax,m_rp_mask);

                
                //If not, continue with the next iteration of j-loop
                if(AVX_TEST_COMPARISON(m_mask_left) == 0) {
                    continue;
                }
                
                //There is some r2 that satisfies sqr_rpmin <= r2 < sqr_rpmax && dz < pimax.
                r2 = AVX_BLEND_FLOATS_WITH_MASK(m_sqr_rpmax, r2, m_mask_left);
            }
            
#ifdef OUTPUT_RPAVG
            union_mDperp.m_Dperp = AVX_SQRT_FLOAT(r2);
            AVX_FLOATS m_rpbin = AVX_SET_FLOAT(ZERO);
#endif
            
            //Loop backwards through nbins. m_mask_left contains all the points that are less than rpmax
            for(int kbin=nbin-1;kbin>=1;kbin--) {
                const AVX_FLOATS m1 = AVX_COMPARE_FLOATS(r2,m_rupp_sqr[kbin-1],_CMP_GE_OS);
                const AVX_FLOATS m_bin_mask = AVX_BITWISE_AND(m1,m_mask_left);
                const int test2  = AVX_TEST_COMPARISON(m_bin_mask);
                npairs[kbin] += AVX_BIT_COUNT_INT(test2);
#ifdef OUTPUT_RPAVG
                m_rpbin = AVX_BLEND_FLOATS_WITH_MASK(m_rpbin,m_kbin[kbin], m_bin_mask);
#endif
                m_mask_left = AVX_COMPARE_FLOATS(r2,m_rupp_sqr[kbin-1],_CMP_LT_OS);
                const int test3 = AVX_TEST_COMPARISON(m_mask_left);
                if(test3 == 0) {
                    break;
                }
            }
            
#ifdef OUTPUT_RPAVG
            union_rpbin.m_ibin = AVX_TRUNCATE_FLOAT_TO_INT(m_rpbin);
            //protect the unroll pragma in case compiler is not icc.
#if  __INTEL_COMPILER
#pragma unroll(AVX_NVEC)
#endif
            for(int jj=0;jj<AVX_NVEC;jj++) {
                const int kbin = union_rpbin.ibin[jj];
                const DOUBLE r = union_mDperp.Dperp[jj];
                rpavg[kbin] += r;
            }
#endif//OUTPUT_RPAVG
		}//j loop		

        //remainder j loop
		for(;j<N0;j++) {
            const DOUBLE dx = *x1++ - xpos;
            const DOUBLE dy = *y1++ - ypos;
            const DOUBLE dz = *z1++ - zpos;
            if(dz >= pimax) break;

            const DOUBLE r2 = dx*dx + dy*dy;
            if(r2 >= sqr_rpmax || r2 < sqr_rpmin) continue;
            
#ifdef OUTPUT_RPAVG
            const DOUBLE r = SQRT(r2);
#endif
          
		  for(int kbin=nbin-1;kbin>=1;kbin--){
				if(r2 >= rupp_sqr[kbin-1]) {
					npairs[kbin]++;
#ifdef OUTPUT_RPAVG
                    rpavg[kbin] += r;
                    
#endif                    
					break;
				}
		  }//searching for kbin loop
		}//remainder j loop
	}//i-loop over all particles in cell

	for(int i=0;i<nbin;i++) {
		src_npairs[i] += npairs[i];
#ifdef OUTPUT_RPAVG
        src_rpavg[i] += rpavg[i];
#endif        
	}
	free(npairs);
}
Exemplo n.º 24
0
  int readInterfaces_lifreq(HSP *sp)
  {
    int interfaces_found = 0;
    struct lifnum ln;
    struct lifconf lc;
    struct lifreq rq;
    int i, nFd;
    int up, loopback, promisc, bond_master;
    nFd = socket(AF_INET, SOCK_DGRAM, 0);
    if (nFd >= 0)
      {
        ln.lifn_family = AF_INET;
        ln.lifn_flags = 0;
        if (ioctl(nFd, SIOCGLIFNUM, &ln) == 0) {
	  lc.lifc_family = AF_INET;
	  lc.lifc_flags = 0;
	  lc.lifc_len = sizeof(struct lifreq) * ln.lifn_count;
	  lc.lifc_buf = (caddr_t)my_calloc(lc.lifc_len);
	  if (ioctl(nFd, SIOCGLIFCONF, &lc) == 0) {
	    if(debug > 2) myLog(LOG_INFO, "ln.lifn_count = %u", ln.lifn_count);
	    for (i = 0; i < ln.lifn_count; i++) {
	      strcpy(rq.lifr_name, lc.lifc_req[i].lifr_name);
	      myLog(LOG_INFO, "interface: %s", rq.lifr_name);
	      if (ioctl(nFd, SIOCGLIFFLAGS, &rq) == 0) {
		if(debug) myLog(LOG_INFO, "interface:%s flags=%x",
				rq.lifr_name,
				rq.lifr_index);
		up = (rq.lifr_flags & IFF_UP) ? 1 : 0;
		loopback = (rq.lifr_flags & IFF_LOOPBACK) ? 1: 0;
		promisc = (rq.lifr_flags & IFF_PROMISC) ? 1 : 0;
		// TODO: No IFF_MASTER so set to 0
		bond_master = 0;
		if(up == 0) continue;
		interfaces_found++;
	      
		// get MAC if we can
		u_char *macptr = NULL;
		u_char macAddr[6];
		if(readMacAddress(rq.lifr_name, macAddr, 6)) {
		  macptr = macAddr;
		}

		// find or create the "adaptor" entry for this dev
		SFLAdaptor *adaptor = adaptorListAdd(sp->adaptorList, rq.lifr_name, macptr, sizeof(HSPAdaptorNIO));
			
		// clear the mark so we don't free it below
		adaptor->marked = NO; 
			
		// this flag might belong in the adaptorNIO struct
		adaptor->promiscuous = promisc;
			
		// remember some useful flags in the userData structure
		HSPAdaptorNIO *adaptorNIO = (HSPAdaptorNIO *)adaptor->userData;
		adaptorNIO->loopback = loopback;
		adaptorNIO->bond_master = bond_master;
		adaptorNIO->vlan = HSP_VLAN_ALL; // may be modified below
		adaptorNIO->forCounters = NO;

		if (ioctl(nFd, SIOCGLIFINDEX, &rq) == 0) {
		  if(debug) myLog(LOG_INFO, "interface: %s ifIndex=%d",
				  rq.lifr_name,
				  rq.lifr_index);
		  adaptor->ifIndex = rq.lifr_index;
		}

		if (ioctl(nFd, SIOCGLIFADDR, &rq) == 0) {
		  char buf[51];
			  
		  if (AF_INET == rq.lifr_addr.ss_family) {
		    struct sockaddr_in *s = (struct sockaddr_in *)&rq.lifr_addr;
		    adaptorNIO->ipAddr.type = SFLADDRESSTYPE_IP_V4;
		    adaptorNIO->ipAddr.address.ip_v4.addr = s->sin_addr.s_addr;
		  }
		  else if(AF_INET6 == rq.lifr_addr.ss_family) {
		    /* I think we have to do the whole thing with an IPv6 raw socket
		       before we can get an IPv6 address this way,  so this will
		       probably not work.  Better to use getifaddrs() if we can. */
		    struct sockaddr_in6 *s = (struct sockaddr_in6 *)&rq.lifr_addr;
		    adaptorNIO->ipAddr.type = SFLADDRESSTYPE_IP_V6;
		    memcpy(&adaptorNIO->ipAddr.address.ip_v6.addr, &s->sin6_addr, 16);
		  }
		  if(debug) {
		    myLog(LOG_INFO, "lifreq interface: %s family: %d IP: %s",
			  rq.lifr_name,
			  rq.lifr_addr.ss_family,
			  inet_ntop(rq.lifr_addr.ss_family, &adaptorNIO->ipAddr.address, buf, 51));
		  }
		}
	      }
	    }
	  }
	  
	  my_free(lc.lifc_buf);
	}
        close(nFd);
      }
    
    if(debug) myLog(LOG_INFO, "found (and unmarked) %d interfaces via lifrec", interfaces_found);
    return interfaces_found;
  }
Exemplo n.º 25
0
void
print_relative_pos_distr(void)
{

	/* Prints out the probability distribution of the relative locations of *
	 * input pins on a net -- i.e. simulates 2-point net distance probability *
	 * distribution.                                                        */
#ifdef PRINT_REL_POS_DISTR
	FILE *out_bin_file;
	relapos_rec_t rp_rec;
#endif /* PRINT_REL_POS_DISTR */

	int inet, len, rp, src_x, src_y, dst_x, dst_y, del_x, del_y, min_del,
	sink_pin, sum;
	int *total_conn;
	int **relapos;
	double **relapos_distr;

	total_conn = (int *)my_malloc((nx + ny + 1) * sizeof(int));
	relapos = (int **)my_malloc((nx + ny + 1) * sizeof(int *));
	relapos_distr = (double **)my_malloc((nx + ny + 1) * sizeof(double *));
	for (len = 0; len <= nx + ny; len++)
	{
		relapos[len] = (int *)my_calloc(len / 2 + 1, sizeof(int));
		relapos_distr[len] =
		(double *)my_calloc((len / 2 + 1), sizeof(double));
	}

	for (inet = 0; inet < num_nets; inet++)
	{
		if (clb_net[inet].is_global == FALSE)
		{

			src_x = block[clb_net[inet].node_block[0]].x;
			src_y = block[clb_net[inet].node_block[0]].y;

			for (sink_pin = 1; sink_pin <= clb_net[inet].num_sinks;
					sink_pin++)
			{
				dst_x = block[clb_net[inet].node_block[sink_pin]].x;
				dst_y = block[clb_net[inet].node_block[sink_pin]].y;

				del_x = ABS_DIFF(dst_x, src_x);
				del_y = ABS_DIFF(dst_y, src_y);

				len = del_x + del_y;

				min_del = (del_x < del_y) ? del_x : del_y;

				if (!(min_del <= (len / 2)))
				{
					vpr_printf(TIO_MESSAGE_ERROR, "Error calculating relative location min_del = %d, len = %d\n",
						min_del, len);
					exit(1);
				}
				else
				{
					relapos[len][min_del]++;
				}
			}
		}
	}

#ifdef PRINT_REL_POS_DISTR
	out_bin_file =
	fopen("/jayar/b/b5/fang/vpr_test/wirelength/relapos2.bin", "rb+");
#endif /* PRINT_REL_POS_DISTR */

	for (len = 0; len <= nx + ny; len++)
	{
		sum = 0;
		for (rp = 0; rp <= len / 2; rp++)
		{
			sum += relapos[len][rp];
		}
		if (sum != 0)
		{
#ifdef PRINT_REL_POS_DISTR
			fseek(out_bin_file, sizeof(relapos_rec_t) * len,
					SEEK_SET);
			fread(&rp_rec, sizeof(relapos_rec_t), 1, out_bin_file);
#endif /* PRINT_REL_POS_DISTR */

			for (rp = 0; rp <= len / 2; rp++)
			{

				relapos_distr[len][rp] =
				(double)relapos[len][rp] / (double)sum;

				/* updating the binary record at "len" */
#ifdef PRINT_REL_POS_DISTR
				vpr_printf(TIO_MESSAGE_ERROR, "old %d increased by %d\n", rp_rec.num_rp[rp], relapos[len][rp]);
				rp_rec.num_rp[rp] += relapos[len][rp];
				vpr_printf(TIO_MESSAGE_ERROR, "becomes %d\n", rp_rec.num_rp[rp]);
#endif /* PRINT_REL_POS_DISTR */
			}
#ifdef PRINT_REL_POS_DISTR
			/* write back the updated record at "len" */
			fseek(out_bin_file, sizeof(relapos_rec_t) * len,
					SEEK_SET);
			fwrite(&rp_rec, sizeof(relapos_rec_t), 1, out_bin_file);
#endif /* PRINT_REL_POS_DISTR */

		}
		total_conn[len] = sum;
	}

	fprintf(stdout, "Source to sink relative positions:\n");
	for (len = 1; len <= nx + ny; len++)
	{
		if (total_conn[len] != 0)
		{
			fprintf(stdout, "Of 2-pin distance %d exists %d\n\n", len,
					total_conn[len]);
			for (rp = 0; rp <= len / 2; rp++)
			{
				fprintf(stdout, "\trp%d\t%d\t\t(%.5f)\n", rp,
						relapos[len][rp], relapos_distr[len][rp]);
			}
			fprintf(stdout, "----------------\n");
		}
	}

	free((void *)total_conn);
	for (len = 0; len <= nx + ny; len++)
	{
		free((void *)relapos[len]);
		free((void *)relapos_distr[len]);
	}
	free((void *)relapos);
	free((void *)relapos_distr);

#ifdef PRINT_REL_POS_DISTR
	fclose(out_bin_file);
#endif /* PRINT_REL_POS_DISTR */
}
Exemplo n.º 26
0
void
do_probe(XDR * xdrs, int chfd, struct LSFHeader * reqHdr)
{
    static char         fname[] = "do_probe()";
    char                reply_buf[MSGSIZE];
    XDR                 xdrs2;
    struct LSFHeader    replyHdr;
    struct sbdPackage   sbdPackage;
    struct jobSpecs     *jobSpecs;
    int                 i;
    struct lsfAuth      *auth = NULL;

    if (reqHdr->length == 0)
        return;

    initLSFHeader_(&replyHdr);
    replyHdr.opCode = ERR_NO_ERROR;
    jobSpecs = NULL;

    if (!xdr_sbdPackage(xdrs, &sbdPackage, reqHdr)) {
        ls_syslog(LOG_ERR, I18N_FUNC_FAIL, fname, "xdr_sbdPackage");
        relife();
    } else {
        if (sbdPackage.numJobs) {
            jobSpecs = my_calloc(sbdPackage.numJobs,
                                 sizeof(struct jobSpecs), fname);
            for (i = 0; i < sbdPackage.numJobs; i++) {
                if (!xdr_arrayElement(xdrs, (char *) &(jobSpecs[i]),
                                      reqHdr, xdr_jobSpecs)) {
                    replyHdr.opCode = ERR_BAD_REQ;
                    ls_syslog(LOG_ERR, _i18n_msg_get(ls_catd , NL_SETN, 5815,
                                                     "%s: %s(%d) failed for %d jobs"), /* catgets 5815 */
                              fname, "xdr_arrayElement", i, sbdPackage.numJobs);
                    break;
                }
                refreshJob(&(jobSpecs[i]));
                xdr_lsffree(xdr_jobSpecs, (char *)&jobSpecs[i], reqHdr);
            }
        }
    }
    if (replyHdr.opCode == ERR_NO_ERROR)
	if (!xdr_sbdPackage1(xdrs, &sbdPackage, reqHdr)) {
	    ls_syslog(LOG_ERR, I18N_FUNC_FAIL, fname, "xdr_sbdPackage1");
	    relife();
	}
    if (replyHdr.opCode == ERR_NO_ERROR) {
        if (myStatus & NO_LIM) {
	    replyHdr.opCode = ERR_NO_LIM;
        }
    }
    xdrmem_create(&xdrs2, reply_buf, MSGSIZE, XDR_ENCODE);

    if (!xdr_encodeMsg(&xdrs2, NULL, &replyHdr, NULL, 0, auth)) {
	ls_syslog(LOG_ERR, I18N_FUNC_FAIL, fname, "xdr_encodeMsg");
	relife();
    }

    if (chanWrite_(chfd, reply_buf, XDR_GETPOS(&xdrs2)) <= 0) {
	ls_syslog(LOG_ERR, I18N_FUNC_FAIL_M, fname, "chanWrite_");
    }

    xdr_destroy(&xdrs2);

    if (jobSpecs != NULL)
	free(jobSpecs);


    getManagerId(&sbdPackage);

    mbdPid = sbdPackage.mbdPid;
    sbdSleepTime = sbdPackage.sbdSleepTime;
    retryIntvl = sbdPackage.retryIntvl;
    preemPeriod = sbdPackage.preemPeriod;
    pgSuspIdleT = sbdPackage.pgSuspIdleT;
    maxJobs = sbdPackage.maxJobs;
    uJobLimit = sbdPackage.uJobLimit;
    rusageUpdateRate = sbdPackage.rusageUpdateRate;
    rusageUpdatePercent = sbdPackage.rusageUpdatePercent;
    jobTerminateInterval = sbdPackage.jobTerminateInterval;


    for (i = 0; i < sbdPackage.nAdmins; i++)
	FREEUP(sbdPackage.admins[i]);
    FREEUP(sbdPackage.admins);

    return;
}
Exemplo n.º 27
0
int readInterfaces(HSP *sp)
{
  newAdaptorList(sp);

  // Walk the interfaces and collect the non-loopback interfaces so that we
  // have a list of MAC addresses for each interface (usually only 1).
  //
  // May need to come back and run a variation of this where we supply
  // a domain and collect the virtual interfaces for that domain in a
  // similar way.  It looks like we do that by just parsing the numbers
  // out of the interface name.

  struct ifaddrs *ifap;
  getifaddrs(&ifap);
  for(struct ifaddrs *ifp = ifap; ifp; ifp = ifp->ifa_next) {
    char *devName = ifp->ifa_name;

    if(devName) {
      devName = trimWhitespace(devName);
      // Get the flags for this interface
      int up = (ifp->ifa_flags & IFF_UP) ? YES : NO;
      int loopback = (ifp->ifa_flags & IFF_LOOPBACK) ? YES : NO;
      int address_family = ifp->ifa_addr->sa_family;
      if(debug > 1) {
	myLog(LOG_INFO, "reading interface %s (up=%d, loopback=%d, family=%d)",
	      devName,
	      up,
	      loopback,
	      address_family);
      }
      //int hasBroadcast = (ifp->ifa_flags & IFF_BROADCAST);
      //int pointToPoint = (ifp->ifa_flags & IFF_POINTOPOINT);
      if(up && !loopback && address_family == AF_LINK) {
	// for now just assume that each interface has only one MAC.  It's not clear how we can
	// learn multiple MACs this way anyhow.  It seems like there is just one per ifr record.
	// create a new "adaptor" entry
	SFLAdaptor *adaptor = (SFLAdaptor *)my_calloc(sizeof(SFLAdaptor) + (1 * sizeof(SFLMacAddress)));
	memcpy(adaptor->macs[0].mac, &ifp->ifa_addr->sa_data, 6);
	adaptor->num_macs = 1;
	adaptor->deviceName = strdup(devName);
	
	// Try and get the ifIndex for this interface
	// if(ioctl(fd,SIOCGIFINDEX, &ifr) != 0) {
	// only complain about this if we are debugging
	//if(debug) {
	//myLog(LOG_ERR, "device %s Get SIOCGIFINDEX failed : %s",
	//devName,
	//strerror(errno));
	//}
	//}
	//else {
	//adaptor->ifIndex = ifr.ifr_ifindex;
	//}
	       
	// Try to get the IP address for this interface
/* 	if(ioctl(fd,SIOCGIFADDR, &ifr) != 0) { */
/* 	  // only complain about this if we are debugging */
/* 	  if(debug) { */
/* 	    myLog(LOG_ERR, "device %s Get SIOCGIFADDR failed : %s", */
/* 		  devName, */
/* 		  strerror(errno)); */
/* 	  } */
/* 	} */
/* 	else { */
/* 	  if (ifr.ifr_addr.sa_family == AF_INET) { */
/* 	    struct sockaddr_in *s = (struct sockaddr_in *)&ifr.ifr_addr; */
/* 	    // IP addr is now s->sin_addr */
/* 	    adaptor->ipAddr.addr = s->sin_addr.s_addr; */
/* 	  } */
/* 	  //else if (ifr.ifr_addr.sa_family == AF_INET6) { */
/* 	  // not sure this ever happens - on a linux system IPv6 addresses */
/* 	  // are picked up from /proc/net/if_inet6 */
/* 	  // struct sockaddr_in6 *s = (struct sockaddr_in6 *)&ifr.ifr_addr; */
/* 	  // IP6 addr is now s->sin6_addr; */
/* 	  //} */
/* 	} */
	
	// add it to the list
	sp->adaptorList->adaptors[sp->adaptorList->num_adaptors] = adaptor;
	if(++sp->adaptorList->num_adaptors == sp->adaptorList->capacity)  {
	  // grow
	  sp->adaptorList->capacity *= 2;
	  sp->adaptorList->adaptors = (SFLAdaptor **)my_realloc(sp->adaptorList->adaptors,
								sp->adaptorList->capacity * sizeof(SFLAdaptor *));
	}
      }
    }
  }
  freeifaddrs(ifap);
  return sp->adaptorList->num_adaptors;
}
Exemplo n.º 28
0
void check_rr_graph (enum e_route_type route_type, int num_switch) {

/* This routine sanity checks the routing resource graph to see that it has *
 * no repeated edges between two nodes, that there are no disconnected      *
 * routing resource nodes, and that the attributes of each node are         *
 * reasonable.                                                              */

 int *num_edges_from_current_to_node;   /* [0..num_rr_nodes-1] */
 int *total_edges_to_node;              /* [0..num_rr_nodes-1] */
 char *switch_types_from_current_to_node;  /* [0..num_rr_nodes-1] */
 int inode, iedge, to_node, num_edges;
 short switch_type;
 t_rr_type rr_type, to_rr_type;
 
 total_edges_to_node = (int *) my_calloc (num_rr_nodes, sizeof (int)); 
 num_edges_from_current_to_node = (int *) my_calloc (num_rr_nodes, 
                                      sizeof (int));
 switch_types_from_current_to_node = (char *) my_calloc (num_rr_nodes,
                                      sizeof (char));

 for (inode=0;inode<num_rr_nodes;inode++) {
    rr_type = rr_node[inode].type;
    num_edges = rr_node[inode].num_edges;

    check_node (inode, route_type);
    
/* Check all the connectivity (edges, etc.) information.                    */

    for (iedge=0;iedge<num_edges;iedge++) {
       to_node = rr_node[inode].edges[iedge];

       if (to_node < 0 || to_node >= num_rr_nodes) {
          printf ("Error in check_rr_graph:  node %d has an edge %d.\n"
                  "Edge is out of range.\n", inode, to_node);
          exit (1);
       }

       num_edges_from_current_to_node[to_node]++;
       total_edges_to_node[to_node]++;

       switch_type = rr_node[inode].switches[iedge];

       if (switch_type < 0 || switch_type >= num_switch) {
          printf ("Error in check_rr_graph:  node %d has a switch type %d.\n"
                  "Switch type is out of range.\n", inode, switch_type);
          exit (1);
       }

       if (switch_inf[switch_type].buffered) 
          switch_types_from_current_to_node[to_node] |= BUF_FLAG;
       else
          switch_types_from_current_to_node[to_node] |= PTRANS_FLAG;

    }  /* End for all edges of node. */


    for (iedge=0;iedge<num_edges;iedge++) {
       to_node = rr_node[inode].edges[iedge];

       if (num_edges_from_current_to_node[to_node] > 1) {
          to_rr_type = rr_node[to_node].type;

          if ((to_rr_type != CHANX && to_rr_type != CHANY) ||
                 (rr_type != CHANX && rr_type != CHANY)) {
             printf ("Error in check_rr_graph:  node %d connects to node %d "
                     "%d times.\n", inode, to_node, 
                     num_edges_from_current_to_node[to_node]);
             exit (1);
          }

         /* Between two wire segments.  Two connections are legal only if  *
          * one connection is a buffer and the other is a pass transistor. */

          else if (num_edges_from_current_to_node[to_node] != 2 || 
                      switch_types_from_current_to_node[to_node] != 
                       BUF_AND_PTRANS_FLAG) {
             printf ("Error in check_rr_graph:  node %d connects to node %d "
                     "%d times.\n", inode, to_node, 
                     num_edges_from_current_to_node[to_node]);
             exit (1);
          }
       }

       num_edges_from_current_to_node[to_node] = 0;
       switch_types_from_current_to_node[to_node] = 0;
    }

  /* Slow test below.  Leave commented out most of the time. */

#ifdef DEBUG
    check_pass_transistors (inode);
#endif

 }    /* End for all rr_nodes */


/* I built a list of how many edges went to everything in the code above -- *
 * now I check that everything is reachable.                                */

 for (inode=0;inode<num_rr_nodes;inode++) {
    rr_type = rr_node[inode].type;

    if (rr_type != SOURCE) {
       if (total_edges_to_node[inode] < 1 && 
              !rr_node_is_global_clb_ipin(inode)) {

     /* A global CLB input pin will not have any edges, and neither will  *
      * a SOURCE.  Anything else is an error.                             */

          printf ("Error in check_rr_graph:  node %d has no fanin.\n", inode);
          exit (1);
       }
    }

    else {   /* SOURCE.  No fanin for now; change if feedthroughs allowed. */
       if (total_edges_to_node[inode] != 0) {
          printf ("Error in check_rr_graph:  SOURCE node %d has a fanin\n"
                  "\tof %d, expected 0.\n", inode, total_edges_to_node[inode]);
          exit (1);
       }
    }
 }

 free (num_edges_from_current_to_node);
 free (total_edges_to_node);
 free (switch_types_from_current_to_node);
}
Exemplo n.º 29
0
UTStrBuf *UTStrBuf_new(size_t cap) {
    UTStrBuf *buf = (UTStrBuf *)my_calloc(sizeof(UTStrBuf));
    buf->buf = my_calloc(cap);
    buf->cap = cap;
    return buf;
}
Exemplo n.º 30
0
int readSystemUUID(u_char *uuidbuf){
	int	                    gotData = NO;
	BSTR                    path = SysAllocString(L"root\\wmi");
	BSTR                    className = SysAllocString(L"MSSmBios_RawSMBiosTables");
	BSTR                    propName = SysAllocString(L"SMBiosData");
	ULONG                   uReturned = 1;
	HRESULT                 hr = S_FALSE;
	IWbemLocator            *pLocator = NULL;
	IWbemServices           *pNamespace = NULL;
	IEnumWbemClassObject    *pEnumSMBIOS = NULL;
	IWbemClassObject        *pSmbios = NULL;
	CIMTYPE                 type;
	VARIANT                 pVal;
	SAFEARRAY               *pArray = NULL;
	smbiosHeader            *smbiosData;
	u_char                  *uuidPtr;
	DWORD                   smbufSize;

	hr =  CoInitializeEx(0, COINIT_MULTITHREADED);
	if (! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"readSystemUUID: failed to initialize COM");
		gotData = NO;
		goto Cleanup;
	}
	
	hr =  CoInitializeSecurity(NULL,-1,NULL,NULL,RPC_C_AUTHN_LEVEL_DEFAULT,RPC_C_IMP_LEVEL_IMPERSONATE,NULL,EOAC_NONE,NULL);
	hr = CoCreateInstance( CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLocator );
	if(! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"readSystemUUID: failed to create WMI instance");
		gotData = NO;
		goto Cleanup;
	}

	hr = pLocator->ConnectServer(path, NULL, NULL, NULL, 0, NULL, NULL, &pNamespace );
	pLocator->Release();
	if( WBEM_S_NO_ERROR != hr ){
		myLog(LOG_ERR,"getSystemUUID: ConnectServer() failed for namespace");
		gotData = NO;
		goto Cleanup;
	}

	hr = pNamespace->CreateInstanceEnum(className, 0, NULL, &pEnumSMBIOS );
	pNamespace->Release();
	if (! SUCCEEDED( hr ) ){
		myLog(LOG_ERR,"getSystemUUID: CreateInstanceEnum() failed for MSSmBios_RawSMBiosTables");
		gotData = NO;
		goto Cleanup;
	}

	hr = pEnumSMBIOS->Next(4000, 1, &pSmbios, &uReturned );
	pEnumSMBIOS->Release();
	if ( 1 != uReturned ){
		myLog(LOG_ERR,"getSystemUUID: Next() failed for pEnumSMBIOS");
		gotData = NO;
		goto Cleanup;
	}
	
	pSmbios->Get(propName,0L,&pVal,&type,NULL);
	if ( ( VT_UI1 | VT_ARRAY) != pVal.vt){
		myLog(LOG_ERR,"getSystemUUID: Get() failed for pSmbios");
	    gotData = NO;
		goto Cleanup;
	}

	pArray = V_ARRAY(&pVal);
	smbufSize = pArray->rgsabound[0].cElements;
	smbiosData = (smbiosHeader*)my_calloc(smbufSize);
	if(!smbiosData){
		myLog(LOG_ERR,"getSystemUUID: failed to allocate buffer for smbiosData");
		gotData = NO;
		goto Cleanup;
	}
	memcpy((void*)smbiosData,pArray->pvData,smbufSize);
	uuidPtr = (u_char*)getUUIDPtr(smbufSize,smbiosData);
	if(!uuidPtr){
		myLog(LOG_ERR,"getSystemUUID: failed to find UUID in SMBIOS");
		gotData = NO;
		goto Cleanup;
	}
	memcpy((void*)uuidbuf,uuidPtr,16);
	gotData = YES;

Cleanup:
	SysFreeString(propName);
	SysFreeString(className);
	SysFreeString(path);
	if(smbiosData) my_free(smbiosData);

	return gotData;
}