Beispiel #1
0
static int __init nddebug_setup(char *str)
{
    get_option(&str, &nm_dbg_level);
    return 1;
}
Beispiel #2
0
static int __init cachesize_setup(char *str)
{
    get_option(&str, &cachesize_override);
    return 1;
}
static int __init loglevel(char *str)
{
	get_option(&str, &console_loglevel);
	return 0;
}
static int __init getskuid(char *str)
{
	get_option(&str, &skuid);
	printk(KERN_INFO "\n[disp] skuid = %d\n", skuid);
	return 0;
}
Beispiel #5
0
void 
dhcpleasequery(struct packet *packet, int ms_nulltp) {
	char msgbuf[256];
	char dbg_info[128];
	struct iaddr cip;
	struct iaddr gip;
	struct data_string uid;
	struct hardware h;
	struct lease *tmp_lease;
	struct lease *lease;
	int want_associated_ip;
	int assoc_ip_cnt;
	u_int32_t assoc_ips[40];  /* XXXSK: arbitrary maximum number of IPs */
	const int nassoc_ips = sizeof(assoc_ips) / sizeof(assoc_ips[0]);

	unsigned char dhcpMsgType;
	const char *dhcp_msg_type_name;
	struct subnet *subnet;
	struct option_state *options;
	struct option_cache *oc;
	int allow_leasequery;
	int ignorep;
	u_int32_t lease_duration;
	u_int32_t time_renewal;
	u_int32_t time_rebinding;
	u_int32_t time_expiry;
	u_int32_t client_last_transaction_time;
	struct sockaddr_in to;
	struct in_addr siaddr;
	struct data_string prl;
	struct data_string *prl_ptr;

	int i;
	struct interface_info *interface;

	/* INSIST(packet != NULL); */

	/*
	 * Prepare log information.
	 */
	snprintf(msgbuf, sizeof(msgbuf), 
		"DHCPLEASEQUERY from %s", inet_ntoa(packet->raw->giaddr));

	/* 
	 * We can't reply if there is no giaddr field.
	 */
	if (!packet->raw->giaddr.s_addr) {
		log_debug("%s: missing giaddr, ciaddr is %s, no reply sent", 
			 msgbuf, inet_ntoa(packet->raw->ciaddr));
		return;
	}

	/* 
	 * Set up our options, scope, and, um... stuff.
	 * This is basically copied from dhcpinform() in dhcp.c.
	 */
	gip.len = sizeof(packet->raw->giaddr);
	memcpy(gip.iabuf, &packet->raw->giaddr, sizeof(packet->raw->giaddr));

	subnet = NULL;
	find_subnet(&subnet, gip, MDL);
	if (subnet == NULL) {
		log_error("%s: unknown subnet for address %s", 
			 msgbuf, piaddr(gip));
		return;
	}

	options = NULL;
	if (!option_state_allocate(&options, MDL)) {
		subnet_dereference(&subnet, MDL);
		log_error("No memory for option state.");
		log_debug("%s: out of memory, no reply sent", msgbuf);
		return;
	}

	execute_statements_in_scope(NULL,
				    packet,
				    NULL,
				    NULL,
				    packet->options,
				    options,
				    &global_scope,
				    subnet->group,
				    NULL);
	for (i=packet->class_count-1; i>=0; i--) {
		execute_statements_in_scope(NULL,
					    packet,
					    NULL,
					    NULL,
					    packet->options,
					    options,
					    &global_scope,
					    packet->classes[i]->group,
					    subnet->group);
	}

	subnet_dereference(&subnet, MDL);

	/* 
	 * Because LEASEQUERY has some privacy concerns, default to deny.
	 */
	allow_leasequery = 0;

	/*
	 * See if we are authorized to do LEASEQUERY.
	 */
	oc = lookup_option(&server_universe, options, SV_LEASEQUERY);
	if (oc != NULL) {
		allow_leasequery = evaluate_boolean_option_cache(&ignorep,
					 packet, NULL, NULL, packet->options,
					 options, &global_scope, oc, MDL);
	}

	if (!allow_leasequery) {
		log_debug("%s: LEASEQUERY not allowed, query ignored", msgbuf);
		option_state_dereference(&options, MDL);
		return;
	}
	    

	/* 
	 * Copy out the client IP address.
	 */
	cip.len = sizeof(packet->raw->ciaddr);
	memcpy(cip.iabuf, &packet->raw->ciaddr, sizeof(packet->raw->ciaddr));

	/* 
	 * If the client IP address is valid (not all zero), then we 
	 * are looking for information about that IP address.
	 */
	assoc_ip_cnt = 0;
	lease = tmp_lease = NULL;
	if (memcmp(cip.iabuf, "\0\0\0", 4)) {

		want_associated_ip = 0;

		snprintf(dbg_info, sizeof(dbg_info), "IP %s", piaddr(cip));
		find_lease_by_ip_addr(&lease, cip, MDL);


	} else {

		want_associated_ip = 1;

		/*
		 * If the client IP address is all zero, then we will
		 * either look up by the client identifier (if we have
		 * one), or by the MAC address.
		 */

		memset(&uid, 0, sizeof(uid));
		if (get_option(&uid, 
			       &dhcp_universe,
			       packet,
			       NULL,
			       NULL,
			       packet->options,
			       NULL,
			       packet->options, 
			       &global_scope,
			       DHO_DHCP_CLIENT_IDENTIFIER,
			       MDL)) {

			snprintf(dbg_info, 
				 sizeof(dbg_info), 
				 "client-id %s",
				 print_hex_1(uid.len, uid.data, 60));

			find_lease_by_uid(&tmp_lease, uid.data, uid.len, MDL);
			data_string_forget(&uid, MDL);
			get_newest_lease(&lease, tmp_lease, next_uid);
			assoc_ip_cnt = get_associated_ips(tmp_lease,
							  next_uid, 
							  lease,
							  assoc_ips, 
							  nassoc_ips);

		} else {

			if (packet->raw->hlen+1 > sizeof(h.hbuf)) {
				log_info("%s: hardware length too long, "
					 "no reply sent", msgbuf);
				option_state_dereference(&options, MDL);
				return;
			}

			h.hlen = packet->raw->hlen + 1;
			h.hbuf[0] = packet->raw->htype;
			memcpy(&h.hbuf[1], 
			       packet->raw->chaddr, 
			       packet->raw->hlen);

			snprintf(dbg_info, 
				 sizeof(dbg_info), 
				 "MAC address %s",
				 print_hw_addr(h.hbuf[0], 
					       h.hlen - 1, 
					       &h.hbuf[1]));

			find_lease_by_hw_addr(&tmp_lease, h.hbuf, h.hlen, MDL);
			get_newest_lease(&lease, tmp_lease, next_hw);
			assoc_ip_cnt = get_associated_ips(tmp_lease,
							  next_hw, 
							  lease,
							  assoc_ips, 
							  nassoc_ips);

		}

		lease_dereference(&tmp_lease, MDL);

		if (lease != NULL) {
			memcpy(&packet->raw->ciaddr, 
			       lease->ip_addr.iabuf,
			       sizeof(packet->raw->ciaddr));
		}

		/*
		 * Log if we have too many IP addresses associated
		 * with this client.
		 */
		if (want_associated_ip && (assoc_ip_cnt > nassoc_ips)) {
			log_debug("%d IP addresses associated with %s, "
				 "only %d sent in reply.",
				 assoc_ip_cnt, dbg_info, nassoc_ips);
		}
	}

	/*
	 * We now know the query target too, so can report this in 
	 * our log message.
	 */
	snprintf(msgbuf, sizeof(msgbuf), 
		"DHCPLEASEQUERY from %s for %s",
		inet_ntoa(packet->raw->giaddr), dbg_info);

	/*
	 * Figure our our return type.
	 */
	if (lease == NULL) {
		dhcpMsgType = DHCPLEASEUNKNOWN;
		dhcp_msg_type_name = "DHCPLEASEUNKNOWN";
	} else {
		if (lease->binding_state == FTS_ACTIVE) {
			dhcpMsgType = DHCPLEASEACTIVE;
			dhcp_msg_type_name = "DHCPLEASEACTIVE";
		} else {
			dhcpMsgType = DHCPLEASEUNASSIGNED;
			dhcp_msg_type_name = "DHCPLEASEUNASSIGNED";
		}
	}

	/* 
	 * Set options that only make sense if we have an active lease.
	 */

	if (dhcpMsgType == DHCPLEASEACTIVE)
	{

		/* 
		 * Set the hardware address fields.
		 */

		packet->raw->hlen = lease->hardware_addr.hlen - 1;
		packet->raw->htype = lease->hardware_addr.hbuf[0];
		memcpy(packet->raw->chaddr, 
		       &lease->hardware_addr.hbuf[1], 
		       sizeof(packet->raw->chaddr));

		/*
		 * Set client identifier option.
		 */
		if (lease->uid_len > 0) {
			if (!add_option(options,
					DHO_DHCP_CLIENT_IDENTIFIER,
					lease->uid,
					lease->uid_len)) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}


		/*
		 * Calculate T1 and T2, the times when the client
		 * tries to extend its lease on its networking
		 * address.
		 * These seem to be hard-coded in ISC DHCP, to 0.5 and
		 * 0.875 of the lease time.
		 */

		lease_duration = lease->ends - lease->starts;
		time_renewal = lease->starts + 
			(lease_duration / 2);
		time_rebinding = lease->starts + 
			(lease_duration / 2) +
			(lease_duration / 4) +
			(lease_duration / 8);

		if (time_renewal > cur_time) {
			time_renewal = htonl(time_renewal - cur_time);
			if (!add_option(options, 
					DHO_DHCP_RENEWAL_TIME,
					&time_renewal, 
					sizeof(time_renewal))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}

		if (time_rebinding > cur_time) {
			time_rebinding = htonl(time_rebinding - cur_time);
			if (!add_option(options, 
					DHO_DHCP_REBINDING_TIME,
					&time_rebinding, 
					sizeof(time_rebinding))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}

		if (lease->ends > cur_time) {
			time_expiry = htonl(lease->ends - cur_time);
			if (!add_option(options, 
					DHO_DHCP_LEASE_TIME,
					&time_expiry, 
					sizeof(time_expiry))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}


		/*
		 * Set the relay agent info.
		 */

		if (lease->agent_options != NULL) {
			int idx = agent_universe.index;
			struct option_chain_head **tmp1 = 
				(struct option_chain_head **)
				&(options->universes[idx]);
				struct option_chain_head *tmp2 = 
				(struct option_chain_head *)
				lease->agent_options;

			option_chain_head_reference(tmp1, tmp2, MDL);
		}

		/* 
	 	 * Set the client last transaction time.
		 * We check to make sure we have a timestamp. For
		 * lease files that were saved before running a 
		 * timestamp-aware version of the server, this may
		 * not be set.
	 	 */

		if (lease->cltt != MIN_TIME) {
			if (cur_time > lease->cltt) {
				client_last_transaction_time = 
					htonl(cur_time - lease->cltt);
			} else {
				client_last_transaction_time = htonl(0);
			}
			if (!add_option(options, 
					DHO_CLIENT_LAST_TRANSACTION_TIME,
					&client_last_transaction_time,
		     			sizeof(client_last_transaction_time))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}

		/*
	 	 * Set associated IPs, if requested and there are some.
	 	 */
		if (want_associated_ip && (assoc_ip_cnt > 0)) {
			if (!add_option(options, 
					DHO_ASSOCIATED_IP,
					assoc_ips,
					assoc_ip_cnt * sizeof(assoc_ips[0]))) {
				option_state_dereference(&options, MDL);
				lease_dereference(&lease, MDL);
				log_info("%s: out of memory, no reply sent",
					 msgbuf);
				return;
			}
		}
	}

	/* 
	 * Set the message type.
	 */

	packet->raw->op = BOOTREPLY;

	/*
	 * Set DHCP message type.
	 */
	if (!add_option(options, 
		        DHO_DHCP_MESSAGE_TYPE,
		        &dhcpMsgType, 
			sizeof(dhcpMsgType))) {
		option_state_dereference(&options, MDL);
		lease_dereference(&lease, MDL);
		log_info("%s: error adding option, no reply sent", msgbuf);
		return;
	}

	/*
	 * Log the message we've received.
	 */
	log_debug("%s", msgbuf);

	/*
	 * Figure out which address to use to send from.
	 */
	get_server_source_address(&siaddr, options, packet);

	/* 
	 * Set up the option buffer.
	 */

	memset(&prl, 0, sizeof(prl));
	oc = lookup_option(&dhcp_universe, options, 
			   DHO_DHCP_PARAMETER_REQUEST_LIST);
	if (oc != NULL) {
		evaluate_option_cache(&prl, 
				      packet, 
				      NULL,
				      NULL,
				      packet->options,
				      options,
				      &global_scope,
				      oc,
				      MDL);
	}
	if (prl.len > 0) {
		prl_ptr = &prl;
	} else {
		prl_ptr = NULL;
	}

	packet->packet_length = cons_options(packet, 
					     packet->raw, 
					     lease,
					     NULL,
					     0,
					     packet->options,
					     options,
					     &global_scope,
					     0,
					     0,
					     0, 
					     prl_ptr,
					     NULL);

	data_string_forget(&prl, MDL);	/* SK: safe, even if empty */
	option_state_dereference(&options, MDL);
	lease_dereference(&lease, MDL);

	to.sin_family = AF_INET;
#ifdef HAVE_SA_LEN
	to.sin_len = sizeof(to);
#endif
	memset(to.sin_zero, 0, sizeof(to.sin_zero));

	/* 
	 * Leasequery packets are be sent to the gateway address.
	 */
	to.sin_addr = packet->raw->giaddr;
	if (packet->raw->giaddr.s_addr != htonl(INADDR_LOOPBACK)) {
		to.sin_port = local_port;
	} else {
		to.sin_port = remote_port; /* XXXSK: For debugging. */
	}

	/* 
	 * The fallback_interface lets us send with a real IP
	 * address. The packet interface sends from all-zeros.
	 */
	if (fallback_interface != NULL) {
		interface = fallback_interface;
	} else {
		interface = packet->interface;
	}

	/*
	 * Report what we're sending.
	 */
		log_debug("%s to %s for %s (%d associated IPs)",
		dhcp_msg_type_name, 
		inet_ntoa(to.sin_addr), dbg_info, assoc_ip_cnt);

	send_packet(interface,
		    NULL,
		    packet->raw, 
		    packet->packet_length,
		    siaddr,
		    &to,
		    NULL);
}
Beispiel #6
0
/*
* SB600 enables all USB controllers by default in SMBUS Control.
* SB600 enables SATA by default in SMBUS Control.
*/
static void sm_init(device_t dev)
{
	u8 byte;
	u8 byte_old;
	u32 dword;
	u32 ioapic_base;
	u32 on;
	u32 nmi_option;

	printk(BIOS_INFO, "sm_init().\n");

	ioapic_base = pci_read_config32(dev, 0x74) & (0xffffffe0);	/* some like mem resource, but does not have  enable bit */
	/* Don't rename APIC ID */
	clear_ioapic(ioapic_base);

	dword = pci_read_config8(dev, 0x62);
	dword |= 1 << 2;
	pci_write_config8(dev, 0x62, dword);

	dword = pci_read_config32(dev, 0x78);
	dword |= 1 << 9;
	pci_write_config32(dev, 0x78, dword);	/* enable 0xCD6 0xCD7 */

	/* bit 10: MultiMediaTimerIrqEn */
	dword = pci_read_config8(dev, 0x64);
	dword |= 1 << 10;
	pci_write_config8(dev, 0x64, dword);
	/* enable serial irq */
	byte = pci_read_config8(dev, 0x69);
	byte |= 1 << 7;		/* enable serial irq function */
	byte &= ~(0xF << 2);
	byte |= 4 << 2;		/* set NumSerIrqBits=4 */
	pci_write_config8(dev, 0x69, byte);

	byte = pm_ioread(0x61);
	byte |= 1 << 1;		/* Set to enable NB/SB handshake during IOAPIC interrupt for AMD K8/K7 */
	pm_iowrite(0x61, byte);

	/* disable SMI */
	byte = pm_ioread(0x53);
	byte |= 1 << 3;
	pm_iowrite(0x53, byte);

	/* power after power fail */
	on = CONFIG_MAINBOARD_POWER_ON_AFTER_POWER_FAIL;
	get_option(&on, "power_on_after_fail");
	byte = pm_ioread(0x74);
	byte &= ~0x03;
	if (on) {
		byte |= 1 << 0;
	}
	byte |= 1 << 2;
	pm_iowrite(0x74, byte);
	printk(BIOS_INFO, "set power %s after power fail\n", on ? "on" : "off");

	/* sb600 rpr:2.3.3: */
	byte = pm_ioread(0x9A);
	byte |= 1 << 5 | 1 << 4 | 1 << 2;
	pm_iowrite(0x9A, byte);

	byte = pm_ioread(0x8F);
	byte |= 1 << 5;
	byte &= ~(1 << 4);
	pm_iowrite(0x8F, byte);

	pm_iowrite(0x8B, 0x01);
	pm_iowrite(0x8A, 0x90);
	pm_iowrite(0x88, 0x10);	/* A21 */

	byte = pm_ioread(0x7C);
	byte |= 1 << 0;
	pm_iowrite(0x7C, byte);

	byte = pm_ioread(0x68);
	byte &= ~(1 << 1);
	/* 2.6 */
	byte |= 1 << 2;
	pm_iowrite(0x68, byte);

	/* 2.6 */
	byte = pm_ioread(0x65);
	byte &= ~(1 << 7);
	pm_iowrite(0x65, byte);

	/* 2.3.4 */
	byte = pm_ioread(0x52);
	byte &= ~0x2F;
	byte |= 0x8;
	pm_iowrite(0x52, byte);

	byte = pm_ioread(0x8D);
	byte &= ~(1 << 6);
	pm_iowrite(0x8D, byte);

	byte = pm_ioread(0x61);
	byte &= ~(1 << 2);
	pm_iowrite(0x61, byte);

	byte = pm_ioread(0x42);
	byte &= ~(1 << 2);
	pm_iowrite(0x42, byte);

	/* Set up NMI on errors */
	byte = inb(0x70);	/* RTC70 */
	byte_old = byte;
	nmi_option = NMI_OFF;
	get_option(&nmi_option, "nmi");
	if (nmi_option) {
		byte &= ~(1 << 7);	/* set NMI */
		printk(BIOS_INFO, "++++++++++set NMI+++++\n");
	} else {
		byte |= (1 << 7);	/* Can not mask NMI from PCI-E and NMI_NOW */
		printk(BIOS_INFO, "++++++++++no set NMI+++++\n");
	}
	byte &= ~(1 << 7);
	if (byte != byte_old) {
		outb(byte, 0x70);
	}

	/* 2.10 IO Trap Settings */
	abcfg_reg(0x10090, 1 << 16, 1 << 16);

	/* ab index */
	pci_write_config32(dev, 0xF0, AB_INDX);
	/* Initialize the real time clock */
	cmos_init(0);

	/*3.4 Enabling IDE/PCIB Prefetch for Performance Enhancement */
	abcfg_reg(0x10060, 9 << 17, 9 << 17);
	abcfg_reg(0x10064, 9 << 17, 9 << 17);

	/* 3.5 Enabling OHCI Prefetch for Performance Enhancement */
	abcfg_reg(0x80, 1 << 0, 1<< 0);

	/* 3.6 B-Link Client's Credit Variable Settings for the Downstream Arbitration Equation */
	/* 3.7 Enabling Additional Address Bits Checking in Downstream */
	abcfg_reg(0x9c, 3 << 0, 3 << 0);

	/* 3.8 Set B-Link Prefetch Mode */
	abcfg_reg(0x80, 3 << 17, 3 << 17);

	/* 3.9 Enabling Detection of Upstream Interrupts */
	abcfg_reg(0x94, 1 << 20,1 << 20);

	/* 3.10: Enabling Downstream Posted Transactions to Pass Non-Posted
	 *  Transactions for the K8 Platform (for All Revisions) */
	abcfg_reg(0x10090, 1 << 8, 1 << 8);

	/* 3.11:Programming Cycle Delay for AB and BIF Clock Gating */
	/* 3.12: Enabling AB and BIF Clock Gating */
	abcfg_reg(0x10054, 0xFFFF0000, 0x1040000);
	abcfg_reg(0x54, 0xFF << 16, 4 << 16);
	printk(BIOS_INFO, "3.11, ABCFG:0x54\n");
	abcfg_reg(0x54, 1 << 24, 1 << 24);
	printk(BIOS_INFO, "3.12, ABCFG:0x54\n");
	abcfg_reg(0x98, 0x0000FF00, 0x00004700);

	/* 3.13:Enabling AB Int_Arbiter Enhancement (for All Revisions) */
	abcfg_reg(0x10054, 0x0000FFFF, 0x07FF);

	/* 3.14:Enabling L1 on A-link Express */
	axcfg_reg(0x68, 0x00000003, 0x2);
	axindxp_reg(0xa0, 0x0000F000, 0x6000);

	abcfg_reg(0x10098, 0xFFFFFFFF, 0x4000);
	abcfg_reg(0x04, 0xFFFFFFFF, 0x6);
	printk(BIOS_INFO, "sm_init() end\n");

	/* Enable NbSb virtual channel */
	axcfg_reg(0x114, 0x3f << 1, 0 << 1);
	axcfg_reg(0x120, 0x7f << 1, 0x7f << 1);
	axcfg_reg(0x120, 7 << 24, 1 << 24);
	axcfg_reg(0x120, 1 << 31, 1 << 31);
	abcfg_reg(0x50, 1 << 3, 1 << 3);
}
int main(int argc, char *argv[]) {
  char **av;
  char *fslfn, *ltafn;
  MRI *mri_src, *mri_tgt;
  int ac, nargs;
  LTA *mylta = 0;
  FILE *fo;
  VOL_GEOM srcG, dstG;
  MATRIX *invTgt, *Dsrc, *V_to_V;

  Progname = argv[0];

  nargs = handle_version_option (argc, argv, "$Id: mri_fslmat_to_lta.c,v 1.3 2011/03/02 00:04:15 nicks Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc != 5)
    usage(1);

  printf("Read source volume file %s\n", argv[1]);
  mri_src = MRIread(argv[1]) ;

  if (!mri_src)
    ErrorExit(ERROR_BADPARM, "%s: could not read source volume %s",
              Progname, argv[1]) ;

  printf("Read destination volume file %s\n", argv[2]);
  mri_tgt = MRIread(argv[2]) ;
  if (!mri_tgt)
    ErrorExit(ERROR_BADPARM, "%s: could not read label volume %s",
              Progname, argv[2]) ;

  fslfn = argv[3];
  ltafn = argv[4];

  printf("Read fsl transformation from file %s\n", fslfn);
  mylta = ltaFSLread(fslfn);

  getVolGeom(mri_src, &srcG);
  getVolGeom(mri_tgt, &dstG);

  if (invert_flag) {
    mylta->xforms[0].src = dstG;
    mylta->xforms[0].dst = srcG;
  } else {
    mylta->xforms[0].src = srcG;
    mylta->xforms[0].dst = dstG;
  }

  invTgt = MatrixAlloc(4,4,MATRIX_REAL);
  invTgt->rptr[1][1] = 1.0/dstG.xsize;
  invTgt->rptr[2][2] = 1.0/dstG.ysize;
  invTgt->rptr[3][3] = 1.0/dstG.zsize;
  invTgt->rptr[4][4] = 1.0;

  Dsrc = MatrixAlloc(4,4,MATRIX_REAL);
  Dsrc->rptr[1][1] = srcG.xsize;
  Dsrc->rptr[2][2] = srcG.ysize;
  Dsrc->rptr[3][3] = srcG.zsize;
  Dsrc->rptr[4][4] = 1.0;

  V_to_V = MatrixMultiply(invTgt, mylta->xforms[0].m_L, NULL);
  V_to_V = MatrixMultiply(V_to_V, Dsrc, V_to_V);

  if (invert_flag) {
    mylta->xforms[0].m_L = MatrixInverse(V_to_V, mylta->xforms[0].m_L);
  } else {
    mylta->xforms[0].m_L = MatrixCopy(V_to_V, mylta->xforms[0].m_L);
  }

  if (!mylta) {
    MRIfree(&mri_src);
    MRIfree(&mri_tgt);
    ErrorExit(ERROR_BADFILE, "%s: can't read in transformation",Progname);
  }

  printf("Write transformation to lta file %s\n", ltafn);
  fo = fopen(ltafn,"w");
  if (fo==NULL)
    ErrorExit(ERROR_BADFILE, "%s: can't create file %s",Progname, ltafn);

  LTAprint(fo, mylta);

  fclose(fo);


  MRIfree(&mri_src);
  MRIfree(&mri_tgt);

  LTAfree(&mylta);

  MatrixFree(&invTgt);
  MatrixFree(&Dsrc);
  MatrixFree(&V_to_V);

  return(0);

}  /*  end main()  */
Beispiel #8
0
static int __init fpaff_thresh(char *str)
{
	get_option(&str, &fpaff_threshold);
	return 1;
}
static int __init bootmode_setup(char *str)
{
	get_option(&str, &bootmode);
	return 1;
}
Beispiel #10
0
static int __init get_isp_volt(char *str)
{
	get_option(&str, &set_isp_volt);
	return 0;
}
Beispiel #11
0
/*
* SB700 enables all USB controllers by default in SMBUS Control.
* SB700 enables SATA by default in SMBUS Control.
*/
static void sm_init(device_t dev)
{
	u8 byte;
	u8 byte_old;
	u8 rev;
	u32 dword;
	void *ioapic_base;
	uint32_t power_state;
	u32 nmi_option;

	printk(BIOS_INFO, "sm_init().\n");

	rev = get_sb700_revision(dev);
	/* This works in a similar fashion to a memory resource, but without an enable bit */
	ioapic_base = (void *)(pci_read_config32(dev, 0x74) & (0xffffffe0));
	setup_ioapic(ioapic_base, 0); /* Don't rename IOAPIC ID. */

	/* 2.10 Interrupt Routing/Filtering */
	dword = pci_read_config8(dev, 0x62);
	dword |= 3;
	pci_write_config8(dev, 0x62, dword);

	/* Delay back to back interrupts to the CPU. */
	dword = pci_read_config16(dev, 0x64);
	dword |= 1 << 13;
	pci_write_config16(dev, 0x64, dword);

	/* rrg:K8 INTR Enable (BIOS should set this bit after PIC initialization) */
	/* rpr 2.1 Enabling Legacy Interrupt */
	dword = pci_read_config8(dev, 0x62);
	dword |= 1 << 2;
	pci_write_config8(dev, 0x62, dword);

	dword = pci_read_config32(dev, 0x78);
	dword |= 1 << 9;
	pci_write_config32(dev, 0x78, dword);	/* enable 0xCD6 0xCD7 */

	/* bit 10: MultiMediaTimerIrqEn */
	dword = pci_read_config8(dev, 0x64);
	dword |= 1 << 10;
	pci_write_config8(dev, 0x64, dword);
	/* enable serial irq */
	byte = pci_read_config8(dev, 0x69);
	byte |= 1 << 7;		/* enable serial irq function */
	byte &= ~(0xF << 2);
	byte |= 4 << 2;		/* set NumSerIrqBits=4 */
	pci_write_config8(dev, 0x69, byte);

	/* Sx State Settings
	 * Note: These 2 registers need to be set correctly for the S-state
	 * to work properly. Otherwise the system may hang during resume
	 * from the S-state.
	 */
	/*Use 8us clock for delays in the S-state resume timing sequence.*/
	byte = pm_ioread(0x65);
	byte &= ~(1 << 7);
	pm_iowrite(0x65, byte);
	/* Delay the APIC interrupt to the CPU until the system has fully resumed from the S-state. */
	byte = pm_ioread(0x68);
	byte |= 1 << 2;
	pm_iowrite(0x68, byte);

	/* IRQ0From8254 */
	byte = pci_read_config8(dev, 0x41);
	byte &= ~(1 << 7);
	pci_write_config8(dev, 0x41, byte);

	byte = pm_ioread(0x61);
	if (IS_ENABLED(CONFIG_CPU_AMD_MODEL_10XXX))
		byte &= ~(1 << 1);	/* Clear for non-K8 CPUs */
	else
		byte |= 1 << 1;		/* Set to enable NB/SB handshake during IOAPIC interrupt for AMD K8/K7 */
	pm_iowrite(0x61, byte);

	/* disable SMI */
	byte = pm_ioread(0x53);
	byte |= 1 << 3;
	pm_iowrite(0x53, byte);

	/* power after power fail */
	power_state = CONFIG_MAINBOARD_POWER_ON_AFTER_POWER_FAIL;
	get_option(&power_state, "power_on_after_fail");
	if (power_state > 2) {
		printk(BIOS_WARNING, "Invalid power_on_after_fail setting, using default\n");
		power_state = CONFIG_MAINBOARD_POWER_ON_AFTER_POWER_FAIL;
	}
	byte = pm_ioread(0x74);
	byte &= ~0x03;
	if (power_state == POWER_MODE_OFF)
		byte |= 0x0;
	else if (power_state == POWER_MODE_ON)
		byte |= 0x1;
	else if (power_state == POWER_MODE_LAST)
		byte |= 0x2;
	byte |= 1 << 2;
	pm_iowrite(0x74, byte);
	printk(BIOS_INFO, "set power \"%s\" after power fail\n", power_mode_names[power_state]);

	byte = pm_ioread(0x68);
	byte &= ~(1 << 1);
	/* 2.7 */
	byte |= 1 << 2;
	pm_iowrite(0x68, byte);

	/* 2.7 */
	byte = pm_ioread(0x65);
	byte &= ~(1 << 7);
	pm_iowrite(0x65, byte);

	/* 2.16 */
	byte = pm_ioread(0x55);
	byte |= 1 << 5;
	pm_iowrite(0x55, byte);

	byte = pm_ioread(0xD7);
	byte |= 1 << 6 | 1 << 1;
	pm_iowrite(0xD7, byte);

	/* 2.15 */
	byte = pm_ioread(0x42);
	byte &= ~(1 << 2);
	pm_iowrite(0x42, byte);

	/* Set up NMI on errors */
	byte = inb(0x70);	/* RTC70 */
	byte_old = byte;
	nmi_option = NMI_OFF;
	get_option(&nmi_option, "nmi");
	if (nmi_option) {
		byte &= ~(1 << 7);	/* set NMI */
		printk(BIOS_INFO, "++++++++++set NMI+++++\n");
	} else {
		byte |= (1 << 7);	/* Can not mask NMI from PCI-E and NMI_NOW */
		printk(BIOS_INFO, "++++++++++no set NMI+++++\n");
	}
	byte &= ~(1 << 7);
	if (byte != byte_old) {
		outb(byte, 0x70);
	}

	/*rpr v2.13  2.22 SMBUS PCI Config */
 	byte = pci_read_config8(dev, 0xE1);
	if ((REV_SB700_A11 == rev) || REV_SB700_A12 == rev) {
		byte |= 1 << 0;
	}
	/*Set bit2 to 1, enable Io port 60h read/write SMi trapping and
	 *Io port 64h write Smi trapping. conflict with ps2 keyboard
	 */
	//byte |= 1 << 2 | 1 << 3 | 1 << 4;
	byte |= 1 << 3 | 1 << 4;
 	pci_write_config8(dev, 0xE1, byte);

	/* 2.5 Enabling Non-Posted Memory Write */
       	axindxc_reg(0x10, 1 << 9, 1 << 9);

	/* 2.11 IO Trap Settings */
	abcfg_reg(0x10090, 1 << 16, 1 << 16);

	/* ab index */
	pci_write_config32(dev, 0xF0, AB_INDX);
	/* Initialize the real time clock */
	cmos_init(0);

	/* 4.3 Enabling Upstream DMA Access */
	axcfg_reg(0x04, 1 << 2, 1 << 2);
	/* 4.4 Enabling IDE/PCIB Prefetch for Performance Enhancement */
	abcfg_reg(0x10060, 9 << 17, 9 << 17);
	abcfg_reg(0x10064, 9 << 17, 9 << 17);

	/* 4.5 Enabling OHCI Prefetch for Performance Enhancement, A12 */
	abcfg_reg(0x80, 1 << 0, 1<< 0);

	/* 4.6 B-Link Client's Credit Variable Settings for the Downstream Arbitration Equation */
	/* 4.7 Enabling Additional Address Bits Checking in Downstream */
	/* 4.16 IO write and SMI ordering enhancement*/
	abcfg_reg(0x9c, 3 << 0, 3 << 0);
	if (REV_SB700_A12 == rev) {
		abcfg_reg(0x9c, 1 << 8, 1 << 8);
	} else if (rev >= REV_SB700_A14) {
		abcfg_reg(0x9c, 1 << 8, 0 << 8);
	}
	if (REV_SB700_A15 == rev) {
		abcfg_reg(0x90, 1 << 21, 1 << 21);
		abcfg_reg(0x9c, 1 << 5 | 1 << 9 | 1 << 15, 1 << 5 | 1 << 9 | 1 << 15);
	}

	/* 4.8 Set B-Link Prefetch Mode */
	abcfg_reg(0x80, 3 << 17, 3 << 17);

	/* 4.9 Enabling Detection of Upstream Interrupts */
	abcfg_reg(0x94, 1 << 20 | 0x7FFFF, 1 << 20 | 0x00FEE);

	/* 4.10: Enabling Downstream Posted Transactions to Pass Non-Posted
	 *  Transactions for the K8 Platform (for All Revisions) */
	abcfg_reg(0x10090, 1 << 8, 1 << 8);

	/* Set ACPI Software clock Throttling Period to 244 us*/
	byte = pm_ioread(0x68);
	byte &= ~(3 << 6);
	byte |= (2 << 6);	/* 244us */
	pm_iowrite(0x68, byte);

	if (REV_SB700_A15 == rev) {
		u16 word;

		/* rpr v2.13 4.18 Enabling Posted Pass Non-Posted Downstream */
        	axindxc_reg(0x02, 1 << 9, 1 << 9);
		abcfg_reg(0x9C, 0x00007CC0, 0x00007CC0);
		abcfg_reg(0x1009C, 0x00000030, 0x00000030);
		abcfg_reg(0x10090, 0x00001E00, 0x00001E00);

		/* rpr v2.13 4.19 Enabling Posted Pass Non-Posted Upstream */
		abcfg_reg(0x58, 0x0000F800, 0x0000E800);

		/* rpr v2.13 4.20 64 bit Non-Posted Memory Write Support */
        	axindxc_reg(0x02, 1 << 10, 1 << 10);

		/* rpr v2.13 2.38 Unconditional Shutdown */
 		byte = pci_read_config8(dev, 0x43);
		byte &= ~(1 << 3);
 		pci_write_config8(dev, 0x43, byte);

		word = pci_read_config16(dev, 0x38);
		word |= 1 << 12;
 		pci_write_config16(dev, 0x38, word);

		byte |= 1 << 3;
 		pci_write_config8(dev, 0x43, byte);

		/* Enable southbridge MMIO decode */
		dword = pci_read_config32(dev, SB_MMIO_CFG_REG);
		dword &= ~(0xffffff << 8);
		dword |= SB_MMIO_BASE_ADDRESS;
		dword |= 0x1;
		pci_write_config32(dev, SB_MMIO_CFG_REG, dword);
	}
	//ACPI_DISABLE_TIMER_IRQ_ENHANCEMENT_FOR_8254_TIMER
 	byte = pci_read_config8(dev, 0xAE);
	byte |= 1 << 5;
 	pci_write_config8(dev, 0xAE, byte);

	/* 4.11:Programming Cycle Delay for AB and BIF Clock Gating */
	/* 4.12: Enabling AB and BIF Clock Gating */
	abcfg_reg(0x10054, 0xFFFF0000, 0x1040000);
	abcfg_reg(0x54, 0xFF << 16, 4 << 16);
	abcfg_reg(0x54, 1 << 24, 0 << 24);
	abcfg_reg(0x98, 0x0000FF00, 0x00004700);

	/* 4.13:Enabling AB Int_Arbiter Enhancement (for All Revisions) */
	abcfg_reg(0x10054, 0x0000FFFF, 0x07FF);

	/* 4.14:Enabling Requester ID for upstream traffic. */
	abcfg_reg(0x98, 1 << 16, 1 << 16);

	/* 9.2: Enabling IDE Data Bus DD7 Pull Down Resistor */
	byte = pm2_ioread(0xE5);
	byte |= 1 << 2;
	pm2_iowrite(0xE5, byte);

	/* Enable IDE controller. */
	byte = pm_ioread(0x59);
	byte &= ~(1 << 1);
	pm_iowrite(0x59, byte);

	/* Enable SCI as irq9. */
	outb(0x4, 0xC00);
	outb(0x9, 0xC01);

	printk(BIOS_INFO, "sm_init() end\n");

	/* Enable NbSb virtual channel */
	axcfg_reg(0x114, 0x3f << 1, 0 << 1);
	axcfg_reg(0x120, 0x7f << 1, 0x7f << 1);
	axcfg_reg(0x120, 7 << 24, 1 << 24);
	axcfg_reg(0x120, 1 << 31, 1 << 31);
	abcfg_reg(0x50, 1 << 3, 1 << 3);
}
Beispiel #12
0
int
main(int argc, char *argv[]) {
  int          ac, nargs ;
  char         **av, *cp, surf_name[100], *hemi, *subject_name, *label_name,
               *out_fname ;
  MRI_SURFACE  *mris ;
  LABEL        *label ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: label2patch.c,v 1.7 2016/12/10 22:57:39 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  /* read in command-line options */
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }
  
  if (argc < 4)
    print_usage() ;

  subject_name = argv[1] ;
  hemi = argv[2] ;
  label_name = argv[3] ;
  out_fname = argv[4] ;

  if (strlen(subjects_dir) == 0)
  {
    cp = getenv("SUBJECTS_DIR") ;
    if (!cp)
      ErrorExit(ERROR_BADPARM, "no subjects directory in environment.\n") ;
    strcpy(subjects_dir, cp) ;
  }

  sprintf(surf_name,"%s/%s/surf/%s.%s",subjects_dir,subject_name,hemi,surface);
  fprintf(stderr, "reading %s...\n", surf_name) ;
  mris = MRISread(surf_name) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s\n",
              surf_name) ;
  MRIScomputeMetricProperties(mris) ;
  label = LabelRead(subject_name, label_name) ;
  if (ndilate)
    LabelDilate(label, mris, ndilate, CURRENT_VERTICES) ;
  if (nerode)
    LabelErode(label, mris, nerode) ;
  if (nclose)
  {
    LabelDilate(label, mris, nclose, CURRENT_VERTICES) ;
    LabelErode(label, mris, nclose) ;
  }

  LabelRipRestOfSurface(label, mris) ;
  MRISripFaces(mris) ;
  if (writesurf)
  {
     MRISwrite(mris, out_fname) ;
  }
  else
     MRISwritePatch(mris, out_fname) ;

  if (verbose)
    fprintf(stderr, "done.\n") ;
  exit(0) ;
  return(0) ;  /* ansi */
}
int
main(int argc, char *argv[])
{
  char        **av, *out_name ;
  int          ac, nargs ;
  int          msec, minutes, seconds ;
  struct timeb start ;
  MRI_SURFACE  *mris ;
  GCA_MORPH    *gcam ;
  MRI          *mri = NULL ;

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: mris_interpolate_warp.c,v 1.5 2011/10/07 12:07:26 fischl Exp $", "$Name:  $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  TimerStart(&start) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
  {
    usage_exit(1) ;
  }


  /*
    note that a "forward" morph means a retraction, so we reverse the order of the argvs here.
    This means that for every voxel in the inflated image we have a vector that points to where in
    the original image it came from, and *NOT* the reverse.
  */
  mris = MRISread(argv[2]) ;
  if (mris == NULL)
    ErrorExit(ERROR_NOFILE, "%s: could not read source surface %s\n", Progname,argv[2]) ;

  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
  if (MRISreadVertexPositions(mris, argv[1]) != NO_ERROR)
    ErrorExit(ERROR_NOFILE, "%s: could not read target surface %s\n", Progname,argv[1]) ;

  if (like_vol_name == NULL)
  {
    mri = MRIallocSequence(mris->vg.width, mris->vg.height, mris->vg.depth, MRI_FLOAT, 3) ;
    MRIcopyVolGeomToMRI(mri, &mris->vg) ;
  }
  else
  {
    MRI *mri_tmp ;
    mri_tmp = MRIread(like_vol_name) ;
    if (mri_tmp == NULL)
    {
      ErrorExit(ERROR_NOFILE, "%s: could not like volume %s\n", like_vol_name) ;
    }
    mri = MRIallocSequence(mri_tmp->width, mri_tmp->height, mri_tmp->depth, MRI_FLOAT, 3) ;
    MRIcopyHeader(mri_tmp, mri) ;
    MRIfree(&mri_tmp) ;
  }
  if (Gdiag & DIAG_SHOW && DIAG_VERBOSE_ON)
  {
    double xv, yv, zv ;
    VERTEX *v = &mris->vertices[0] ;
    MRISsurfaceRASToVoxel(mris, mri, v->x, v->y, v->z, &xv, &yv, &zv) ;
    printf("v 0: sras (%f, %f, %f) --> vox (%f, %f, %f)\n", v->x,v->y,v->z,xv,yv,zv);
    MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xv, &yv, &zv) ;
    printf("v 0: sras (%f, %f, %f) --> vox (%f, %f, %f)\n", v->x,v->y,v->z,xv,yv,zv);
    DiagBreak() ;
  }
  {
    MRI *mri_tmp ;
    mri_tmp = expand_mri_to_fit_surface(mris, mri) ;
    MRIfree(&mri) ; mri = mri_tmp ;
  }
  write_surface_warp_into_volume(mris, mri, niter) ;

  if (Gdiag & DIAG_WRITE && DIAG_VERBOSE_ON)
    MRIwrite(mri, "warp.mgz") ;
  gcam = GCAMalloc(mri->width, mri->height, mri->depth) ;
  GCAMinitVolGeom(gcam, mri, mri) ;
  GCAMremoveSingularitiesAndReadWarpFromMRI(gcam, mri) ;
//  GCAMreadWarpFromMRI(gcam, mri) ;
  //  GCAsetVolGeom(gca, &gcam->atlas);
#if 0
  gcam->gca = gcaAllocMax(1, 1, 1,
			  mri->width, mri->height,
			  mri->depth,
			  0, 0) ;
 GCAMinit(gcam, mri, NULL, NULL, 0) ;
#endif
#if 0
  GCAMinvert(gcam, mri) ;
  GCAMwriteInverseWarpToMRI(gcam, mri) ;
  GCAMremoveSingularitiesAndReadWarpFromMRI(gcam, mri) ;  // should be inverse now
#endif
  if (mri_in)
  {
    MRI *mri_warped, *mri_tmp ;
    printf("applying warp to %s and writing to %s\n", mri_in->fname, out_fname) ;
    mri_tmp = MRIextractRegionAndPad(mri_in, NULL, NULL, pad) ; MRIfree(&mri_in) ; mri_in = mri_tmp ;
    mri_warped = GCAMmorphToAtlas(mri_in, gcam, NULL, -1, SAMPLE_TRILINEAR) ;
    MRIwrite(mri_warped, out_fname) ;
    if (Gdiag_no >= 0)
    {
      double  xi, yi, zi, xo, yo, zo, val;
      int     xp, yp, zp ;
      GCA_MORPH_NODE *gcamn ;

      VERTEX *v = &mris->vertices[Gdiag_no] ;
      MRISsurfaceRASToVoxelCached(mris, mri, v->origx, v->origy, v->origz, &xi, &yi, &zi) ;
      MRISsurfaceRASToVoxelCached(mris, mri, v->x, v->y, v->z, &xo, &yo, &zo) ;
      printf("surface vertex %d: inflated (%2.0f, %2.0f, %2.0f), orig (%2.0f, %2.0f, %2.0f)\n", Gdiag_no, xi, yi, zi, xo, yo, zo) ;
      MRIsampleVolume(mri_in, xo, yo, zo, &val) ;
      xp = nint(xi) ; yp = nint(yi) ; zp = nint(zi) ;
      gcamn = &gcam->nodes[xp][yp][zp] ;
      printf("warp = (%2.1f, %2.1f, %2.1f), orig (%2.1f %2.1f %2.1f) = %2.1f \n", 
	     gcamn->x, gcamn->y, gcamn->z,
	     gcamn->origx, gcamn->origy, gcamn->origz,val) ;
      DiagBreak() ;
    }
  }
  if (no_write == 0)
  {
    out_name = argv[3] ;
    GCAMwrite(gcam, out_name) ;
  }
  msec = TimerStop(&start) ;
  seconds = nint((float)msec/1000.0f) ;
  minutes = seconds / 60 ;
  seconds = seconds % 60 ;
  fprintf(stderr, "warp field calculation took %d minutes and %d seconds.\n", minutes, seconds) ;
  exit(0) ;
  return(0) ;
}
Beispiel #14
0
int main(int argc, char** argv) {
  char   **av ;
  int    ac, nargs ;

  {
    char c ;

    while (feof(stdin))
      printf(".") ;
    c = fgetc(stdin) ;
    printf("c = %c\n", c) ;
    exit(0) ;
  }

  /* rkt: check for and handle version tag */
  nargs = handle_version_option (argc, argv, "$Id: stim_polar.c,v 1.10 2011/03/02 00:04:40 nicks Exp $", "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
    exit (0);
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  setenv("__GL_SYNC_TO_VBLANK", "23", 1) ;
  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  glutInit(&argc, argv);
  if (argc != 8) {
    printf("\nUsage: eccen <flickerFreq> <stimPeriod (ms)> <minEcc> <maxEcc> "
           "<numRings> <numSpokes> <OUTWARD>\n\n");
    exit(1);
  }

  flickerFreq = atof(argv[1]);
  stimPeriod = atof(argv[2]);
  minEcc = atof(argv[3]);
  maxEcc = atof(argv[4]);
  numRings = atoi(argv[5]);
  numSpokes = atoi(argv[6]);
  OUTWARD = atoi(argv[7]);

  if (minEcc < EPS) {
    printf("\nArgument 3 (minEcc) must be larger than %.1e\n\n", EPS);
    exit(1);
  }


  glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
  glutInitWindowSize (width, height);
  glutInitWindowPosition (100, 100);
  glutCreateWindow (argv[0]);
  init ();
#if 0
  glNewList(0, GL_COMPILE) ;
  glNewList(1, GL_COMPILE) ;
#endif

  glutDisplayFunc(display_all);
  glutReshapeFunc(reshape);
  glutIdleFunc(idle);
  glutMainLoop();
  return 0;
}
Beispiel #15
0
int main(int argc, char **argv){
	/* vars */
	FILE *IN = NULL;
	struct option opt;
	int i = 0;
	int c = 0;
	int lines = 0;
	int max_fs = 0;
	int min_fs = 0;
	int count_fs = 0;
	int ie = 0;
	int is_open = 0;

	/* init/get options */
	init_option(&opt);
	get_option(argc-1,argv+1,&opt);

	/* check args */
	if(opt.help > 0){
		help();
		ie++;
	}
	if(ie > 0){
		exit(0);
	}
	if(opt.check > 0){
		print_option(opt);
		ie++;
	}
	if(ie > 0){
		exit(0);
	}

	/* open file */
	if((strlen(opt.input_file) > 0)&&(opt.help == 0)&&(opt.check == 0)){
		if((IN = fopen(opt.input_file,"r")) == NULL){
			perror(opt.input_file);
			exit(1);
		}
		is_open++;
	}else{
		IN = stdin;
	}

	/* skip */
	for(i=0;i<opt.lskip;i++){
		while((c = fgetc(IN)) != opt.linefeed);
	}
	/* first read */
	while((c = fgetc(IN)) != opt.linefeed){
		if(c == opt.fsep){
			count_fs++;
		}
	}
	max_fs = count_fs;
	min_fs = count_fs;
	count_fs = 0;
	lines++;
	/* long raed */
	while((c = fgetc(IN)) != EOF){
		if(c == opt.linefeed){
			max_fs = max(max_fs,count_fs);
			min_fs = min(min_fs,count_fs);
			count_fs = 0;
			lines++;
		}else if(c == opt.fsep){
			count_fs++;
		}
	}

	/* close file */
	if(is_open > 0){
		fclose(IN);
	}

	/* report */
	printf("LINES:%d:\n",lines);
	printf("MAX:%d:\n",max_fs);
	printf("MIN:%d:\n",min_fs);

	/* exit */
	return(0);
}
int
main(int argc, char *argv[])
{
  char          **av, *hemi, fname[STRLEN],
                *in_aseg_name, *out_aseg_name, *surf_dir ;
  int           ac, nargs, h ;
  MRI_SURFACE   *mris ;
  MRI           *mri_aseg ;

  char cmdline[CMD_LINE_LEN] ;
  make_cmd_version_string
  (argc, argv,
   "$Id: mri_relabel_hypointensities.c,v 1.13 2015/05/15 18:44:10 nicks Exp $",
   "$Name:  $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mri_relabel_hypointensities.c,v 1.13 2015/05/15 18:44:10 nicks Exp $",
           "$Name:  $");
  if (nargs && argc - nargs == 1) {
    exit (0);
  }
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3) {
    usage_exit() ;
  }

  in_aseg_name = argv[1] ;
  surf_dir = argv[2] ;
  out_aseg_name = argv[3] ;

  mri_aseg = MRIread(in_aseg_name) ;
  if (!mri_aseg) {
    ErrorExit(ERROR_NOFILE,
              "%s: could not read input segmentation %s",
              Progname, in_aseg_name) ;
  }

  for (h = 0 ; h <= 1 ; h++) {
    if (h == 0) {
      hemi = "lh" ;
    } else {
      hemi = "rh" ;
    }
    sprintf(fname, "%s/%s.%s", surf_dir, hemi, surf_name)  ;
    printf("reading input surface %s...\n", fname) ;
    mris = MRISread(fname) ;
    if (!mris)
      ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
                Progname, fname) ;
    MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;
    MRIScomputeMetricProperties(mris) ;

    printf("relabeling %s hypointensities...\n", hemi) ;
    relabel_hypointensities(mri_aseg, mris, h) ;
    MRISfree(&mris) ;
  }
  relabel_hypointensities_neighboring_gray(mri_aseg) ;

  MRIwrite(mri_aseg, out_aseg_name) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Beispiel #17
0
int
main (int argc, const char *argv[])
{
    hid_t        fid_src=-1;
    hid_t        fid_dst=-1;
    char         *fname_src=NULL;
    char         *fname_dst=NULL;
    char         *oname_src=NULL;
    char         *oname_dst=NULL;
    unsigned     flag=0;
    unsigned     verbose=0;
    unsigned     parents=0;
    hid_t        ocpl_id = (-1);          /* Object copy property list */
    hid_t        lcpl_id = (-1);          /* Link creation property list */
    char         str_flag[20];
    int          opt;
    int          li_ret;
    h5tool_link_info_t linkinfo;
    int          i, len;
    char         *str_ptr=NULL;

    h5tools_setprogname(PROGRAMNAME);
    h5tools_setstatus(EXIT_SUCCESS);
    /* initialize h5tools lib */
    h5tools_init();

    /* init linkinfo struct */
    HDmemset(&linkinfo, 0, sizeof(h5tool_link_info_t));

    /* Check for no command line parameters */
    if(argc == 1) 
    {
        usage();
        leave(EXIT_FAILURE);
    } /* end if */

    /* parse command line options */
    while ((opt = get_option(argc, argv, s_opts, l_opts)) != EOF)
    {
        switch ((char)opt)
        {
        case 'd':
            oname_dst = HDstrdup(opt_arg);
            break;

        case 'f':
            /* validate flag */
            if (parse_flag(opt_arg,&flag)<0)
            {
                usage();
                leave(EXIT_FAILURE);
            }
            HDstrcpy(str_flag,opt_arg);
            break;

        case 'h':
            usage();
            leave(EXIT_SUCCESS);
            break;

        case 'i':
            fname_src = HDstrdup(opt_arg);
            break;

        case 'o':
            fname_dst = HDstrdup(opt_arg);
            break;

        case 'p':
            parents = 1;
            break;

        case 's':
            oname_src = HDstrdup(opt_arg);
            break;

        case 'V':
            print_version(h5tools_getprogname());
            leave(EXIT_SUCCESS);
            break;

        case 'v':
            verbose = 1;
            break;

        default:
            usage();
            leave(EXIT_FAILURE);
        }
    } /* end of while */

/*-------------------------------------------------------------------------
 * check for missing file/object names
 *-------------------------------------------------------------------------*/

    if (fname_src==NULL)
    {
        error_msg("Input file name missing\n");
        usage();
        leave(EXIT_FAILURE);
    }

    if (fname_dst==NULL)
    {
        error_msg("Output file name missing\n");
        usage();
        leave(EXIT_FAILURE);
    }

    if (oname_src==NULL)
    {
        error_msg("Source object name missing\n");
        usage();
        leave(EXIT_FAILURE);
    }

    if (oname_dst==NULL)
    {
        error_msg("Destination object name missing\n");
        usage();
        leave(EXIT_FAILURE);
    }

   /*-------------------------------------------------------------------------
    * open output file
    *-------------------------------------------------------------------------*/

    /* Attempt to open an existing HDF5 file first. Need to open the dst file
       before the src file just in case that the dst and src are the same file
     */
    fid_dst = h5tools_fopen(fname_dst, H5F_ACC_RDWR, H5P_DEFAULT, NULL, NULL, 0);

   /*-------------------------------------------------------------------------
    * open input file
    *-------------------------------------------------------------------------*/

    fid_src = h5tools_fopen(fname_src, H5F_ACC_RDONLY, H5P_DEFAULT, NULL, NULL, 0);

   /*-------------------------------------------------------------------------
    * test for error in opening input file
    *-------------------------------------------------------------------------*/
    if (fid_src==-1)
    {
        error_msg("Could not open input file <%s>...Exiting\n", fname_src);
        if (fname_src)
            HDfree(fname_src);
        leave(EXIT_FAILURE);
    }


   /*-------------------------------------------------------------------------
    * create an output file when failed to open it
    *-------------------------------------------------------------------------*/

    /* If we couldn't open an existing file, try creating file */
    /* (use "EXCL" instead of "TRUNC", so we don't blow away existing non-HDF5 file) */
    if(fid_dst < 0)
        fid_dst = H5Fcreate(fname_dst, H5F_ACC_EXCL, H5P_DEFAULT, H5P_DEFAULT);

   /*-------------------------------------------------------------------------
    * test for error in opening output file
    *-------------------------------------------------------------------------*/
    if (fid_dst==-1)
    {
        error_msg("Could not open output file <%s>...Exiting\n", fname_dst);
        if (fname_src)
            HDfree(fname_src);
        if (fname_dst)
            HDfree(fname_dst);
        leave(EXIT_FAILURE);
    }

   /*-------------------------------------------------------------------------
    * print some info
    *-------------------------------------------------------------------------*/

    if (verbose)
    {
        printf("Copying file <%s> and object <%s> to file <%s> and object <%s>\n",
        fname_src, oname_src, fname_dst, oname_dst);
        if (flag)
            printf("Using %s flag\n", str_flag);
    }


   /*-------------------------------------------------------------------------
    * create property lists for copy
    *-------------------------------------------------------------------------*/

    /* create property to pass copy options */
    if ( (ocpl_id = H5Pcreate(H5P_OBJECT_COPY)) < 0)
        goto error;

    /* set options for object copy */
    if (flag)
    {
        if ( H5Pset_copy_object(ocpl_id, flag) < 0)
            goto error;
    }

    /* Create link creation property list */
    if((lcpl_id = H5Pcreate(H5P_LINK_CREATE)) < 0) {
        error_msg("Could not create link creation property list\n");
        goto error;
    } /* end if */

    /* Check for creating intermediate groups */
    if(parents) {
        /* Set the intermediate group creation property */
        if(H5Pset_create_intermediate_group(lcpl_id, 1) < 0) {
            error_msg("Could not set property for creating parent groups\n");
            goto error;
        } /* end if */

        /* Display some output if requested */
        if(verbose)
            printf("%s: Creating parent groups\n", h5tools_getprogname());
    } /* end if */
    else /* error, if parent groups doesn't already exist in destination file */
    {
        len = HDstrlen(oname_dst);        
        /* check if all the parents groups exist. skip root group */
        for (i = 1; i < len; i++)
        {
            if ('/'==oname_dst[i])
            {
                str_ptr = (char*)HDcalloc((size_t)i+1, sizeof(char));
                HDstrncpy (str_ptr, oname_dst, (size_t)i);
                str_ptr[i]='\0';
                if (H5Lexists(fid_dst, str_ptr, H5P_DEFAULT) <= 0)
                {
                    error_msg("group <%s> doesn't exist. Use -p to create parent groups.\n", str_ptr);
                    HDfree(str_ptr);
                    goto error;
                }
                HDfree(str_ptr);
            }
        }
    }

   /*-------------------------------------------------------------------------
    * do the copy
    *-------------------------------------------------------------------------*/
 
    if(verbose)
        linkinfo.opt.msg_mode = 1;
 
    li_ret = H5tools_get_symlink_info(fid_src, oname_src, &linkinfo, 1);
    if (li_ret == 0) /* dangling link */
    {
        if(H5Lcopy(fid_src, oname_src, 
                   fid_dst, oname_dst,
                   H5P_DEFAULT, H5P_DEFAULT) < 0)
            goto error;
    }
    else /* valid link */
    {
        if (H5Ocopy(fid_src,          /* Source file or group identifier */
                  oname_src,        /* Name of the source object to be copied */
                  fid_dst,          /* Destination file or group identifier  */
                  oname_dst,        /* Name of the destination object  */
                  ocpl_id,          /* Object copy property list */
                  lcpl_id)<0)       /* Link creation property list */
            goto error;
    }

    /* free link info path */
    if (linkinfo.trg_path)
        HDfree(linkinfo.trg_path);

    /* close propertis */
    if(H5Pclose(ocpl_id)<0)
        goto error;
    if(H5Pclose(lcpl_id)<0)
        goto error;

    /* close files */
    if (H5Fclose(fid_src)<0)
        goto error;
    if (H5Fclose(fid_dst)<0)
        goto error;

    if (fname_src)
        HDfree(fname_src);
    if (fname_dst)
        HDfree(fname_dst);
    if (oname_dst)
        HDfree(oname_dst);
    if (oname_src)
        HDfree(oname_src);

    h5tools_close();

    return EXIT_SUCCESS;

error:
    printf("Error in copy...Exiting\n");

    /* free link info path */
    if (linkinfo.trg_path)
        HDfree(linkinfo.trg_path);

 H5E_BEGIN_TRY {
    H5Pclose(ocpl_id);
    H5Pclose(lcpl_id);
    H5Fclose(fid_src);
    H5Fclose(fid_dst);
 } H5E_END_TRY;
    if (fname_src)
        HDfree(fname_src);
    if (fname_dst)
        HDfree(fname_dst);
    if (oname_dst)
        HDfree(oname_dst);
    if (oname_src)
        HDfree(oname_src);

    h5tools_close();

    return EXIT_FAILURE;
}
Beispiel #18
0
void RTC_VIT(unsigned int number, const char* GPU_kernel, HMMER_PROFILE *hmm,
	     unsigned int *seq_1D, unsigned int *offset, unsigned int *seq_len,
	     unsigned int *iLen, unsigned int sum, double *pVal,
	     int warp, int maxreg, dim3 GRID, dim3 BLOCK)
{	
	/*********************************/
	/* 0. Prepare for cuda drive API */
	/*********************************/
	CUdevice cuDevice;
	CUcontext context;
	CUmodule module;
	CUfunction kernel;

	checkCudaErrors(cuInit(0));
	checkCudaErrors(cuDeviceGet(&cuDevice, 0));
	checkCudaErrors(cuCtxCreate(&context, 0, cuDevice)); 

	/*********************************************/
	/* 1. Device Property: fixed based on Device */
	/*********************************************/

	/****************************************/
	/* 2. Device Memory Allocation and copy */
	/****************************************/
	StopWatchInterface *timer;
    sdkCreateTimer(&timer);
    sdkStartTimer(&timer);

   	/* Driver API pointers */
	CUdeviceptr d_seq, d_offset, d_len, d_len_6r, mat_v, trans, score;

	/* Allocation */
	checkCudaErrors(cuMemAlloc(&d_seq, sum * sizeof(unsigned int)));							/* copy 1D database */
	checkCudaErrors(cuMemAlloc(&d_offset, number * sizeof(unsigned int)));						/* copy offset of each seq*/
	checkCudaErrors(cuMemAlloc(&d_len, number * sizeof(unsigned int)));							/* copy raw length of each seq */
	checkCudaErrors(cuMemAlloc(&d_len_6r, number * sizeof(unsigned int)));						/* copy padding length of each seq */
	checkCudaErrors(cuMemAlloc(&mat_v, hmm->vitQ * PROTEIN_TYPE * sizeof(__32int__)));		/* striped EMISSION score */
	checkCudaErrors(cuMemAlloc(&trans, hmm->vitQ * TRANS_TYPE * sizeof(__32int__)));		/* striped transition score */
	checkCudaErrors(cuMemAlloc(&score, number * sizeof(double)));								/* P-Value as output */

	/* H to D copy */
	checkCudaErrors(cuMemcpyHtoD(d_seq, seq_1D, sum * sizeof(unsigned int)));
	checkCudaErrors(cuMemcpyHtoD(d_offset, offset, number * sizeof(unsigned int)));
	checkCudaErrors(cuMemcpyHtoD(d_len, seq_len, number * sizeof(unsigned int)));
	checkCudaErrors(cuMemcpyHtoD(d_len_6r, iLen, number * sizeof(unsigned int)));
	checkCudaErrors(cuMemcpyHtoD(mat_v, hmm->vit_vec, hmm->vitQ * PROTEIN_TYPE * sizeof(__32int__)));
	checkCudaErrors(cuMemcpyHtoD(trans, hmm->trans_vec, hmm->vitQ * TRANS_TYPE * sizeof(__32int__)));
		
	sdkStopTimer(&timer);
    printf("Alloc & H to D Copy time: %f (ms)\n", sdkGetTimerValue(&timer));
    sdkDeleteTimer(&timer);

    /********************************************************/
	/* 3. Runtime compilation, Generate PTX and Load module */
	/********************************************************/
    sdkCreateTimer(&timer);
    sdkStartTimer(&timer);

	/* NVRTC create handle */
	nvrtcProgram prog;
	NVRTC_SAFE_CALL("nvrtcCreateProgram", nvrtcCreateProgram(&prog,				// prog
															 GPU_kernel,		// buffer
															 NULL,				// name: CUDA program name. name can be NULL; “default_program” is used when it is NULL.
															 0,					// numHeaders (I put header file path with -I later)
															 NULL,				// headers' content
															 NULL));			// include full name of headers

	/* 1. eliminate const through pointer */
    char *a = NULL;
    const char *b = a;
    const char **opts = &b;

    /* 2. elminate const through reference */
    //char a_value = 'c';
    //char* aa = &a_value;
    //const char *&bb = aa;		// no way with const
    //const char**&ref = aa;	// no way

    /* Dynamic Options */
    char **test_char = new char*[8];

    test_char[0] = new char[__INCLUDE__.length() + strlen("simd_def.h") + 1];					// #include simd_def.h
	strcpy(test_char[0], get_option(__INCLUDE__, "simd_def.h").c_str());

    test_char[1] = new char[__INCLUDE__.length() + strlen("simd_functions.h") + 1];				// #include simd_functions.h
    strcpy(test_char[1], get_option(__INCLUDE__, "simd_functions.h").c_str());

    test_char[2] = new char[__RDC__.length() + __F__.length() + 1];								// -rdc=false
    strcpy(test_char[2], get_option(__RDC__, __F__).c_str());

    test_char[3] = new char[__ARCH__.length() + __CC35__.length() + 1];							// -arch=compute_35
    strcpy(test_char[3], get_option(__ARCH__, __CC35__).c_str());

    test_char[4] = new char[__MAXREG__.length() + int2str(maxreg).length() + 1];				// -maxrregcount = <?>
    strcpy(test_char[4], get_option(__MAXREG__, int2str(maxreg)).c_str());

    test_char[5] = new char[__RIB__.length() + int2str(warp).length() + 1];						// #define RIB <?> : warps per block
    strcpy(test_char[5], get_option(__RIB__, int2str(warp)).c_str());

    test_char[6] = new char[__SIZE__.length() + int2str((int)force_local_size).length() + 1];	// #define SIZE 40
    strcpy(test_char[6], get_option(__SIZE__, int2str((int)force_local_size)).c_str());

    test_char[7] = new char[__Q__.length() + int2str(hmm->vitQ).length() + 1];					// #define Q <?>
    strcpy(test_char[7], get_option(__Q__, int2str(hmm->vitQ)).c_str());

    /* 1. change const char** through pointer */
    //char* **test = const_cast<char** *>(&opts);
    //*test = test_char;

    /* 2. change const char** through reference */
    char** &test_ref = const_cast<char** &>(opts);
    test_ref = test_char;

    /* NVRTC compile */
	NVRTC_SAFE_CALL("nvrtcCompileProgram", nvrtcCompileProgram(prog,	// prog
															   8,		// numOptions
															   opts));	// options

	sdkStopTimer(&timer);
    printf("nvrtc Creat and Compile: %f (ms)\n", sdkGetTimerValue(&timer));
    sdkDeleteTimer(&timer);

	//======================================================================================//
	// /* dump log */																		//	
    // size_t logSize;																		//
    // NVRTC_SAFE_CALL("nvrtcGetProgramLogSize", nvrtcGetProgramLogSize(prog, &logSize));	//
    // char *log = (char *) malloc(sizeof(char) * logSize + 1);								//
    // NVRTC_SAFE_CALL("nvrtcGetProgramLog", nvrtcGetProgramLog(prog, log));				//
    // log[logSize] = '\x0';																//
    // std::cerr << "\n compilation log ---\n";												//
    // std::cerr << log;																	//
    // std::cerr << "\n end log ---\n";														//
    // free(log);																			//
	//======================================================================================//
	
	/* NVRTC fetch PTX */
	sdkCreateTimer(&timer);
    sdkStartTimer(&timer);

	size_t ptxsize;
	NVRTC_SAFE_CALL("nvrtcGetPTXSize", nvrtcGetPTXSize(prog, &ptxsize));
	char *ptx = new char[ptxsize];
	NVRTC_SAFE_CALL("nvrtcGetPTX", nvrtcGetPTX(prog, ptx));
	NVRTC_SAFE_CALL("nvrtcDestroyProgram", nvrtcDestroyProgram(&prog));	// destroy program instance

	/* Launch PTX by driver API */
	checkCudaErrors(cuModuleLoadDataEx(&module, ptx, 0, 0, 0));
	checkCudaErrors(cuModuleGetFunction(&kernel, module, "KERNEL"));	// return the handle of function, name is the same as real kernel function

	sdkStopTimer(&timer);
    printf("Compile & Load time: %f (ms)\n", sdkGetTimerValue(&timer));
    sdkDeleteTimer(&timer);

    /**************************************/
	/* 4. GPU kernel launch by driver API */
	/**************************************/
    sdkCreateTimer(&timer);
    sdkStartTimer(&timer);
    
    cuCtxSetCacheConfig(CU_FUNC_CACHE_PREFER_L1);
   /* parameters for kernel funciton */
	void *arr[] = { &d_seq, &number, &d_offset,
					&score, &d_len, &d_len_6r, &mat_v, &trans, 
					&(hmm->base_vs), &(hmm->E_lm), &(hmm->ddbound_vs),
					&(hmm->scale_w), &(hmm->vitQ), &(hmm->MU[1]), &(hmm->LAMBDA[1])};

	/* launch kernel */
        checkCudaErrors(cuLaunchKernel(	kernel,
								  	GRID.x, GRID.y, GRID.z,		/* grid dim */
									BLOCK.x, BLOCK.y, BLOCK.z,	/* block dim */
									0,0,						/* SMEM, stream */
									&arr[0],					/* kernel params */
									0));						/* extra opts */

	/* wait for kernel finish */
	checkCudaErrors(cuCtxSynchronize());			/* block for a context's task to complete */

	sdkStopTimer(&timer);
    printf("Kernel time: %f (ms)\n", sdkGetTimerValue(&timer));
    sdkDeleteTimer(&timer);

    /*****************************************/
    /* 5. P-value return and post-processing */
    /*****************************************/
    sdkCreateTimer(&timer);
    sdkStartTimer(&timer);

    checkCudaErrors(cuMemcpyDtoH(pVal, score, number * sizeof(double)));

   	sdkStopTimer(&timer);
    printf("D to H copy time: %f (ms)\n", sdkGetTimerValue(&timer));
    sdkDeleteTimer(&timer);

    /* count the number of seqs pass */
	unsigned long pass_vit = 0;			/* # of seqs pass vit */

	for (int i = 0; i < number; i++)
	{
		if (pVal[i] <= F2)
			pass_vit++;
	}

	printf("|			PASS VIT 			\n");
	printf("|	 ALL	|	 FWD	|\n");
	printf("|	%d  	|	%d  	|\n",  pass_vit, pass_vit);

	/************************/
	/* 6. clean the context */
	/************************/
    checkCudaErrors(cuDevicePrimaryCtxReset(cuDevice));		/* reset */
	checkCudaErrors(cuCtxSynchronize());					/* block for a context's task to complete */
}
Beispiel #19
0
static int __init profile_setup(char *str)
{
    int par;
    if (get_option(&str,&par)) prof_shift = par;
	return 1;
}
Beispiel #20
0
int main(int argc, char *argv[])
#endif
{
	uint8_t *temp, *message;
	unsigned long t1 = 0, t2 = 0, xid = 0;
	unsigned long start = 0, lease;
	fd_set rfds;
	int retval;
	struct timeval tv;
	int c, len;
	struct dhcpMessage packet;
	struct in_addr temp_addr;
	long now;
	int max_fd;
	int sig;
	int no_clientid = 0;
	int fail_times = 0;		/* how many times that we fail to find a dhcp server */
	int server_unicast = 0;		


	static const struct option arg_options[] = {
		{"clientid",	required_argument,	0, 'c'},
		{"clientid-none", no_argument,		0, 'C'},
		{"foreground",	no_argument,		0, 'f'},
		{"background",	no_argument,		0, 'b'},
		{"hostname",	required_argument,	0, 'H'},
		{"hostname",    required_argument,      0, 'h'},
		{"interface",	required_argument,	0, 'i'},
		{"now", 	no_argument,		0, 'n'},
		{"pidfile",	required_argument,	0, 'p'},
		{"quit",	no_argument,		0, 'q'},
		{"request",	required_argument,	0, 'r'},
		{"script",	required_argument,	0, 's'},
		{"unicast",	no_argument,		0, 'u'},	/* unicast flag */
		{"version",	no_argument,		0, 'v'},
		{0, 0, 0, 0}
	};

	/* get options */
	while (1) {
		int option_index = 0;
		c = getopt_long(argc, argv, "c:CfbH:h:i:np:qr:s:uv", arg_options, &option_index);
		if (c == -1) break;

		switch (c) {
		case 'c':
			if (no_clientid) show_usage();
			len = strlen(optarg) > 255 ? 255 : strlen(optarg);
			if (client_config.clientid) free(client_config.clientid);
			client_config.clientid = xmalloc(len + 2);
			client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
			client_config.clientid[OPT_LEN] = len;
			client_config.clientid[OPT_DATA] = '\0';
			strncpy(client_config.clientid + OPT_DATA, optarg, len);
			break;
		case 'C':
			if (client_config.clientid) show_usage();
			no_clientid = 1;
			break;
		case 'f':
			client_config.foreground = 1;
			break;
		case 'b':
			client_config.background_if_no_lease = 1;
			break;
		case 'h':
		case 'H':
			len = strlen(optarg) > 255 ? 255 : strlen(optarg);
			if (client_config.hostname) free(client_config.hostname);
			client_config.hostname = xmalloc(len + 2);
			client_config.hostname[OPT_CODE] = DHCP_HOST_NAME;
			client_config.hostname[OPT_LEN] = len;
			strncpy(client_config.hostname + 2, optarg, len);
			break;
		case 'i':
			client_config.interface =  optarg;
			break;
		case 'n':
			client_config.abort_if_no_lease = 1;
			break;
		case 'p':
			client_config.pidfile = optarg;
			break;
		case 'q':
			client_config.quit_after_lease = 1;
			break;
		case 'r':
			requested_ip = inet_addr(optarg);
			break;
		case 's':
			client_config.script = optarg;
			break;
		case 'u':
			server_unicast = 1;
			break;
		case 'v':
			printf("udhcpcd, version %s\n\n", VERSION);
			return 0;
			break;
		default:
			show_usage();
		}
	}

	/* Start the log, sanitize fd's, and write a pid file */
	start_log_and_pid("udhcpc", client_config.pidfile);

	if (read_interface(client_config.interface, &client_config.ifindex,
			   NULL, client_config.arp) < 0)
		return 1;

	/* if not set, and not suppressed, setup the default client ID */
	if (!client_config.clientid && !no_clientid) {
		client_config.clientid = xmalloc(6 + 3);
		client_config.clientid[OPT_CODE] = DHCP_CLIENT_ID;
		client_config.clientid[OPT_LEN] = 7;
		client_config.clientid[OPT_DATA] = 1;
		memcpy(client_config.clientid + 3, client_config.arp, 6);
	}

	/* changed by lsz 070621 */
	client_background();
	
	/* setup the signal pipe */
	udhcp_sp_setup();

	//if (dhcpc_shm_init() != 0)
	//	return -1;
	#include "msgq.h"
	dhcp_ipc_fork(DHCPC);

	state = INIT_SELECTING;
	run_script(NULL, "deconfig");
	change_mode(LISTEN_RAW);

	for (;;) {
		tv.tv_sec = timeout - uptime();
		tv.tv_usec = 0;

		if (listen_mode != LISTEN_NONE && fd < 0) {
			if (listen_mode == LISTEN_KERNEL)
				fd = listen_socket(INADDR_ANY, CLIENT_PORT, client_config.interface);
			else
				fd = raw_socket(client_config.ifindex);
			if (fd < 0) {
				LOG(LOG_ERR, "FATAL: couldn't listen on socket, %m");
				return 0;
			}
		}
		
        /* 
         * select don't return when timeout value is larger than 1.5 hours
         * we just wait multiple times
         * added by tiger 090819, should fix later
         */
        struct timeval tp_timeout;
        #define TP_TIMEOUT_MAX  (30*60)
        
		if (tv.tv_sec > 0) 
		{
            do
            {
                max_fd = udhcp_sp_fd_set(&rfds, fd);
                
                tp_timeout.tv_sec = (tv.tv_sec > TP_TIMEOUT_MAX) ? TP_TIMEOUT_MAX : tv.tv_sec;
                tv.tv_sec -= tp_timeout.tv_sec;                                
                tp_timeout.tv_usec = 0;

                retval = select(max_fd + 1, &rfds, NULL, NULL, &tp_timeout);                
                
            } while (tv.tv_sec > 0 && retval == 0);
		}
		else
		{
			retval = 0; /* If we already timed out, fall through */
		}
        
		now = uptime();
		if (retval == 0) {
			/* timeout dropped to zero */
			switch (state) {
			case INIT_SELECTING:
               
#define     DISCOVER_RETRY_TIMES    5
#define     DISCOVER_INVERT_TIMES   3

				if (packet_num < DISCOVER_RETRY_TIMES) {
					if (packet_num == 0)
					{
						xid = random_xid();
                        /* use user config dhcp flags when first discover, added by tiger 20090821 */
                        if (server_unicast)
                        {
                            set_runtime_dhcp_flags(DHCP_FLAGS_UNICAST);
                        }
                        else
                        {
                            set_runtime_dhcp_flags(DHCP_FLAGS_BROADCAST);                            
                        }
					}

                    /* change runtime dhcp flags when exceed DISCOVER_INVERT_TIMES added by tiger 20090819 apply 11G and XP's option */
                    if (DISCOVER_INVERT_TIMES == packet_num)
                    {                        
                        invert_runtime_dhcp_flags();
                    }
                    
					/* send discover packet */
					//send_discover(xid, requested_ip, server_unicast); /* broadcast */
					/* modified by tiger 20090304, reply mode's setting way changed */
					send_discover(xid, requested_ip);
					msglogd(LOG_INFO, LOGTYPE_DHCP, "DHCPC Send DISCOVER with request ip %X and unicast flag %d", requested_ip, get_runtime_dhcp_flags());                    
                    
					timeout = now + ((packet_num == 2) ? 4 : 2);
					packet_num++;
				} else {
					run_script(NULL, "leasefail");
					msglogd(LOG_INFO, LOGTYPE_DHCP, "DHCPC DHCP Service unavailable, recv no OFFER");
					if (client_config.background_if_no_lease) {
						LOG(LOG_INFO, "No lease, forking to background.");
						client_background();
					} else if (client_config.abort_if_no_lease) {
						LOG(LOG_INFO, "No lease, failing.");
						return 1;
				  	}
					/* wait to try again */
					packet_num = 0;
					
					timeout = now + 10 + (fail_times ++) * 30;	
					/* 60->6000, we dont need to try again -- lsz, 080722 */
					/* 6000->30*fail_times -- lsz, 081008 */
				}
				break;
			case RENEW_REQUESTED:
			case REQUESTING:
				if (packet_num < 3) {
					/* send request packet */
					if (state == RENEW_REQUESTED)
					{
						send_renew(xid, server_addr, requested_ip); /* unicast */
					}
					else
					{
						send_selecting(xid, server_addr, requested_ip); /* broadcast */
					}

					msglogd(LOG_INFO, LOGTYPE_DHCP, "DHCPC Send REQUEST to server %x with request ip %x", server_addr, requested_ip);

					timeout = now + ((packet_num == 2) ? 10 : 2);
					packet_num++;
				} else {
					/* timed out, go back to init state */
					if (state == RENEW_REQUESTED) run_script(NULL, "deconfig");
					state = INIT_SELECTING;
					timeout = now;
					packet_num = 0;
					change_mode(LISTEN_RAW);
				}
				break;
			case BOUND:
				/* Lease is starting to run out, time to enter renewing state */
				state = RENEWING;
				change_mode(LISTEN_KERNEL);
				DEBUG(LOG_INFO, "Entering renew state");
				/* fall right through */
			case RENEWING:
				/* Either set a new T1, or enter REBINDING state */
				if ((t2 - t1) <= (lease / 14400 + 1)) {
					/* timed out, enter rebinding state */
					state = REBINDING;
					timeout = now + (t2 - t1);
					DEBUG(LOG_INFO, "Entering rebinding state");
				} else {
					/* send a request packet */				
					send_renew(xid, server_addr, requested_ip); /* unicast */

					msglogd(LOG_INFO, LOGTYPE_DHCP, "DHCPC Send REQUEST to server %x with request ip %x", server_addr, requested_ip);
              
					t1 = (t2 - t1) / 2 + t1;
					timeout = t1 + start;
				}
				break;
			case REBINDING:
				/* Either set a new T2, or enter INIT state */
				if ((lease - t2) <= (lease / 14400 + 1)) {
					/* timed out, enter init state */
					state = INIT_SELECTING;
					LOG(LOG_INFO, "Lease lost, entering init state");
					run_script(NULL, "deconfig");
					timeout = now;
					packet_num = 0;
					change_mode(LISTEN_RAW);
				} else {
					/* send a request packet */
					send_renew(xid, 0, requested_ip); /* broadcast */

					
					msglogd(LOG_INFO, LOGTYPE_DHCP, "DHCPC Broadcast REQUEST with request ip %x", requested_ip);
					t2 = (lease - t2) / 2 + t2;
					timeout = t2 + start;
				}
				break;
			case RELEASED:
				/* yah, I know, *you* say it would never happen */
				timeout = 0x7fffffff;
				break;
			}
		}
		else if (retval > 0 && listen_mode != LISTEN_NONE && FD_ISSET(fd, &rfds)) {
			/* a packet is ready, read it */
			if (listen_mode == LISTEN_KERNEL)
				len = get_packet(&packet, fd);
			else len = get_raw_packet(&packet, fd);

			if (len == -1 && errno != EINTR) {
				DEBUG(LOG_INFO, "error on read, %m, reopening socket");
				change_mode(listen_mode); /* just close and reopen */
			}
			if (len < 0) continue;

			if (packet.xid != xid) {
				DEBUG(LOG_INFO, "Ignoring XID %lx (our xid is %lx)",
					(unsigned long) packet.xid, xid);
				continue;
			}
			/* Ignore packets that aren't for us */
			if (memcmp(packet.chaddr, client_config.arp, 6)) {
				DEBUG(LOG_INFO, "packet does not have our chaddr -- ignoring");
				continue;
			}

			if ((message = get_option(&packet, DHCP_MESSAGE_TYPE)) == NULL) {
				DEBUG(LOG_ERR, "couldnt get option from packet -- ignoring");
				continue;
			}

			switch (state) {
			case INIT_SELECTING:
				/* Must be a DHCPOFFER to one of our xid's */
				if (*message == DHCPOFFER) {
					if ((temp = get_option(&packet, DHCP_SERVER_ID))) {
						memcpy(&server_addr, temp, 4);
						xid = packet.xid;
						requested_ip = packet.yiaddr;

						msglogd(LOG_INFO, LOGTYPE_DHCP, "DHCPC Recv OFFER from server %x with ip %x", server_addr, requested_ip);

						/* enter requesting state */
						state = REQUESTING;
						timeout = now;
						packet_num = 0;
					} else {
						DEBUG(LOG_ERR, "No server ID in message");
					}
				}
				break;
			case RENEW_REQUESTED:
			case REQUESTING:
			case RENEWING:
			case REBINDING:
				if (*message == DHCPACK) {
					if (!(temp = get_option(&packet, DHCP_LEASE_TIME))) {
						LOG(LOG_ERR, "No lease time with ACK, using 1 hour lease");
						lease = 60 * 60;
					} else {
						memcpy(&lease, temp, 4);
						lease = ntohl(lease);
					}

/* RFC 2131 3.1 paragraph 5:
 * "The client receives the DHCPACK message with configuration
 * parameters. The client SHOULD perform a final check on the
 * parameters (e.g., ARP for allocated network address), and notes
 * the duration of the lease specified in the DHCPACK message. At this
 * point, the client is configured. If the client detects that the
 * address is already in use (e.g., through the use of ARP),
 * the client MUST send a DHCPDECLINE message to the server and restarts
 * the configuration process..." 
 * added by tiger 20090827
 */                    
					if (!arpping(packet.yiaddr,
						    (uint32_t) 0,
						    packet.yiaddr,
						    client_config.arp,
						    client_config.interface)
					) {
					
						msglogd (LOG_INFO, LOGTYPE_DHCP, "DHCPC: offered address is in use "
							"(got ARP reply), Send decline");
						send_decline(xid, server_addr, packet.yiaddr);

						if (state != REQUESTING)
							run_script(NULL, "deconfig");
						change_mode(LISTEN_RAW);
						state = INIT_SELECTING;
						requested_ip = 0;
						timeout = now + 12;
						packet_num = 0;
						continue; /* back to main loop */
					}
                    
					/* enter bound state */
					t1 = lease / 2;

					/* little fixed point for n * .875 */
					t2 = (lease * 0x7) >> 3;
					temp_addr.s_addr = packet.yiaddr;
					LOG(LOG_INFO, "Lease of %s obtained, lease time %ld",
						inet_ntoa(temp_addr), lease);
					start = now;
					timeout = t1 + start;
					requested_ip = packet.yiaddr;

					if ((temp = get_option(&packet, DHCP_SERVER_ID))) 
						memcpy(&server_addr, temp, 4);
					msglogd(LOG_INFO, LOGTYPE_DHCP, "DHCPC Recv ACK from server %x with ip %x lease time %ld", 
						server_addr, requested_ip, lease);
					
					run_script(&packet,
						   ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));

					fail_times = 0;		/* clear the retry counter */
					state = BOUND;
					change_mode(LISTEN_NONE);
					if (client_config.quit_after_lease)
						return 0;
					if (!client_config.foreground)
						client_background();

				} else if (*message == DHCPNAK) {
					/* return to init state */
					LOG(LOG_INFO, "Received DHCP NAK");

					if ((temp = get_option(&packet, DHCP_SERVER_ID))) 
						memcpy(&server_addr, temp, 4);
					msglogd(LOG_INFO, LOGTYPE_DHCP, "DHCPC Recv NAK from server %x with ip %x", server_addr, requested_ip);

					run_script(&packet, "nak");
					if (state != REQUESTING)
						run_script(NULL, "deconfig");
					state = INIT_SELECTING;
					timeout = now + 3;	/* change by lsz 080905, without this 3 seconds,
										 * the udhcpc will keep on trying and the release
										 * msg cant be recved by udhcpc, even if we are
										 * wan static ip now, the udhcpc is still sending 
										 * discover pkts. 
										 */
					requested_ip = 0;
					packet_num = 0;
					change_mode(LISTEN_RAW);
					//sleep(3); /* avoid excessive network traffic */
				}
				break;
			/* case BOUND, RELEASED: - ignore all packets */
			}
		} 
		else if (retval > 0 && (sig = udhcp_sp_read(&rfds))) {
static int __init getddt(char *str)
{
	get_option(&str, &ddt);
	printk(KERN_INFO "\n[disp] ddt = %d\n", ddt);
	return 0;
}
static int __init pdc_chassis_setup(char *str)
{
	/*panic_timeout = simple_strtoul(str, NULL, 0);*/
	get_option(&str, &pdc_chassis_enabled);
	return 1;
}
Beispiel #23
0
int main(int argc, char **argv)
{
	double double_var;

	char *input_buffer = NULL;

#if 0
	unsigned char input_tty = 1;
#endif

	int data_file;
	int option;
	int last_option;
	int last_u_option;
	int flip_bytes = 0;

/*	long offset; */
/*	long record_number; */
	long file_position;
	long data_file_length;
	long ops_file_length = 0;
	long new_position;
/*	long long_var; */

	fprintf(stderr, "%s",
#ifdef FF_ALPHA
"\nWelcome to readfile alpha 1.1 "__DATE__" -- an NGDC binary file reader\n"
#elif defined(FF_BETA)
"\nWelcome to readfile beta 1.1 "__DATE__" -- an NGDC binary file reader\n"
#else
"\nWelcome to readfile release 1.1 -- an NGDC binary file reader\n"
#endif
	       );

	if (argc == 1)
	{
		fprintf(stderr, "%s", "\nUSAGE: readfile binary_file\n");
		exit(1);
	}

	show_opt();

#if FF_OS == FF_OS_DOS
	data_file = open(argv[1], O_RDONLY | O_BINARY);
#endif

#if FF_OS == FF_OS_UNIX
	data_file = open(argv[1], O_RDONLY);
#endif

	if(data_file == -1)
	{
		fprintf(stderr,"Could Not Open Input File %s\n", argv[1]);
		exit(0);
	}

	{
		FILE *fp = fopen(argv[1], "r");
		data_file_length = -1;

		if (fp)
		{
			if (!fseek(fp, 0, SEEK_END))
				data_file_length = ftell(fp);

			fclose(fp);
		}
	}

	/* Determine if the input is coming from a file, if so read the file in */
	if (!isatty(fileno(stdin)))
	{
		ops_file_length = lseek(fileno(stdin), 0L, SEEK_END);
		input_buffer = (char *)malloc((size_t)ops_file_length + 1);
		if (!input_buffer)
		{
			fprintf(stderr, "Insufficient memory -- file is too large");
			exit(1);
		}

		lseek(fileno(stdin), 0L, SEEK_SET);
		read(fileno(stdin), input_buffer, (size_t)ops_file_length);
		*(input_buffer + ops_file_length) = '\0';
		input = input_buffer;
	}

	last_u_option = ' ';
	last_option = ' ';

	while ((option = get_option()) != 'q')
	{
		if (option == UINT_PREFIX)
			last_u_option = ' ';
		if (option == EOL_MARKER)
			option = last_option;

		switch(option)
		{
			case TEXT_CODE:

				if (check_error(read(data_file, (char *)&double_var, sizeof(char)), sizeof(char)))
					break;

				fprintf(stdout, "text: \'%c\', dec: %3d, hex: %2x, oct: %3o\n",
				        *(char *)&double_var,
				        *(unsigned char *)&double_var,
				        *(unsigned char *)&double_var,
				        *(unsigned char *)&double_var);

			break;

			case INT8_CODE:

				if (check_error(read(data_file, (char *)&double_var, SIZE_INT8), SIZE_INT8))
					break;

				fprintf(stdout, "int8: ");
				fprintf(stdout, fft_cnv_flags_width[FFNT_INT8], INT8_WIDTH,
				        *((int8 *)&double_var));
				fprintf(stdout, "\n");
			break;

			case INT16_CODE:

				if (check_error(read(data_file, (char *)&double_var, SIZE_INT16), SIZE_INT16))
					break;

				if (flip_bytes)
				{
					flip_2_bytes(&double_var);
					fprintf(stdout,"int16, byte swapped: ");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT16], INT16_WIDTH,
					        *((int16 *)&double_var));
					flip_2_bytes(&double_var);
					fprintf(stdout,", (\"%s-endian\": ",
					        endian() == LITTLE_ENDIAN ? "little" : "big");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT16], INT16_WIDTH,
					        *((int16 *)&double_var));
					fprintf(stdout, ")\n");
				}
				else
				{
					fprintf(stdout, "int16: ");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT16], INT16_WIDTH,
					        *((int16 *)&double_var));
					fprintf(stdout, "\n");
				}

			break;

			case INT32_CODE:

				if (check_error(read(data_file, (char *)&double_var, SIZE_INT32), SIZE_INT32))
					break;

				if (flip_bytes)
				{
					flip_4_bytes(&double_var);
					fprintf(stdout,"int32, byte swapped: ");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT32], INT32_WIDTH,
					        *((int32 *)&double_var));
					flip_4_bytes(&double_var);
					fprintf(stdout,", (\"%s-endian\": ",
					        endian() == LITTLE_ENDIAN ? "little" : "big");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT32], INT32_WIDTH,
					        *((int32 *)&double_var));
					fprintf(stdout, ")\n");
				}
				else
				{
					fprintf(stdout, "int32: ");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT32], INT32_WIDTH,
					        *((int32 *)&double_var));
					fprintf(stdout, "\n");
				}

			break;

#ifdef LONGS_ARE_64

			case INT64_CODE:

				if (check_error(read(data_file, (char *)&double_var, SIZE_INT64), SIZE_INT64))
					break;

				if (flip_bytes)
				{
					flip_8_bytes(&double_var);
					fprintf(stdout,"int64, byte swapped: ");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT64], INT64_WIDTH,
					        *((int64 *)&double_var));
					flip_8_bytes(&double_var);
					fprintf(stdout,", (\"%s-endian\": ",
					        endian() == LITTLE_ENDIAN ? "little" : "big");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT64], INT64_WIDTH,
					        *((int64 *)&double_var));
					fprintf(stdout, ")\n");
				}
				else
				{
					fprintf(stdout, "int64: ");
					fprintf(stdout, fft_cnv_flags_width[FFNT_INT64], INT64_WIDTH,
					        *((int64 *)&double_var));
					fprintf(stdout, "\n");
				}

			break;

#endif

			case FLOAT32_CODE:

				if (check_error(read(data_file,(char *)&double_var, SIZE_FLOAT32), SIZE_FLOAT32))
					break;

				if (flip_bytes)
				{
					flip_4_bytes(&double_var);
					fprintf(stdout, "float32, byte swapped: ");
					fprintf(stdout, fft_cnv_flags_width_prec[FFNT_FLOAT32], FLOAT32_WIDTH,
					        FLOAT32_PREC, *((float32 *)&double_var));
					flip_4_bytes(&double_var);
					fprintf(stdout,", (\"%s-endian\": ",
					        endian() == LITTLE_ENDIAN ? "little" : "big");
					fprintf(stdout, fft_cnv_flags_width_prec[FFNT_FLOAT32], FLOAT32_WIDTH,
					        FLOAT32_PREC, *((float32 *)&double_var));
					fprintf(stdout, ")\n");
				}
				else
				{
					fprintf(stdout, "float32: ");
					fprintf(stdout, fft_cnv_flags_width_prec[FFNT_FLOAT32], FLOAT32_WIDTH,
					        FLOAT32_PREC, *((float32 *)&double_var));
					fprintf(stdout, "\n");
				}

			break;

			case FLOAT64_CODE:

				if (check_error(read(data_file,(char *)&double_var, SIZE_FLOAT64), SIZE_FLOAT64))
					break;

				if (flip_bytes)
				{
					flip_8_bytes(&double_var);
					fprintf(stdout, "float64, byte swapped: ");
					fprintf(stdout, fft_cnv_flags_width_prec[FFNT_FLOAT64], FLOAT64_WIDTH,
					        FLOAT64_PREC, *((float64 *)&double_var));
					flip_8_bytes(&double_var);
					fprintf(stdout,", (\"%s-endian\": ",
					        endian() == LITTLE_ENDIAN ? "little" : "big");
					fprintf(stdout, fft_cnv_flags_width_prec[FFNT_FLOAT64], FLOAT64_WIDTH,
					        FLOAT64_PREC, *((float64 *)&double_var));
					fprintf(stdout, ")\n");
				}
				else
				{
					fprintf(stdout, "float64: ");
					fprintf(stdout, fft_cnv_flags_width_prec[FFNT_FLOAT64], FLOAT64_WIDTH,
					        FLOAT64_PREC, *((float64 *)&double_var));
					fprintf(stdout, "\n");
				}

			break;

			case UINT_PREFIX: /* unsigned ... */

				/* If last option is not yet defined, prompt the user */
				if (last_u_option == ' ')
				{
					last_u_option = get_option();
				}

				switch (last_u_option)
				{
					case INT8_CODE: /* unsigned char */

						if (check_error(read(data_file, (char *)&double_var, SIZE_UINT8), SIZE_UINT8))
							break;

						fprintf(stdout, "uint8: ");
						fprintf(stdout, fft_cnv_flags_width[FFNT_UINT8], UINT8_WIDTH,
						        *((uint8 *)&double_var));
						fprintf(stdout, "\n");

					break;

					case INT16_CODE:

						if (check_error(read(data_file, (char *)&double_var, SIZE_UINT16), SIZE_UINT16))
							break;

						if (flip_bytes)
						{
							flip_2_bytes(&double_var);
							fprintf(stdout,"uint16, byte swapped: ");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT16], UINT16_WIDTH,
							        *((uint16 *)&double_var));
							flip_2_bytes(&double_var);
							fprintf(stdout,", (\"%s-endian\": ",
							        endian() == LITTLE_ENDIAN ? "little" : "big");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT16], UINT16_WIDTH,
							        *((uint16 *)&double_var));
							fprintf(stdout, ")\n");
						}
						else
						{
							fprintf(stdout, "uint16: ");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT16], UINT16_WIDTH,
							        *((uint16 *)&double_var));
							fprintf(stdout, "\n");
						}

					break;

					case INT32_CODE:

						if (check_error(read(data_file, (char *)&double_var, SIZE_UINT32), SIZE_UINT32))
							break;

						if (flip_bytes)
						{
							flip_4_bytes(&double_var);
							fprintf(stdout,"uint32, byte swapped: ");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT32], UINT32_WIDTH,
							        *((uint32 *)&double_var));
							flip_4_bytes(&double_var);
							fprintf(stdout,", (\"%s-endian\": ",
							        endian() == LITTLE_ENDIAN ? "little" : "big");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT32], UINT32_WIDTH,
							        *((uint32 *)&double_var));
							fprintf(stdout, ")\n");
						}
						else
						{
							fprintf(stdout, "uint32: ");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT32], UINT32_WIDTH,
							        *((uint32 *)&double_var));
							fprintf(stdout, "\n");
						}

					break;

#ifdef LONGS_ARE_64

					case INT64_CODE:

						if (check_error(read(data_file, (char *)&double_var, SIZE_UINT64), SIZE_UINT64))
							break;

						if (flip_bytes)
						{
							flip_8_bytes(&double_var);
							fprintf(stdout,"uint64, byte swapped: ");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT64], UINT64_WIDTH,
							        *((uint64 *)&double_var));
							flip_8_bytes(&double_var);
							fprintf(stdout,", (\"%s-endian\": ",
							        endian() == LITTLE_ENDIAN ? "little" : "big");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT64], UINT64_WIDTH,
							        *((uint64 *)&double_var));
							fprintf(stdout, ")\n");
						}
						else
						{
							fprintf(stdout, "uint64: ");
							fprintf(stdout, fft_cnv_flags_width[FFNT_UINT64], UINT64_WIDTH,
							        *((uint64 *)&double_var));
							fprintf(stdout, "\n");
						}

					break;

#endif

					default:
						fprintf(stdout,"Type 'h' or '?' to see options menu.\n");
						last_u_option = ' ';
					break;
				}/* end switch on unsigned types */

			break;

			case 'b': /* toggle between little-endian and big-endian */

				flip_bytes = (flip_bytes) ? 0 : 1;
				if (flip_bytes)
				{
					fprintf(stderr, "Displaying numbers with byte swapping\n");
				}
				else
				{
					/* Say what the native byte order IS */
					fprintf(stderr, "Displaying numbers using your machine's native byte order\n");
				}

			break;

			case 'p': /* position file, don't show file size */

				if (input)
				{
					input = strtok(input, " ");

					/* Check for errors */
					if (!input)
					{
						fprintf(stderr, "Missing blank space after number.");
						exit(1);
					}
					if ((input - input_buffer) >= ops_file_length)
					{
						fprintf(stderr, "Reading past end of input file.");
						exit(1);
					}

					sscanf(input, "%ld", &new_position);
					input += strlen(input) + 1;
				}
				else
				{
					fprintf(stdout,"Input New File Position in Bytes ");
					scanf("%ld", &new_position);

#if FF_OS == FF_OS_UNIX
					os_getch();
#endif

				}

				if (new_position > data_file_length)
				{
					fprintf(stderr,"ERROR: Position not changed.\n");
					fprintf(stderr,"       New position cannot be beyond %ld, the size of %s.\n", data_file_length, argv[1]);
					break;
				}

				file_position = lseek(data_file, new_position, SEEK_SET);
				fprintf(stdout,"New File Position = %ld\n", file_position);
				new_position = 0;

			break;

			case 'P':  /* show file position and size */

				file_position = lseek(data_file, 0L, SEEK_CUR);
				fprintf(stdout,"File Position: %ld\tFile Length: %ld\n", file_position, data_file_length);

			break;

			case 'h':
			case '?':
				show_opt();
			break;

			default:
				fprintf(stdout,"Type 'h' or '?' to see options menu.\n");
		} /* end switch on all types */
		last_option = option;
		if (last_option != 'u')
			last_u_option = ' ';

	}/* end while loop */

	return 0;
}/* end readfile */
Beispiel #24
0
int main(int argc, char *argv[])
{
	char server_buf[256];
	char *server = NULL;
	char *play_file = NULL;
	char *volume = NULL;
	char *seek = NULL;
	int query = 0;
	int i, nr_cmds = 0;
	int context = 'p';

	program_name = argv[0];
	argv++;
	while (1) {
		int idx;
		char *arg;

		idx = get_option(&argv, options, &arg);
		if (idx < 0)
			break;

		flags[idx] = 1;
		switch ((enum flags)idx) {
		case FLAG_HELP:
			printf(usage, program_name, program_name, program_name);
			return 0;
		case FLAG_VERSION:
			printf("cmus " VERSION
			       "\nCopyright 2004-2006 Timo Hirvonen"
			       "\nCopyright 2008-2011 Various Authors\n");
			return 0;
		case FLAG_SERVER:
			server = arg;
			break;
		case FLAG_PASSWD:
			passwd = arg;
			break;
		case FLAG_VOLUME:
			volume = arg;
			nr_cmds++;
			break;
		case FLAG_SEEK:
			seek = arg;
			nr_cmds++;
			break;
		case FLAG_QUERY:
			query = 1;
			nr_cmds++;
			break;
		case FLAG_FILE:
			play_file = arg;
			nr_cmds++;
			break;
		case FLAG_LIBRARY:
			context = 'l';
			break;
		case FLAG_PLAYLIST:
			context = 'p';
			break;
		case FLAG_QUEUE:
			context = 'q';
			break;
		case FLAG_PLAY:
		case FLAG_PAUSE:
		case FLAG_STOP:
		case FLAG_NEXT:
		case FLAG_PREV:
		case FLAG_REPEAT:
		case FLAG_SHUFFLE:
		case FLAG_CLEAR:
			nr_cmds++;
			break;
		case FLAG_RAW:
			raw_args = 1;
			break;
		}
	}

	if (nr_cmds && raw_args)
		die("don't mix raw and cooked stuff\n");

	if (server == NULL) {
		const char *config_dir = getenv("CMUS_HOME");

		if (config_dir && config_dir[0]) {
			snprintf(server_buf, sizeof(server_buf), "%s/socket", config_dir);
		} else {
			const char *home = getenv("HOME");

			if (!home)
				die("error: environment variable HOME not set\n");
			snprintf(server_buf, sizeof(server_buf), "%s/.cmus/socket", home);
		}
		server = server_buf;
	}

	if (!remote_connect(server))
		return 1;

	if (raw_args) {
		while (*argv)
			send_cmd("%s\n", *argv++);
		return 0;
	}

	if (nr_cmds == 0 && argv[0] == NULL) {
		char line[512];

		while (fgets(line, sizeof(line), stdin))
			write_line(line);
		return 0;
	}

	if (flags[FLAG_CLEAR])
		send_cmd("clear -%c\n", context);
	for (i = 0; argv[i]; i++) {
		char *filename = file_url_absolute(argv[i]);

		send_cmd("add -%c %s\n", context, filename);
		free(filename);
	}
	if (flags[FLAG_REPEAT])
		send_cmd("toggle repeat\n");
	if (flags[FLAG_SHUFFLE])
		send_cmd("toggle shuffle\n");
	if (flags[FLAG_STOP])
		send_cmd("player-stop\n");
	if (flags[FLAG_NEXT])
		send_cmd("player-next\n");
	if (flags[FLAG_PREV])
		send_cmd("player-prev\n");
	if (flags[FLAG_PLAY])
		send_cmd("player-play\n");
	if (flags[FLAG_PAUSE])
		send_cmd("player-pause\n");
	if (flags[FLAG_FILE])
		send_cmd("player-play %s\n", file_url_absolute(play_file));
	if (volume)
		send_cmd("vol %s\n", volume);
	if (seek)
		send_cmd("seek %s\n", seek);
	if (query)
		send_cmd("status\n");
	return 0;
}
Beispiel #25
0
void parse_command_line(int argc,
                        const char* argv[],
                        const char** fname1,
                        const char** fname2,
                        const char** objname1,
                        const char** objname2,
                        diff_opt_t* options)
{

    int opt;
    struct exclude_path_list *exclude_head, *exclude_prev, *exclude_node;

    /* process the command-line */
    memset(options, 0, sizeof (diff_opt_t));

    /* assume equal contents initially */
    options->contents = 1;

    /* NaNs are handled by default */
    options->do_nans = 1;

    /* init for exclude-path option */
    exclude_head = NULL;

    /* parse command line options */
    while ((opt = get_option(argc, argv, s_opts, l_opts)) != EOF)
    {
        switch ((char)opt)
        {
        default:
            usage();
            h5diff_exit(EXIT_FAILURE);
        case 'h':
            usage();
            h5diff_exit(EXIT_SUCCESS);
        case 'V':
            print_version(h5tools_getprogname());
            h5diff_exit(EXIT_SUCCESS);
        case 'v':
            options->m_verbose = 1;
            break;
        case 'q':
            /* use quiet mode; supress the message "0 differences found" */
            options->m_quiet = 1;
            break;
        case 'r':
            options->m_report = 1;
            break;
        case 'l':
            options->follow_links = 1;
            break;
        case 'x':
            options->no_dangle_links = 1;
            break;
        case 'E':
            options->exclude_path = 1;
            
            /* create linked list of excluding objects */
            if( (exclude_node = (struct exclude_path_list*) malloc(sizeof(struct exclude_path_list))) == NULL)
            {
                printf("Error: lack of memory!\n");
                h5diff_exit(EXIT_FAILURE);
            }

            /* init */
            exclude_node->obj_path = opt_arg;
            exclude_node->obj_type = H5TRAV_TYPE_UNKNOWN;
            exclude_prev = exclude_head;
            
            if (NULL == exclude_head)            
            {
                exclude_head = exclude_node;
                exclude_head->next = NULL;
            }
            else
            {
                while(NULL != exclude_prev->next)
                    exclude_prev=exclude_prev->next;

                exclude_node->next = NULL;
                exclude_prev->next = exclude_node;
            }            
            break;
        case 'd':
            options->d=1;

            if ( check_d_input( opt_arg )==-1)
            {
                printf("<-d %s> is not a valid option\n", opt_arg );
                usage();
                h5diff_exit(EXIT_FAILURE);
            }
            options->delta = atof( opt_arg );

            /* -d 0 is the same as default */
            if (options->delta == 0)
            options->d=0;

            break;

        case 'p':

            options->p=1;
            if ( check_p_input( opt_arg )==-1)
            {
                printf("<-p %s> is not a valid option\n", opt_arg );
                usage();
                h5diff_exit(EXIT_FAILURE);
            }
            options->percent = atof( opt_arg );

            /* -p 0 is the same as default */
            if (options->percent == 0)
            options->p = 0;

            break;

        case 'n':

            options->n=1;
            if ( check_n_input( opt_arg )==-1)
            {
                printf("<-n %s> is not a valid option\n", opt_arg );
                usage();
                h5diff_exit(EXIT_FAILURE);
            }
            options->count = atol( opt_arg );

            break;

        case 'N':
            options->do_nans = 0;
            break;
        case 'c':
            options->m_list_not_cmp = 1;
            break;
        case 'e':
            options->use_system_epsilon = 1;
            break;
        }
    }

    /* if exclude-path option is used, keep the exclude path list */
    if (options->exclude_path)
        options->exclude = exclude_head;

    /* if use system epsilon, unset -p and -d option */
    if (options->use_system_epsilon)
        options->d = options->p = 0;

    /* check for file names to be processed */
    if (argc <= opt_ind || argv[ opt_ind + 1 ] == NULL)
    {
        error_msg("missing file names\n");
        usage();
        h5diff_exit(EXIT_FAILURE);
    }

    *fname1 = argv[ opt_ind ];
    *fname2 = argv[ opt_ind + 1 ];
    *objname1 = argv[ opt_ind + 2 ];

    if ( *objname1 == NULL )
    {
        *objname2 = NULL;
        return;
    }

    if ( argv[ opt_ind + 3 ] != NULL)
    {
        *objname2 = argv[ opt_ind + 3 ];
    }
    else
    {
        *objname2 = *objname1;
    }


}
Beispiel #26
0
int
main(int argc, char *argv[]) {
  MRI_SURFACE  *mris ;
  char         **av, *in_label_fname, *out_label_fname, *surf_fname, ext[STRLEN] ; ;
  int          ac, nargs ;
  LABEL        *label, *label_out ;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++) {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 4)
    usage_exit() ;

  in_label_fname = argv[1] ;
  surf_fname = argv[2] ;
  out_label_fname = argv[3] ;

  printf("reading label from %s...\n", in_label_fname) ;
  if (!strcmp(FileNameExtension(in_label_fname, ext), "mgz"))
  {
    MRI *mri = MRIread(in_label_fname) ;
    printf("creating label from volumetric inputs with voxval = %d\n", voxval) ;
    if (mri == NULL)
      ErrorExit(ERROR_NOFILE, "%s: could not read input volume from %s", Progname, in_label_fname);
    label = LabelfromASeg(mri, voxval) ;
    MRIfree(&mri) ;
  }
  else
  {
    label = LabelRead(NULL, in_label_fname) ;
    if (!label)
      ErrorExit(ERROR_NOFILE, "%s: could not read label file %s", Progname, in_label_fname) ;
  }
  printf("reading surface from %s...\n", surf_fname) ;
  mris = MRISread(surf_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",Progname, surf_fname) ;
  MRISsaveVertexPositions(mris, ORIGINAL_VERTICES) ;

#if 0
  LabelFillUnassignedVertices(mris, label) ;
#else
  label_out = LabelFillHoles(label, mris, ORIGINAL_VERTICES) ;
#endif
  printf("writing sampled label to %s...\n", out_label_fname) ;
  LabelWrite(label_out, out_label_fname) ;
  MRISfree(&mris) ;
  LabelFree(&label) ;

  exit(0) ;
  return(0) ;  /* for ansi */
}
static int __init lcdtype_setup(char *str)
{
	get_option(&str, &lcdtype);
	return 1;
}
Beispiel #28
0
int
main(int argc, char *argv[])
{
  char               **av, *in_fname, *out_fname, fname[STRLEN], path[STRLEN] ;
  int                ac, nargs, start_t, pass ;
  MRI_SURFACE        *mris ;

  char cmdline[CMD_LINE_LEN] ;

  make_cmd_version_string
  (argc, argv,
   "$Id: mris_smooth.c,v 1.28 2011/03/02 00:04:34 nicks Exp $",
   "$Name: stable5 $", cmdline);

  /* rkt: check for and handle version tag */
  nargs = handle_version_option
          (argc, argv,
           "$Id: mris_smooth.c,v 1.28 2011/03/02 00:04:34 nicks Exp $",
           "$Name: stable5 $");
  if (nargs && argc - nargs == 1)
  {
    exit (0);
  }
  argc -= nargs;

  Progname = argv[0] ;
  ErrorInit(NULL, NULL, NULL) ;
  DiagInit(NULL, NULL, NULL) ;

  ac = argc ;
  av = argv ;
  for ( ; argc > 1 && ISOPTION(*argv[1]) ; argc--, argv++)
  {
    nargs = get_option(argc, argv) ;
    argc -= nargs ;
    argv += nargs ;
  }

  if (argc < 3)
  {
    print_help() ;
  }

  in_fname = argv[1] ;
  out_fname = argv[2] ;
  FileNamePath(out_fname, path) ;

  mris = MRISfastRead(in_fname) ;
  if (!mris)
    ErrorExit(ERROR_NOFILE, "%s: could not read surface file %s",
              Progname, in_fname) ;

  MRISaddCommandLine(mris, cmdline) ;
  MRISremoveTriangleLinks(mris) ;
  fprintf(stderr, "smoothing surface tessellation for %d iterations...\n",
          niterations);

  MRIScomputeMetricProperties(mris) ;
  MRISstoreMetricProperties(mris) ;
  MRISsetNeighborhoodSize(mris, nbrs) ;
#define DT 0.5
  if (gaussian_norm > 0)
  {
    int i, done, start_avgs = gaussian_avgs, j ;

    done = 0;
    start_t = 0 ;
    pass = 0 ;
    do
    {
      for (i = start_t ; i < niterations+start_t ; i++)
      {
        MRIScomputeMetricProperties(mris) ;
        MRISsaveVertexPositions(mris, TMP_VERTICES) ;
        for (j = 0 ; j < 5 ; j++)
        {
          MRISaverageVertexPositions(mris, 2) ; // turn flat spikes into tubular ones
          MRIScomputeMetricProperties(mris) ;
          MRIScomputeSecondFundamentalForm(mris) ;
          MRIShistoThresholdGaussianCurvatureToMarked(mris, (float)(mris->nvertices-20)/mris->nvertices) ;
        }
        MRISrestoreVertexPositions(mris, TMP_VERTICES) ;
        MRIScomputeMetricProperties(mris) ;
        MRISsmoothSurfaceNormals(mris, gaussian_avgs) ;
        MRISclearMarks(mris) ;
        MRISthresholdGaussianCurvatureToMarked(mris, 10, 50);
        MRIScomputeSecondFundamentalForm(mris) ;
        MRIShistoThresholdGaussianCurvatureToMarked(mris, (float)(mris->nvertices-20)/mris->nvertices) ;
        MRISthresholdGaussianCurvatureToMarked(mris, 10, 50);
        if ((write_iterations > 0) && ((i % write_iterations) == 0))
        {
          char fname[STRLEN] ;

          sprintf(fname, "%s%04d", out_fname, i) ;
          printf("writing snapshot to %s...\n", fname) ;
          MRISwrite(mris, fname) ;
          if (Gdiag & DIAG_WRITE)
          {
            MRISuseGaussianCurvature(mris) ;
            sprintf(fname, "%s_K%04d", out_fname, i) ;
            printf("writing curvature to %s...\n", fname) ;
            MRISwriteCurvature(mris, fname) ;
            sprintf(fname, "%s_marked%04d", out_fname, i) ;
            printf("writing marks to %s...\n", fname) ;
            MRISwriteMarked(mris, fname) ;
          }
        }
        for (j = 0 ; j <= 5*nint(1/DT) ; j++)
        {
          MRISmarkedSpringTerm(mris, l_spring) ;
          MRISaverageGradients(mris, gaussian_avgs) ;
          MRISmomentumTimeStep(mris, momentum, DT, 1, gaussian_avgs) ;
          MRISclearGradient(mris) ;
          MRIScomputeMetricProperties(mris) ;
          MRISsmoothSurfaceNormals(mris, gaussian_avgs) ;
          {
            int vno ;
            VERTEX *v ;

            for (vno = 0 ; vno < mris->nvertices ; vno++)
            {
              v = &mris->vertices[vno] ;
              if (v->marked > 0)
              {
                v->K = 1.0/(v->marked) ;
              }
              else
              {
                v->K = 0 ;
              }
            }
          }
        }
      }
      MRISclearGradient(mris) ;
      if (gaussian_avgs == 2)
      {
        if (pass++ > 4)
        {
          done = 1 ;
        }
        else
        {
          int num = count_big_curvatures(mris, 2) ;
          printf("------------------------------------------------------\n") ;
          printf("------------------------------------------------------\n") ;
          printf("------------------ pass %d (num=%d) ------------------\n",
                 pass, num) ;
          printf("------------------------------------------------------\n") ;
          printf("------------------------------------------------------\n") ;
          gaussian_avgs = start_avgs ;
        }
      }
      else
      {
        gaussian_avgs /= 2 ;
        if (done ==0)
        {
          printf("----------------- setting avgs to %d -----------------\n", gaussian_avgs) ;
        }
      }
      start_t = i ;
    }
    while (!done) ;

#if 0
    // more smoothing with principal curvatures
    gaussian_avgs = start_avgs ;
    printf("--------------------------------------------------------------------------\n") ;
    printf("--------------------------------------------------------------------------\n") ;
    printf("---------------------- starting threshold smoothing ----------------------\n") ;
    printf("--------------------------------------------------------------------------\n") ;
    printf("--------------------------------------------------------------------------\n") ;
    do
    {
      for (i = start_t ; i < niterations+start_t ; i++)
      {
        MRIScomputeMetricProperties(mris) ;
        MRIScomputeSecondFundamentalForm(mris) ;
        MRISsmoothSurfaceNormals(mris, 16) ;
#define KTHRESH 1.5  // everything with kmin less than this will not move
        MRISthresholdPrincipalCurvatures(mris, KTHRESH) ;
        MRISspringTermWithGaussianCurvature(mris, gaussian_norm, l_spring) ;
        MRISaverageGradients(mris, gaussian_avgs) ;
        MRISmomentumTimeStep(mris, 0, 0.1, 1, gaussian_avgs) ;
        MRISclearGradient(mris) ;
        if ((write_iterations > 0) && (((i+1) % write_iterations) == 0))
        {
          char fname[STRLEN] ;

          sprintf(fname, "%s%04d", out_fname, i+1) ;
          printf("writing snapshot to %s...\n", fname) ;
          MRISwrite(mris, fname) ;
          if (Gdiag & DIAG_WRITE/* && DIAG_VERBOSE_ON*/)
          {
            MRISuseGaussianCurvature(mris) ;
            sprintf(fname, "%s_K%04d", out_fname, i+1) ;
            printf("writing curvature to %s...\n", fname) ;
            MRISwriteCurvature(mris, fname) ;
          }
        }
      }
      MRISclearGradient(mris) ;
      done = (gaussian_avgs == 2) ;
      gaussian_avgs /= 2 ;
      if (done ==0)
      {
        printf("---------------------- setting avgs to %d ----------------------\n", gaussian_avgs) ;
      }
      start_t = i ;
    }
    while (!done) ;
#endif
  }
  else
  {
    MRISaverageVertexPositions(mris, niterations) ;
  }

  fprintf(stderr, "smoothing complete - recomputing first and second "
          "fundamental forms...\n") ;
  MRIScomputeMetricProperties(mris) ;

  if (rescale)
  {
    MRISscaleBrainArea(mris) ;
  }
  MRIScomputeSecondFundamentalForm(mris) ;
  MRISuseMeanCurvature(mris) ;
  MRISaverageCurvatures(mris, navgs) ;
  if (normalize_flag)
  {
    MRISnormalizeCurvature(mris, which_norm) ;
  }
  sprintf(fname, "%s.%s", mris->hemisphere == LEFT_HEMISPHERE?"lh":"rh",
          curvature_fname);
  if (no_write == 0)
  {
    fprintf(stderr, "writing smoothed curvature to %s/%s\n", path,fname) ;
    MRISwriteCurvature(mris, fname) ;
    sprintf(fname, "%s.%s", mris->hemisphere == LEFT_HEMISPHERE?"lh":"rh",
            area_fname);
    fprintf(stderr, "writing smoothed area to %s/%s\n", path, fname) ;
    MRISwriteArea(mris, fname) ;
  }

  if (Gdiag & DIAG_SHOW)
  {
    fprintf(stderr, "writing smoothed surface to %s\n", out_fname) ;
  }
  MRISwrite(mris, out_fname) ;
  exit(0) ;
  return(0) ;  /* for ansi */
}
Beispiel #29
0
static void i82801gx_power_options(device_t dev)
{
	u8 reg8;
	u16 reg16, pmbase;
	u32 reg32;
	const char *state;
	/* Get the chip configuration */
	config_t *config = dev->chip_info;

	int pwr_on=CONFIG_MAINBOARD_POWER_ON_AFTER_POWER_FAIL;
	int nmi_option;

	/* Which state do we want to goto after g3 (power restored)?
	 * 0 == S0 Full On
	 * 1 == S5 Soft Off
	 *
	 * If the option is not existent (Laptops), use MAINBOARD_POWER_ON.
	 */
	pwr_on = MAINBOARD_POWER_ON;
	get_option(&pwr_on, "power_on_after_fail");

	reg8 = pci_read_config8(dev, GEN_PMCON_3);
	reg8 &= 0xfe;
	switch (pwr_on) {
	case MAINBOARD_POWER_OFF:
		reg8 |= 1;
		state = "off";
		break;
	case MAINBOARD_POWER_ON:
		reg8 &= ~1;
		state = "on";
		break;
	case MAINBOARD_POWER_KEEP:
		reg8 &= ~1;
		state = "state keep";
		break;
	default:
		state = "undefined";
	}

	reg8 |= (3 << 4);	/* avoid #S4 assertions */
	reg8 &= ~(1 << 3);	/* minimum assertion is 1 to 2 RTCCLK */

	pci_write_config8(dev, GEN_PMCON_3, reg8);
	printk(BIOS_INFO, "Set power %s after power failure.\n", state);

	/* Set up NMI on errors. */
	reg8 = inb(0x61);
	reg8 &= 0x0f;		/* Higher Nibble must be 0 */
	reg8 &= ~(1 << 3);	/* IOCHK# NMI Enable */
	// reg8 &= ~(1 << 2);	/* PCI SERR# Enable */
	reg8 |= (1 << 2); /* PCI SERR# Disable for now */
	outb(reg8, 0x61);

	reg8 = inb(0x70);
	nmi_option = NMI_OFF;
	get_option(&nmi_option, "nmi");
	if (nmi_option) {
		printk(BIOS_INFO, "NMI sources enabled.\n");
		reg8 &= ~(1 << 7);	/* Set NMI. */
	} else {
		printk(BIOS_INFO, "NMI sources disabled.\n");
		reg8 |= ( 1 << 7);	/* Can't mask NMI from PCI-E and NMI_NOW */
	}
	outb(reg8, 0x70);

	/* Enable CPU_SLP# and Intel Speedstep, set SMI# rate down */
	reg16 = pci_read_config16(dev, GEN_PMCON_1);
	reg16 &= ~(3 << 0);	// SMI# rate 1 minute
	reg16 |= (1 << 2);	// CLKRUN_EN - Mobile/Ultra only
	reg16 |= (1 << 3);	// Speedstep Enable - Mobile/Ultra only
	reg16 |= (1 << 5);	// CPUSLP_EN Desktop only

	if (config->c4onc3_enable)
		reg16 |= (1 << 7);

	// another laptop wants this?
	// reg16 &= ~(1 << 10);	// BIOS_PCI_EXP_EN - Desktop/Mobile only
	reg16 |= (1 << 10);	// BIOS_PCI_EXP_EN - Desktop/Mobile only
#if DEBUG_PERIODIC_SMIS
	/* Set DEBUG_PERIODIC_SMIS in i82801gx.h to debug using
	 * periodic SMIs.
	 */
	reg16 |= (3 << 0); // Periodic SMI every 8s
#endif
	pci_write_config16(dev, GEN_PMCON_1, reg16);

	// Set the board's GPI routing.
	i82801gx_gpi_routing(dev);

	pmbase = pci_read_config16(dev, 0x40) & 0xfffe;

	outl(config->gpe0_en, pmbase + GPE0_EN);
	outw(config->alt_gp_smi_en, pmbase + ALT_GP_SMI_EN);

	/* Set up power management block and determine sleep mode */
	reg32 = inl(pmbase + 0x04); // PM1_CNT

	reg32 &= ~(7 << 10);	// SLP_TYP
	reg32 |= (1 << 1);	// enable C3->C0 transition on bus master
	reg32 |= (1 << 0);	// SCI_EN
	outl(reg32, pmbase + 0x04);
}
static int __init setup_debug_locks_verbose(char *str)
{
	get_option(&str, &debug_locks_verbose);

	return 1;
}