NGX_TCP_SRV_CONF_OFFSET,
        0,
        NULL },

    { ngx_string("check"),
        NGX_TCP_UPS_CONF|NGX_CONF_1MORE,
        ngx_tcp_upstream_check,
        NGX_TCP_SRV_CONF_OFFSET,
        0,
        NULL },

    { ngx_string("check_http_send"),
        NGX_TCP_UPS_CONF|NGX_CONF_TAKE1,
        ngx_conf_set_str_slot,
        NGX_TCP_SRV_CONF_OFFSET,
        offsetof(ngx_tcp_upstream_srv_conf_t, send),
        NULL },

    { ngx_string("check_smtp_send"),
        NGX_TCP_UPS_CONF|NGX_CONF_TAKE1,
        ngx_conf_set_str_slot,
        NGX_TCP_SRV_CONF_OFFSET,
        offsetof(ngx_tcp_upstream_srv_conf_t, send),
        NULL },

    { ngx_string("check_http_expect_alive"),
        NGX_TCP_UPS_CONF|NGX_CONF_1MORE,
        ngx_conf_set_bitmask_slot,
        NGX_TCP_SRV_CONF_OFFSET,
        offsetof(ngx_tcp_upstream_srv_conf_t, code.status_alive),
        &ngx_check_http_expect_alive_masks },
Beispiel #2
0
    { ngx_string("SSLv2"), NGX_SSL_SSLv2 },
    { ngx_string("SSLv3"), NGX_SSL_SSLv3 },
    { ngx_string("TLSv1"), NGX_SSL_TLSv1 },
    { ngx_string("TLSv1.1"), NGX_SSL_TLSv1_1 },
    { ngx_string("TLSv1.2"), NGX_SSL_TLSv1_2 },
    { ngx_null_string, 0 }
};


static ngx_command_t  ngx_stream_ssl_commands[] = {

    { ngx_string("ssl_handshake_timeout"),
      NGX_STREAM_MAIN_CONF|NGX_STREAM_SRV_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_msec_slot,
      NGX_STREAM_SRV_CONF_OFFSET,
      offsetof(ngx_stream_ssl_conf_t, handshake_timeout),
      NULL },

    { ngx_string("ssl_certificate"),
      NGX_STREAM_MAIN_CONF|NGX_STREAM_SRV_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_str_array_slot,
      NGX_STREAM_SRV_CONF_OFFSET,
      offsetof(ngx_stream_ssl_conf_t, certificates),
      NULL },

    { ngx_string("ssl_certificate_key"),
      NGX_STREAM_MAIN_CONF|NGX_STREAM_SRV_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_str_array_slot,
      NGX_STREAM_SRV_CONF_OFFSET,
      offsetof(ngx_stream_ssl_conf_t, certificate_keys),
      NULL },
Beispiel #3
0
N_NOINLINE(void, purestreamsDatInit)(void) {
static TNimNode* TMP928[7];
static TNimNode* TMP929[2];
static TNimNode TMP923[12];
NTI141629.size = sizeof(tstream141629);
NTI141629.kind = 17;
NTI141629.base = (&NTI1009);
NTI141629.flags = 3;
TMP928[0] = &TMP923[1];
NTI141630.size = sizeof(TY141630);
NTI141630.kind = 25;
NTI141630.base = 0;
NTI141630.flags = 3;
TMP923[1].kind = 1;
TMP923[1].offset = offsetof(tstream141629, Closeimpl);
TMP923[1].typ = (&NTI141630);
TMP923[1].name = "closeImpl";
TMP928[1] = &TMP923[2];
NTI141634.size = sizeof(TY141634);
NTI141634.kind = 25;
NTI141634.base = 0;
NTI141634.flags = 3;
TMP923[2].kind = 1;
TMP923[2].offset = offsetof(tstream141629, Atendimpl);
TMP923[2].typ = (&NTI141634);
TMP923[2].name = "atEndImpl";
TMP928[2] = &TMP923[3];
NTI141638.size = sizeof(TY141638);
NTI141638.kind = 25;
NTI141638.base = 0;
NTI141638.flags = 3;
TMP923[3].kind = 1;
TMP923[3].offset = offsetof(tstream141629, Setpositionimpl);
TMP923[3].typ = (&NTI141638);
TMP923[3].name = "setPositionImpl";
TMP928[3] = &TMP923[4];
NTI141643.size = sizeof(TY141643);
NTI141643.kind = 25;
NTI141643.base = 0;
NTI141643.flags = 3;
TMP923[4].kind = 1;
TMP923[4].offset = offsetof(tstream141629, Getpositionimpl);
TMP923[4].typ = (&NTI141643);
TMP923[4].name = "getPositionImpl";
TMP928[4] = &TMP923[5];
NTI141647.size = sizeof(TY141647);
NTI141647.kind = 25;
NTI141647.base = 0;
NTI141647.flags = 3;
TMP923[5].kind = 1;
TMP923[5].offset = offsetof(tstream141629, Readdataimpl);
TMP923[5].typ = (&NTI141647);
TMP923[5].name = "readDataImpl";
TMP928[5] = &TMP923[6];
NTI141653.size = sizeof(TY141653);
NTI141653.kind = 25;
NTI141653.base = 0;
NTI141653.flags = 3;
TMP923[6].kind = 1;
TMP923[6].offset = offsetof(tstream141629, Writedataimpl);
TMP923[6].typ = (&NTI141653);
TMP923[6].name = "writeDataImpl";
TMP928[6] = &TMP923[7];
NTI141659.size = sizeof(TY141659);
NTI141659.kind = 25;
NTI141659.base = 0;
NTI141659.flags = 3;
TMP923[7].kind = 1;
TMP923[7].offset = offsetof(tstream141629, Flushimpl);
TMP923[7].typ = (&NTI141659);
TMP923[7].name = "flushImpl";
TMP923[0].len = 7; TMP923[0].kind = 2; TMP923[0].sons = &TMP928[0];
NTI141629.node = &TMP923[0];
NTI141999.size = sizeof(tstringstream141999);
NTI141999.kind = 17;
NTI141999.base = (&NTI141629);
NTI141999.flags = 2;
TMP929[0] = &TMP923[9];
TMP923[9].kind = 1;
TMP923[9].offset = offsetof(tstringstream141999, Data);
TMP923[9].typ = (&NTI142);
TMP923[9].name = "data";
TMP929[1] = &TMP923[10];
TMP923[10].kind = 1;
TMP923[10].offset = offsetof(tstringstream141999, Pos);
TMP923[10].typ = (&NTI105);
TMP923[10].name = "pos";
TMP923[8].len = 2; TMP923[8].kind = 2; TMP923[8].sons = &TMP929[0];
NTI141999.node = &TMP923[8];
NTI141997.size = sizeof(tstringstream141999*);
NTI141997.kind = 22;
NTI141997.base = (&NTI141999);
NTI141997.flags = 2;
NTI141997.marker = TMP932;
NTI142109.size = sizeof(tfilestream142109);
NTI142109.kind = 17;
NTI142109.base = (&NTI141629);
NTI142109.flags = 3;
TMP923[11].kind = 1;
TMP923[11].offset = offsetof(tfilestream142109, F);
TMP923[11].typ = (&NTI9004);
TMP923[11].name = "f";
NTI142109.node = &TMP923[11];
NTI142107.size = sizeof(tfilestream142109*);
NTI142107.kind = 22;
NTI142107.base = (&NTI142109);
NTI142107.flags = 2;
NTI142107.marker = TMP934;
NTI141627.size = sizeof(tstream141629*);
NTI141627.kind = 22;
NTI141627.base = (&NTI141629);
NTI141627.flags = 2;
NTI141627.marker = TMP951;
}
    ngx_mail_imap_init_protocol,
    ngx_mail_imap_parse_command,
    ngx_mail_imap_auth_state,

    ngx_string("* BAD internal server error" CRLF),
    ngx_string("* BYE Zimbra IMAP server terminating connection" CRLF)
};


static ngx_command_t  ngx_mail_imap_commands[] = {

    { ngx_string("imap_client_buffer"),
      NGX_MAIL_MAIN_CONF|NGX_MAIL_SRV_CONF|NGX_CONF_TAKE1,
      ngx_conf_set_size_slot,
      NGX_MAIL_SRV_CONF_OFFSET,
      offsetof(ngx_mail_imap_srv_conf_t, client_buffer_size),
      NULL },

    { ngx_string("imap_capabilities"),
      NGX_MAIL_MAIN_CONF|NGX_MAIL_SRV_CONF|NGX_CONF_1MORE,
      ngx_mail_capabilities,
      NGX_MAIL_SRV_CONF_OFFSET,
      offsetof(ngx_mail_imap_srv_conf_t, capabilities),
      NULL },

    { ngx_string("imap_id"),
      NGX_MAIL_MAIN_CONF|NGX_MAIL_SRV_CONF|NGX_CONF_1MORE,
      ngx_mail_imap_id,
      NGX_MAIL_SRV_CONF_OFFSET,
      offsetof(ngx_mail_imap_srv_conf_t, id_params),
      NULL },
static ngx_command_t  ngx_http_eval_commands[] = {

    {   ngx_string("eval"),
        NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE|NGX_CONF_BLOCK,
        ngx_http_eval_block,
        NGX_HTTP_LOC_CONF_OFFSET,
        0,
        NULL
    },

    {   ngx_string("eval_escalate"),
        NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
        ngx_conf_set_flag_slot,
        NGX_HTTP_LOC_CONF_OFFSET,
        offsetof(ngx_http_eval_loc_conf_t, escalate),
        NULL
    },

    {   ngx_string("eval_override_content_type"),
        NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1,
        ngx_conf_set_str_slot,
        NGX_HTTP_LOC_CONF_OFFSET,
        offsetof(ngx_http_eval_loc_conf_t, override_content_type),
        NULL
    },

    {   ngx_string("eval_subrequest_in_memory"),
        NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
        ngx_http_eval_subrequest_in_memory,
        NGX_HTTP_LOC_CONF_OFFSET,
static TNC_Result receive_message(TNC_IMCID imc_id,
								  TNC_ConnectionID connection_id,
								  TNC_UInt32 msg_flags,
								  chunk_t msg,
								  TNC_VendorID msg_vid,
								  TNC_MessageSubtype msg_subtype,
								  TNC_UInt32 src_imv_id,
								  TNC_UInt32 dst_imc_id)
{
	pa_tnc_msg_t *pa_tnc_msg;
	pa_tnc_attr_t *attr;
	pen_type_t attr_type;
	linked_list_t *attr_list;
	imc_state_t *state;
	enumerator_t *enumerator;
	TNC_Result result;
	TNC_UInt32 target_imc_id;
	bool fatal_error;

	if (!imc_android)
	{
		DBG1(DBG_IMC, "IMC \"%s\" has not been initialized", imc_name);
		return TNC_RESULT_NOT_INITIALIZED;
	}

	/* get current IMC state */
	if (!imc_android->get_state(imc_android, connection_id, &state))
	{
		return TNC_RESULT_FATAL;
	}

	/* parse received PA-TNC message and automatically handle any errors */
	result = imc_android->receive_message(imc_android, state, msg, msg_vid,
							msg_subtype, src_imv_id, dst_imc_id, &pa_tnc_msg);

	/* no parsed PA-TNC attributes available if an error occurred */
	if (!pa_tnc_msg)
	{
		return result;
	}
	target_imc_id = (dst_imc_id == TNC_IMCID_ANY) ? imc_id : dst_imc_id;

	/* preprocess any IETF standard error attributes */
	fatal_error = pa_tnc_msg->process_ietf_std_errors(pa_tnc_msg);

	/* analyze PA-TNC attributes */
	attr_list = linked_list_create();
	enumerator = pa_tnc_msg->create_attribute_enumerator(pa_tnc_msg);
	while (enumerator->enumerate(enumerator, &attr))
	{
		attr_type = attr->get_type(attr);

		if (attr_type.vendor_id != PEN_IETF)
		{
			continue;
		}
		if (attr_type.type == IETF_ATTR_ATTRIBUTE_REQUEST)
		{
			ietf_attr_attr_request_t *attr_cast;
			pen_type_t *entry;
			enumerator_t *e;

			attr_cast = (ietf_attr_attr_request_t*)attr;

			e = attr_cast->create_enumerator(attr_cast);
			while (e->enumerate(e, &entry))
			{
				if (entry->vendor_id != PEN_IETF)
				{
					continue;
				}
				switch (entry->type)
				{
					case IETF_ATTR_PRODUCT_INFORMATION:
						add_product_info(attr_list);
						break;
					case IETF_ATTR_STRING_VERSION:
						add_string_version(attr_list);
						break;
					case IETF_ATTR_INSTALLED_PACKAGES:
						add_installed_packages(attr_list);
						break;
					default:
						break;
				}
			}
			e->destroy(e);
		}
		else if (attr_type.type == IETF_ATTR_ASSESSMENT_RESULT)
		{
			ietf_attr_assess_result_t *attr_cast;

			attr_cast = (ietf_attr_assess_result_t*)attr;
			state->set_result(state, target_imc_id,
							  attr_cast->get_result(attr_cast));
		}
	}
	enumerator->destroy(enumerator);
	pa_tnc_msg->destroy(pa_tnc_msg);

	if (fatal_error)
	{
		attr_list->destroy_offset(attr_list, offsetof(pa_tnc_attr_t, destroy));
		return TNC_RESULT_FATAL;
	}

	if (attr_list->get_count(attr_list))
	{
		result = imc_android->send_message(imc_android, connection_id, TRUE, imc_id,
									  src_imv_id, attr_list);
	}
	else
	{
		result = TNC_RESULT_SUCCESS;
	}
	attr_list->destroy(attr_list);

	return result;
}
Beispiel #7
0
    0,                                  /*tp_repr*/
    0,                                  /*tp_as_number*/
    0,                                  /*tp_as_sequence*/
    0,                                  /*tp_as_mapping*/
    0,                                  /*tp_hash*/
    0,                                  /*tp_call*/
    0,                                  /*tp_str*/
    0,                                  /*tp_getattro*/
    0,                                  /*tp_setattro*/
    0,                                  /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT,                 /*tp_flags*/
    0,                                  /*tp_doc*/
    0,                                  /*tp_traverse*/
    0,                                  /*tp_clear*/
    0,                                  /*tp_richcompare*/
    offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/
    0,                                  /*tp_iter*/
    0,                                  /*tp_iternext*/
    lock_methods,                       /*tp_methods*/
};

/* Recursive lock objects */

typedef struct {
    PyObject_HEAD
    PyThread_type_lock rlock_lock;
    long rlock_owner;
    unsigned long rlock_count;
    PyObject *in_weakreflist;
} rlockobject;
Beispiel #8
0
void IOBuf::operator delete(void* ptr) {
  auto* storageAddr = static_cast<uint8_t*>(ptr) - offsetof(HeapStorage, buf);
  auto* storage = reinterpret_cast<HeapStorage*>(storageAddr);
  releaseStorage(storage, kIOBufInUse);
}
Beispiel #9
0
/**Send a request message.
 *
 * @retval 0 if request is pending
 * @retval >=1 if error event has been sent
 * @retval < 0 if no error event has been sent
 */
static
int nua_client_request_sendmsg(nua_client_request_t *cr)
{
  nua_handle_t *nh = cr->cr_owner;
  nua_dialog_state_t *ds = nh->nh_ds;
  sip_method_t method = cr->cr_method;
  char const *name = cr->cr_method_name;
  url_string_t const *url = (url_string_t *)cr->cr_target;
  nta_leg_t *leg;
  msg_t *msg;
  sip_t *sip;
  int error;

  assert(cr->cr_orq == NULL);

  cr->cr_offer_sent = cr->cr_answer_recv = 0;
  cr->cr_offer_recv = cr->cr_answer_sent = 0;

  if (!ds->ds_leg && cr->cr_dialog) {
    ds->ds_leg = nta_leg_tcreate(nh->nh_nua->nua_nta,
				 nua_stack_process_request, nh,
				 SIPTAG_CALL_ID(cr->cr_sip->sip_call_id),
				 SIPTAG_FROM(cr->cr_sip->sip_from),
				 SIPTAG_TO(cr->cr_sip->sip_to),
				 SIPTAG_CSEQ(cr->cr_sip->sip_cseq),
				 TAG_END());
    if (!ds->ds_leg)
      return -1;
  }

  if (cr->cr_sip->sip_from && ds->ds_leg) {
    if (cr->cr_sip->sip_from->a_tag == NULL) {
      if (sip_from_tag(msg_home(cr->cr_msg), cr->cr_sip->sip_from,
		       nta_leg_tag(ds->ds_leg, NULL)) < 0) {
	return -1;
      }
    }
  }

  cr->cr_retry_count++;

  if (ds->ds_leg)
    leg = ds->ds_leg;
  else
    leg = nh->nh_nua->nua_dhandle->nh_ds->ds_leg; /* Default leg */

  msg = msg_copy(cr->cr_msg), sip = sip_object(msg);

  if (msg == NULL)
    return -1;

  if (nua_dialog_is_established(ds)) {
    while (sip->sip_route)
      sip_route_remove(msg, sip);
  }
  else if (!ds->ds_route) {
    sip_route_t *initial_route = NH_PGET(nh, initial_route);

    if (initial_route) {
      initial_route = sip_route_dup(msg_home(msg), initial_route);
      if (!initial_route) return -1;
      msg_header_prepend(msg, (msg_pub_t*)sip,
			 /* This should be
			    (msg_header_t **)&sip->sip_route
			  * but directly casting pointer &sip->sip_route gives
			  * spurious type-punning warning */
			 (msg_header_t **)((char *)sip + offsetof(sip_t, sip_route)),
			 (msg_header_t *)initial_route);
    }
  }


  /**
   * For in-dialog requests, the request URI is taken from the @Contact
   * header received from the remote party during dialog establishment,
   * and the NUTAG_URL() is ignored.
   *
   * Also, the @CallID and @CSeq headers and @From and @To tags are
   * generated based on the dialog information and added to the request.
   * If the dialog has a route, it is added to the request, too.
   */
  if (nta_msg_request_complete(msg, leg, method, name, url) < 0) {
    msg_destroy(msg);
    return -1;
  }

  /**@MaxForwards header (with default value set by NTATAG_MAX_FORWARDS()) is
   * also added now, if it does not exist.
   */

  if (!ds->ds_remote)
    ds->ds_remote = sip_to_dup(nh->nh_home, sip->sip_to);
  if (!ds->ds_local)
    ds->ds_local = sip_from_dup(nh->nh_home, sip->sip_from);

  /**
   * Next, values previously set with nua_set_params() or nua_set_hparams()
   * are used: @Allow, @Supported, @Organization, @UserAgent and
   * @AllowEvents headers are added to the request if they are not already
   * set.
   */
  if (!sip->sip_allow)
    sip_add_dup(msg, sip, (sip_header_t*)NH_PGET(nh, allow));

  if (!sip->sip_supported && NH_PGET(nh, supported))
    sip_add_dup(msg, sip, (sip_header_t *)NH_PGET(nh, supported));

  if (method == sip_method_register && NH_PGET(nh, path_enable) &&
      !sip_has_feature(sip->sip_supported, "path") &&
      !sip_has_feature(sip->sip_require, "path"))
    sip_add_make(msg, sip, sip_supported_class, "path");

  if (!sip->sip_organization && NH_PGET(nh, organization))
    sip_add_make(msg, sip, sip_organization_class, NH_PGET(nh, organization));

  if (!sip->sip_user_agent && NH_PGET(nh, user_agent))
    sip_add_make(msg, sip, sip_user_agent_class, NH_PGET(nh, user_agent));

  if (!sip->sip_via && NH_PGET(nh, via))
    sip_add_make(msg, sip, sip_via_class, NH_PGET(nh, via));

  /** Any node implementing one or more event packages SHOULD include an
   * appropriate @AllowEvents header indicating all supported events in
   * all methods which initiate dialogs and their responses (such as
   * INVITE) and OPTIONS responses.
   */
  if (!sip->sip_allow_events &&
      NH_PGET(nh, allow_events) &&
      (method == sip_method_notify || /* Always in NOTIFY */
       (!ds->ds_remote_tag &&	      /* And in initial requests */
	(method == sip_method_subscribe || method == sip_method_refer ||
	 method == sip_method_options ||
	 method == sip_method_invite))))
    sip_add_dup(msg, sip, (void *)NH_PGET(nh, allow_events));

  /**
   * Next, the stack generates a @Contact header for the request (unless
   * the application already gave a @Contact header or it does not want to
   * use @Contact and indicates that by including SIPTAG_CONTACT(NULL) or
   * SIPTAG_CONTACT(SIP_NONE) in the tagged parameters.) If the
   * application has registered the URI in @From header, the @Contact
   * header used with registration is used. Otherwise, the @Contact header
   * is generated from the local IP address and port number.
   */

  /**For the initial requests, @ServiceRoute set that was received from the
   * registrar is also added to the request message.
   */
  if (cr->cr_method != sip_method_register) {
    if (cr->cr_contactize && cr->cr_has_contact) {
      sip_contact_t *ltarget = sip_contact_dup(nh->nh_home, sip->sip_contact);
      if (ds->ds_ltarget)
	msg_header_free(nh->nh_home, (msg_header_t *)ds->ds_ltarget);
      ds->ds_ltarget = ltarget;
    }

    if (ds->ds_ltarget && !cr->cr_has_contact)
      sip_add_dup(msg, sip, (sip_header_t *)ds->ds_ltarget);

    if (nua_registration_add_contact_to_request(nh, msg, sip,
						cr->cr_contactize &&
						!cr->cr_has_contact &&
						!ds->ds_ltarget,
						!ds->ds_route) < 0) {
      msg_destroy(msg);
      return -1;
    }
  }

  cr->cr_wait_for_cred = 0;

  if (cr->cr_methods->crm_send)
    error = cr->cr_methods->crm_send(cr, msg, sip, NULL);
  else
    error = nua_base_client_request(cr, msg, sip, NULL);

  if (error == -1)
    msg_destroy(msg);

  return error;
}
        self->model->axis_theta.dispersion->accept_as_source(visitor, self->model->axis_theta.dispersion, disp_dict);
        PyDict_SetItemString(self->dispersion, "axis_theta", disp_dict);


         
        // Create empty log
        self->log = PyDict_New();
        
        

    }
    return 0;
}

static PyMemberDef CCoreShellEllipsoidModel_members[] = {
    {"params", T_OBJECT, offsetof(CCoreShellEllipsoidModel, params), 0,
     "Parameters"},
	{"dispersion", T_OBJECT, offsetof(CCoreShellEllipsoidModel, dispersion), 0,
	  "Dispersion parameters"},     
    {"log", T_OBJECT, offsetof(CCoreShellEllipsoidModel, log), 0,
     "Log"},
    {NULL}  /* Sentinel */
};

/** Read double from PyObject
    @param p PyObject
    @return double
*/
double CCoreShellEllipsoidModel_readDouble(PyObject *p) {
    if (PyFloat_Check(p)==1) {
        return (double)(((PyFloatObject *)(p))->ob_fval);
Beispiel #11
0
struct Font
{
  Font();
  ~Font();

  Texture2D texture;

  size_t spaceAdvance;
  std::vector<Glyph> glyphs;
  std::unordered_map<size_t, Glyph*> glyphMap;
};

static const VertexAttribute vertexAttribute =
{
  VertexSemantic::Position, GL_FLOAT, 4, offsetof(Vertex, position)
};

// TODO: Currently the buffer is 4 vertices per glyph!
// Improve performance by using a texture atlas to enable multiple character positions to be
// passed to the GPU at once.
// Improve things even more by using a geometry shader.
static const size_t VerticesPerGlyph = 4;
static const size_t VerticesInBuffer = 2048;
static Vertex vertices[VerticesInBuffer * VerticesPerGlyph];

static const size_t GlyphTextureSlot = 0;

//----------------------------------------------------------------------

static boost::shared_ptr<Font> CreateFont(const char* const filename);
static __inline__ unsigned int
nwi_state_compute_size(unsigned int n)
{
	return (offsetof(nwi_state, nwi_ifstates[n]));

}
Beispiel #13
0
    {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS,
        PyDoc_STR("setstate(state)")},
    {NULL,      NULL},
};

static int
spamdict_init(spamdictobject *self, PyObject *args, PyObject *kwds)
{
    if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
        return -1;
    self->state = 0;
    return 0;
}

static PyMemberDef spamdict_members[] = {
    {"state", T_INT, offsetof(spamdictobject, state), READONLY,
     PyDoc_STR("an int variable for demonstration purposes")},
    {0}
};

static PyTypeObject spamdict_type = {
    PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
    "xxsubtype.spamdict",
    sizeof(spamdictobject),
    0,
    0,                                          /* tp_dealloc */
    0,                                          /* tp_print */
    0,                                          /* tp_getattr */
    0,                                          /* tp_setattr */
    0,                                          /* tp_reserved */
    0,                                          /* tp_repr */
Beispiel #14
0
int main(int argc, char *argv[])
{
	p_mem_t shared_mem, results_mem;
	uint32_t eram_base;
	char results[1024] = { '\0' };
	int device_cols, device_rows, nside;
	p_dev_t dev;
	p_prog_t prog;
	p_team_t team;
	p_coords_t size;
	p_coords_t start = { .row = 0, .col = 0 };

	unsigned int msize;
	float        seed;
	unsigned int addr; //, clocks;
	size_t       sz;
	int          verbose=0;
	double       tdiff[3];
	int          result, retval = 0;

	msize     = 0x00400000;

	get_args(argc, argv);

	fo = stderr;
	fi = stdin;
	printf( "------------------------------------------------------------\n");
	printf( "Calculating:   C[%d][%d] = A[%d][%d] * B[%d][%d]\n", _Smtx, _Smtx, _Smtx, _Smtx, _Smtx, _Smtx);
	seed = 0.0;
	if(verbose){
	  printf( "Seed = %f\n", seed);
	}

	dev = p_init(P_DEV_EPIPHANY, 0);
	if (p_error(dev)) {
		fprintf(stderr, "Error initializing PAL\n");
		return p_error(dev);
	}

	device_cols = p_query(dev, P_PROP_COLS);
	device_rows = p_query(dev, P_PROP_ROWS);

	// Use min size
	nside = device_cols > device_rows ? device_cols : device_rows;

	if (nside < 4) {
		fprintf(stderr, "Error: Too small device, need at least 4x4\n");
		return 1;
	}

	// Either 1024, 256, 64, or 16 cores (side must be power of two),
	nside = nside >= 32 ? 32 : nside >= 16 ? 16 : nside >= 8 ? 8 : 4;

	size.row = nside;
	size.col = nside;
	team = p_open4(dev, P_TOPOLOGY_2D, &start, &size);
	printf("Using team of size %d\n", p_team_size(team));
	if (p_error(team)) {
		fprintf(stderr, "Error opening team\n");
		return p_error(team);
	}

	prog = p_load(dev, ar.elfFile, 0);

	eram_base = (unsigned) p_query(dev, P_PROP_MEMBASE);
	shared_mem = p_map(dev, eram_base, msize);

	// Clear mailbox contents
	memset(&Mailbox, 0, sizeof(Mailbox));
	p_write(&shared_mem, &Mailbox, 0, sizeof(Mailbox), 0);

	// Generate operand matrices based on a provided seed
	matrix_init((int)seed);

#ifdef __WIPE_OUT_RESULT_MATRIX__
	// Wipe-out any previous remains in result matrix (for verification)
	addr = offsetof(shared_buf_t, C[0]);
	sz = sizeof(Mailbox.C);
	if(verbose){
	  printf( "Writing C[%uB] to address %08x...\n", (unsigned) sz, addr);
	}
	p_write(&shared_mem, (void *) Mailbox.C, addr, sz, 0);
#endif

	/* Wallclock time */
	clock_gettime(CLOCK_MONOTONIC, &timer[0]);
	/* Clock CPUTIME too. We don't want to indicate failure just
	 * because the system was under high load. */
	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &timer[4]);

	// Copy operand matrices to Epiphany system
	addr = offsetof(shared_buf_t, A[0]);
	sz = sizeof(Mailbox.A);
	if(verbose){
	  printf( "Writing A[%uB] to address %08x...\n", (unsigned) sz, addr);
	}
	p_write(&shared_mem, (void *) Mailbox.A, addr, sz, 0);

	addr = offsetof(shared_buf_t, B[0]);
	sz = sizeof(Mailbox.B);
	if(verbose){
	  printf( "Writing B[%uB] to address %08x...\n", (unsigned) sz, addr);
	}
	p_write(&shared_mem, (void *) Mailbox.B, addr, sz, 0);
	// Call the Epiphany matmul() function

	if(verbose){
	  printf( "GO Epiphany! ...   ");
	}
	if(verbose){
	  printf("Loading program on Epiphany chip...\n");
	}

	p_arg_t args[] = { &nside, sizeof(nside), true };
	if (p_run(prog, "matmul", team, 0, p_team_size(team), 1, args, 0)) {
		fprintf(stderr, "Error loading Epiphany program.\n");
		exit(1);
	}

	// Read result matrix and timing
	addr = offsetof(shared_buf_t, C[0]);
	sz = sizeof(Mailbox.C);
	if(verbose){
	  printf( "Reading result from address %08x...\n", addr);
	}
	p_read(&shared_mem, (void *) Mailbox.C, addr, sz, 0);

	clock_gettime(CLOCK_MONOTONIC, &timer[1]);
	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &timer[5]);


	// Calculate a reference result
	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &timer[2]);
#ifndef __DO_STRASSEN__
	matmul(Mailbox.A, Mailbox.B, Cref, _Smtx);
#else
	matmul_strassen(Mailbox.A, Mailbox.B, Cref, _Smtx);
#endif
	clock_gettime(CLOCK_THREAD_CPUTIME_ID, &timer[3]);
	addr = offsetof(shared_buf_t, core.clocks);
	sz = sizeof(Mailbox.core.clocks);
	if(verbose){
	  printf( "Reading time from address %08x...\n", addr);
	}
	p_read(&shared_mem, &Mailbox.core.clocks, addr, sizeof(Mailbox.core.clocks), 0);
//	clocks = Mailbox.core.clocks;





	// Calculate the difference between the Epiphany result and the reference result
	matsub(Mailbox.C, Cref, Cdiff, _Smtx);

	tdiff[0] = (timer[1].tv_sec - timer[0].tv_sec) * 1000 + ((double) (timer[1].tv_nsec - timer[0].tv_nsec) / 1000000.0);
//	tdiff[0] = ((double) clocks) / eMHz * 1000;
	tdiff[1] = (timer[3].tv_sec - timer[2].tv_sec) * 1000 + ((double) (timer[3].tv_nsec - timer[2].tv_nsec) / 1000000.0);
	tdiff[2] = (timer[5].tv_sec - timer[4].tv_sec) * 1000 + ((double) (timer[5].tv_nsec - timer[4].tv_nsec) / 1000000.0);


	// If the difference is 0, then the matrices are identical and the
	// calculation was correct
	if (iszero(Cdiff, _Smtx))
	  {

	    printf( "Epiphany(time) %9.1f msec  (@ %03d MHz)\n", tdiff[0], eMHz);
	    printf( "Host(time)     %9.1f msec  (@ %03d MHz)\n", tdiff[1], aMHz);
	    printf( "------------------------------------------------------------\n");
	    printf( "TEST \"matmul-16\" PASSED\n");
	    retval = 0;
	} else {
	  printf( "\n\nERROR: C_epiphany is different from C_host !!!\n");
	  printf( "TEST \"matmul-16\" FAILED\n");
	  retval = 1;
	}

#if 0
#ifdef __DUMP_MATRICES__
	printf( "\n\n\n");
	printf( "A[][] = \n");
	matprt(Mailbox.A, _Smtx);
	printf( "B[][] = \n");
	matprt(Mailbox.B, _Smtx);
	printf( "C[][] = \n");
	matprt(Mailbox.C, _Smtx);
	printf( "Cref[][] = \n");
	matprt(Cref, _Smtx);

	int i, j;
	for (i=0; i<_Nside; i++)
		for (j=0; j<_Nside; j++)
		{
			e_read(pEpiphany, i, j, 0x2000+0*sizeof(float), &Aepi[(i*_Score+0)*_Smtx + j*_Score], 2*sizeof(float));
			e_read(pEpiphany, i, j, 0x2000+2*sizeof(float), &Aepi[(i*_Score+1)*_Smtx + j*_Score], 2*sizeof(float));
			e_read(pEpiphany, i, j, 0x4000+0*sizeof(float), &Bepi[(i*_Score+0)*_Smtx + j*_Score], 2*sizeof(float));
			e_read(pEpiphany, i, j, 0x4000+2*sizeof(float), &Bepi[(i*_Score+1)*_Smtx + j*_Score], 2*sizeof(float));
		}
	printf( "Aepi[][] = \n");
	matprt(Aepi, _Smtx);
	printf( "Bepi[][] = \n");
	matprt(Bepi, _Smtx);
#endif
#endif



	// p_unmap ...
	p_close(team);
	p_finalize(dev);

	return retval;
}


// Initialize operand matrices
void matrix_init(int seed)
{
	int i, j, p;

	p = 0;
	for (i=0; i<_Smtx; i++)
		for (j=0; j<_Smtx; j++)
			Mailbox.A[p++] = (i + j + seed) % _MAX_MEMBER_;

	p = 0;
	for (i=0; i<_Smtx; i++)
		for (j=0; j<_Smtx; j++)
			Mailbox.B[p++] = ((i + j) * 2 + seed) % _MAX_MEMBER_;

	p = 0;
	for (i=0; i<_Smtx; i++)
		for (j=0; j<_Smtx; j++)
			Mailbox.C[p++] = 0x8dead;

	return;
}
/*
 * Lookup an entry in a shortform directory.
 * Returns EEXIST if found, ENOENT if not found.
 */
int						/* error */
xfs_dir2_sf_lookup(
    xfs_da_args_t		*args)		/* operation arguments */
{
    xfs_inode_t		*dp;		/* incore directory inode */
    int			i;		/* entry index */
    xfs_dir2_sf_entry_t	*sfep;		/* shortform directory entry */
    xfs_dir2_sf_t		*sfp;		/* shortform structure */

    xfs_dir2_trace_args("sf_lookup", args);
    xfs_dir2_sf_check(args);
    dp = args->dp;

    ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
    /*
     * Bail out if the directory is way too short.
     */
    if (dp->i_d.di_size < offsetof(xfs_dir2_sf_hdr_t, parent)) {
        ASSERT(XFS_FORCED_SHUTDOWN(dp->i_mount));
        return XFS_ERROR(EIO);
    }
    ASSERT(dp->i_df.if_bytes == dp->i_d.di_size);
    ASSERT(dp->i_df.if_u1.if_data != NULL);
    sfp = (xfs_dir2_sf_t *)dp->i_df.if_u1.if_data;
    ASSERT(dp->i_d.di_size >= XFS_DIR2_SF_HDR_SIZE(sfp->hdr.i8count));
    /*
     * Special case for .
     */
    if (args->namelen == 1 && args->name[0] == '.') {
        args->inumber = dp->i_ino;
        return XFS_ERROR(EEXIST);
    }
    /*
     * Special case for ..
     */
    if (args->namelen == 2 &&
            args->name[0] == '.' && args->name[1] == '.') {
        args->inumber = XFS_DIR2_SF_GET_INUMBER(sfp, &sfp->hdr.parent);
        return XFS_ERROR(EEXIST);
    }
    /*
     * Loop over all the entries trying to match ours.
     */
    for (i = 0, sfep = XFS_DIR2_SF_FIRSTENTRY(sfp);
            i < sfp->hdr.count;
            i++, sfep = XFS_DIR2_SF_NEXTENTRY(sfp, sfep)) {
        if (sfep->namelen == args->namelen &&
                sfep->name[0] == args->name[0] &&
                memcmp(args->name, sfep->name, args->namelen) == 0) {
            args->inumber =
                XFS_DIR2_SF_GET_INUMBER(sfp,
                                        XFS_DIR2_SF_INUMBERP(sfep));
            return XFS_ERROR(EEXIST);
        }
    }
    /*
     * Didn't find it.
     */
    ASSERT(args->oknoent);
    return XFS_ERROR(ENOENT);
}
Beispiel #16
0
static PyObject *
OscBank_setFjit(OscBank *self, PyObject *arg)
{
    int isInt = PyInt_Check(arg);

	if (isInt) {
        self->fjit = PyInt_AS_LONG(arg);
    }

	Py_INCREF(Py_None);
	return Py_None;
}

static PyMemberDef OscBank_members[] = {
    {"server", T_OBJECT_EX, offsetof(OscBank, server), 0, "Pyo server."},
    {"stream", T_OBJECT_EX, offsetof(OscBank, stream), 0, "Stream object."},
    {"table", T_OBJECT_EX, offsetof(OscBank, table), 0, "Waveform table."},
    {"freq", T_OBJECT_EX, offsetof(OscBank, freq), 0, "Base frequency in Hertz."},
    {"spread", T_OBJECT_EX, offsetof(OscBank, spread), 0, "Frequencies spreading factor."},
    {"slope", T_OBJECT_EX, offsetof(OscBank, slope), 0, "Amplitude slope factor."},
    {"frndf", T_OBJECT_EX, offsetof(OscBank, frndf), 0, "Frequency of random frequency changes."},
    {"frnda", T_OBJECT_EX, offsetof(OscBank, frnda), 0, "Amplitude of random frequency changes."},
    {"mul", T_OBJECT_EX, offsetof(OscBank, mul), 0, "Mul factor."},
    {"add", T_OBJECT_EX, offsetof(OscBank, add), 0, "Add factor."},
    {NULL}  /* Sentinel */
};

static PyMethodDef OscBank_methods[] = {
    {"getTable", (PyCFunction)OscBank_getTable, METH_NOARGS, "Returns waveform table object."},
    {"getServer", (PyCFunction)OscBank_getServer, METH_NOARGS, "Returns server object."},
/*
 * Remove an entry from a shortform directory.
 */
int						/* error */
xfs_dir2_sf_removename(
    xfs_da_args_t		*args)
{
    int			byteoff;	/* offset of removed entry */
    xfs_inode_t		*dp;		/* incore directory inode */
    int			entsize;	/* this entry's size */
    int			i;		/* shortform entry index */
    int			newsize;	/* new inode size */
    int			oldsize;	/* old inode size */
    xfs_dir2_sf_entry_t	*sfep;		/* shortform directory entry */
    xfs_dir2_sf_t		*sfp;		/* shortform structure */

    xfs_dir2_trace_args("sf_removename", args);
    dp = args->dp;

    ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
    oldsize = (int)dp->i_d.di_size;
    /*
     * Bail out if the directory is way too short.
     */
    if (oldsize < offsetof(xfs_dir2_sf_hdr_t, parent)) {
        ASSERT(XFS_FORCED_SHUTDOWN(dp->i_mount));
        return XFS_ERROR(EIO);
    }
    ASSERT(dp->i_df.if_bytes == oldsize);
    ASSERT(dp->i_df.if_u1.if_data != NULL);
    sfp = (xfs_dir2_sf_t *)dp->i_df.if_u1.if_data;
    ASSERT(oldsize >= XFS_DIR2_SF_HDR_SIZE(sfp->hdr.i8count));
    /*
     * Loop over the old directory entries.
     * Find the one we're deleting.
     */
    for (i = 0, sfep = XFS_DIR2_SF_FIRSTENTRY(sfp);
            i < sfp->hdr.count;
            i++, sfep = XFS_DIR2_SF_NEXTENTRY(sfp, sfep)) {
        if (sfep->namelen == args->namelen &&
                sfep->name[0] == args->name[0] &&
                memcmp(sfep->name, args->name, args->namelen) == 0) {
            ASSERT(XFS_DIR2_SF_GET_INUMBER(sfp,
                                           XFS_DIR2_SF_INUMBERP(sfep)) ==
                   args->inumber);
            break;
        }
    }
    /*
     * Didn't find it.
     */
    if (i == sfp->hdr.count) {
        return XFS_ERROR(ENOENT);
    }
    /*
     * Calculate sizes.
     */
    byteoff = (int)((char *)sfep - (char *)sfp);
    entsize = XFS_DIR2_SF_ENTSIZE_BYNAME(sfp, args->namelen);
    newsize = oldsize - entsize;
    /*
     * Copy the part if any after the removed entry, sliding it down.
     */
    if (byteoff + entsize < oldsize)
        memmove((char *)sfp + byteoff, (char *)sfp + byteoff + entsize,
                oldsize - (byteoff + entsize));
    /*
     * Fix up the header and file size.
     */
    sfp->hdr.count--;
    dp->i_d.di_size = newsize;
    /*
     * Reallocate, making it smaller.
     */
    xfs_idata_realloc(dp, newsize - oldsize, XFS_DATA_FORK);
    sfp = (xfs_dir2_sf_t *)dp->i_df.if_u1.if_data;
#if XFS_BIG_INUMS
    /*
     * Are we changing inode number size?
     */
    if (args->inumber > XFS_DIR2_MAX_SHORT_INUM) {
        if (sfp->hdr.i8count == 1)
            xfs_dir2_sf_toino4(args);
        else
            sfp->hdr.i8count--;
    }
#endif
    xfs_dir2_sf_check(args);
    xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_DDATA);
    return 0;
}
Beispiel #18
0
void RenderableStars::update(const UpdateData& data) {
    if (_dataIsDirty) {
        const int value = _colorOption;
        LDEBUG("Regenerating data");

        createDataSlice(ColorOption(value));

        int size = static_cast<int>(_slicedData.size());

        if (_vao == 0) {
            glGenVertexArrays(1, &_vao);
            LDEBUG("Generating Vertex Array id '" << _vao << "'");
        }
        if (_vbo == 0) {
            glGenBuffers(1, &_vbo);
            LDEBUG("Generating Vertex Buffer Object id '" << _vbo << "'");
        }
        glBindVertexArray(_vao);
        glBindBuffer(GL_ARRAY_BUFFER, _vbo);
        glBufferData(GL_ARRAY_BUFFER,
            size*sizeof(GLfloat),
            &_slicedData[0],
            GL_STATIC_DRAW);

        GLint positionAttrib = _program->attributeLocation("in_position");
        GLint brightnessDataAttrib = _program->attributeLocation("in_brightness");

        const size_t nStars = _fullData.size() / _nValuesPerStar;
        const size_t nValues = _slicedData.size() / nStars;

        GLsizei stride = static_cast<GLsizei>(sizeof(GLfloat) * nValues);

        glEnableVertexAttribArray(positionAttrib);
        glEnableVertexAttribArray(brightnessDataAttrib);
        const int colorOption = _colorOption;
        switch (colorOption) {
        case ColorOption::Color:
            glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride,
                reinterpret_cast<void*>(offsetof(ColorVBOLayout, position)));
            glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride,
                reinterpret_cast<void*>(offsetof(ColorVBOLayout, bvColor)));
            
            break;
        case ColorOption::Velocity:
            {
                glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride,
                    reinterpret_cast<void*>(offsetof(VelocityVBOLayout, position)));
                glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride,
                    reinterpret_cast<void*>(offsetof(VelocityVBOLayout, bvColor)));

                GLint velocityAttrib = _program->attributeLocation("in_velocity");
                glEnableVertexAttribArray(velocityAttrib);
                glVertexAttribPointer(velocityAttrib, 3, GL_FLOAT, GL_TRUE, stride,
                    reinterpret_cast<void*>(offsetof(VelocityVBOLayout, vx)));

                break;
            }
        case ColorOption::Speed:
            {
                glVertexAttribPointer(positionAttrib, 4, GL_FLOAT, GL_FALSE, stride,
                    reinterpret_cast<void*>(offsetof(SpeedVBOLayout, position)));
                glVertexAttribPointer(brightnessDataAttrib, 3, GL_FLOAT, GL_FALSE, stride,
                    reinterpret_cast<void*>(offsetof(SpeedVBOLayout, bvColor)));

                GLint speedAttrib = _program->attributeLocation("in_speed");
                glEnableVertexAttribArray(speedAttrib);
                glVertexAttribPointer(speedAttrib, 1, GL_FLOAT, GL_TRUE, stride,
                    reinterpret_cast<void*>(offsetof(SpeedVBOLayout, speed)));

            }
        }

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindVertexArray(0);

        _dataIsDirty = false;
    }    

    if (_pointSpreadFunctionTextureIsDirty) {
        LDEBUG("Reloading Point Spread Function texture");
        _pointSpreadFunctionTexture = nullptr;
        if (_pointSpreadFunctionTexturePath.value() != "") {
            _pointSpreadFunctionTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_pointSpreadFunctionTexturePath)));
            
            if (_pointSpreadFunctionTexture) {
                LDEBUG("Loaded texture from '" << absPath(_pointSpreadFunctionTexturePath) << "'");
                _pointSpreadFunctionTexture->uploadTexture();
            }
            _pointSpreadFunctionTexture->setFilter(ghoul::opengl::Texture::FilterMode::AnisotropicMipMap);

            delete _psfTextureFile;
            _psfTextureFile = new ghoul::filesystem::File(_pointSpreadFunctionTexturePath);
            _psfTextureFile->setCallback([&](const ghoul::filesystem::File&) { _pointSpreadFunctionTextureIsDirty = true; });
        }
        _pointSpreadFunctionTextureIsDirty = false;
    }

    if (_colorTextureIsDirty) {
        LDEBUG("Reloading Color Texture");
        _colorTexture = nullptr;
        if (_colorTexturePath.value() != "") {
            _colorTexture = std::move(ghoul::io::TextureReader::ref().loadTexture(absPath(_colorTexturePath)));
            if (_colorTexture) {
                LDEBUG("Loaded texture from '" << absPath(_colorTexturePath) << "'");
                _colorTexture->uploadTexture();
            }

            delete _colorTextureFile;
            _colorTextureFile = new ghoul::filesystem::File(_colorTexturePath);
            _colorTextureFile->setCallback([&](const ghoul::filesystem::File&) { _colorTextureIsDirty = true; });
        }
        _colorTextureIsDirty = false;
    }
}
Beispiel #19
0
/// 小数据量的收发,集中在一个线程里,不影响效率
void CTcpSock::P_ThreadWork()
{
	byte  bytLvl = 0;
	char  szBuf[100] = {0};
	DWORD dwLen = 0;
	DWORD dwPushTm;
	DWORD dwBufSize = (DWORD)sizeof(szBuf);
	bool  bMustConn = false;
	int   iFlag;
	int   iret;
	int   iConnFailTimes = 0;	// 连续连接失败次数
	static DWORD sta_dwLastConTm = GetTickCount();

	fd_set rset, wset, eset;
	struct timeval tval;

	int  iRecvLen;
	char szRecvbuf[ TCP_RECVSIZE+1 ];

	char  szSendBuf[ TCP_SENDSIZE ] = {0};
	DWORD dwSendLen;
	//DWORD dwPushTm = 0;
	//BYTE  bytLvl;

	szRecvbuf[0] = 0x00;		// 0x00 表示中心TCP协议帧

	DWORD dwSleep = 500; // ms
	while(!g_bProgExit)
	{
		usleep(dwSleep * 1000);

		dwSleep = 500;
		if( 0 == m_objSockStaMng.PopData(bytLvl, dwBufSize, dwLen, szBuf, dwPushTm) )
		{
			switch(szBuf[0])
			{
				case 0x01:
					{
						iConnFailTimes = 0;
						m_bytSockSta = DisConn;
						bMustConn = true;
					}
					break;
	
				default:
					break;
			}
		}

		switch( m_bytSockSta )
		{
			case Idle:
				{
					// 若处于空闲状态,则每隔60秒连接一次中心
					if( GetTickCount() - sta_dwLastConTm >= 60000 )
					{
						m_bytSockSta = Conn;
						break;
					}
	
					if( bMustConn == true )
					{
						m_bytSockSta = Conn;
						bMustConn = false;
						break;
					}
				}
				break;
	
			case Conn:
				{
					sta_dwLastConTm = GetTickCount();

					// 若没有可用的临时IP,说明要连接到登陆服务器,此时则使用配置区中的IP
					if( m_dwSymb == DEV_DVR )
					{
						for(int i=0; i<m_iIPCnt; i++)
						{
							if( m_bIPEnabled[i] )
							{
								m_bIPEnabled[i] = false;	// 使用一次后即置为假
								m_conn.sin_family = AF_INET;
								m_conn.sin_port = m_usTempTcpPort[i];
								m_conn.sin_addr.s_addr = m_ulTempIP[i];
								
								// 且DVR UDP的地址和端口也要相应更改
								g_objDvrUdp.m_ulIp = m_ulTempIP[i];
								g_objDvrUdp.m_usPort = m_usTempUdpPort[i];
								tag1QIpCfg	obj1QIpCfg;
								GetImpCfg( &obj1QIpCfg, sizeof(obj1QIpCfg), offsetof(tagImportantCfg, m_uni1QComuCfg.m_ary1QIpCfg[0]), sizeof(obj1QIpCfg) );
								obj1QIpCfg.m_ulVUdpIP = g_objDvrUdp.m_ulIp;
								obj1QIpCfg.m_usVUdpPort = g_objDvrUdp.m_usPort;
								SetImpCfg( &obj1QIpCfg, offsetof(tagImportantCfg, m_uni1QComuCfg.m_ary1QIpCfg[0]), sizeof(obj1QIpCfg) );

								goto TCP_CONNECT;
							}
						}
					}
					
					// 读取IP、端口配置
					tag1QIpCfg obj1QIpCfg[2];
					tag1PComuCfg obj1PComuCfg;
					tag1LComuCfg obj1LComuCfg;
					if(	GetImpCfg( (void*)&obj1QIpCfg, sizeof(obj1QIpCfg), offsetof(tagImportantCfg, m_uni1QComuCfg.m_ary1QIpCfg), sizeof(obj1QIpCfg) )
						|| GetImpCfg( (void*)&obj1PComuCfg, sizeof(obj1PComuCfg), offsetof(tagImportantCfg, m_uni1PComuCfg.m_obj1PComuCfg), sizeof(obj1PComuCfg) )
						|| GetImpCfg( (void*)&obj1LComuCfg, sizeof(obj1LComuCfg), offsetof(tagImportantCfg, m_uni1LComuCfg.m_obj1LComuCfg), sizeof(obj1LComuCfg) )
						)
					{
						PRTMSG(MSG_ERR, "Read IP Cfg Fail\n" );
						m_bytSockSta = Idle;
						break;
					}
					
					m_conn.sin_family = AF_INET;
					switch( m_dwSymb )
					{
					case DEV_QIAN: // king中心
						{
							m_conn.sin_port = obj1QIpCfg[0].m_usQianTcpPort;
	 						m_conn.sin_addr.s_addr = obj1QIpCfg[0].m_ulQianTcpIP;
						}
						break;

					case DEV_DVR:	// 独立视频服务器
						{
							m_conn.sin_port = obj1QIpCfg[1].m_usQianTcpPort;
	 						m_conn.sin_addr.s_addr = obj1QIpCfg[1].m_ulQianTcpIP;
						}
						break;

					case DEV_UPDATE: // 管理平台 (应该增加一个新的标记,待)
						{
							m_conn.sin_port = obj1LComuCfg.m_usLiuPort2;
	 						m_conn.sin_addr.s_addr = obj1LComuCfg.m_ulLiuIP2;
						}
						break;

					default:
						break;
					}

TCP_CONNECT:					
					// 若配置为空,则返回
					if(	0 == m_conn.sin_addr.s_addr	|| 0 == m_conn.sin_port || 0 == strcmp(obj1PComuCfg.m_szTel, ""))
					{
						PRTMSG(MSG_ERR, "IP/Port/Tel Cfg Is Uncompleted!\n");
						G_RecordDebugInfo("IP/Port/Tel Cfg Is Uncompleted!\n");
						m_bytSockSta = Idle;
						break;
					}
	
					// 确认关闭已有连接
					if( -1 != m_sockTcp )
					{
						shutdown(m_sockTcp, 2);
						close(m_sockTcp);
						m_sockTcp = -1;
					}
	
					m_sockTcp = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
					if( -1 == m_sockTcp )
					{
						PRTMSG(MSG_ERR, "Socket err\n" );
						break;
					}
	
					bzero(&(m_conn.sin_zero),8);
	
					// 获取当前socket的属性, 并设置noblocking属性
					iFlag = fcntl(m_sockTcp, F_GETFL, 0);
					fcntl(m_sockTcp, F_SETFL, iFlag | O_NONBLOCK);

					LINGER ling;
					ling.l_onoff = 1; // closesocket时强制关闭并立即释放套接字资源
					ling.l_linger = 0;
					::setsockopt( m_sockTcp, SOL_SOCKET, SO_LINGER, (char*)&ling, sizeof(ling) );

					BOOL blVal = TRUE; // 禁止Nagle算法
					setsockopt( m_sockTcp, IPPROTO_TCP, TCP_NODELAY, (char*)&blVal, sizeof(blVal) );
	
					if( DEV_QIAN == m_dwSymb )
					{
						PRTMSG(MSG_DBG, "Qian Tcp connect: Tel: %s, IP: %s, Port: %d\n", obj1PComuCfg.m_szTel, inet_ntoa(m_conn.sin_addr), htons(m_conn.sin_port));
						RenewMemInfo(0x02, 0x02, 0x01, 0x03);

						G_RecordDebugInfo("Qian Tcp connect: Tel: %s, IP: %s, Port: %d", obj1PComuCfg.m_szTel, inet_ntoa(m_conn.sin_addr), htons(m_conn.sin_port));
					}
					if(DEV_DVR == m_dwSymb)
					{
						PRTMSG(MSG_DBG, "Dvr Tcp connect: Tel: %s, IP: %s, Port: %d\n", obj1PComuCfg.m_szTel, inet_ntoa(m_conn.sin_addr), htons(m_conn.sin_port));
					
						G_RecordDebugInfo("Dvr Tcp connect: Tel: %s, IP: %s, Port: %d", obj1PComuCfg.m_szTel, inet_ntoa(m_conn.sin_addr), htons(m_conn.sin_port));
					}
					
					if( (iret = connect( m_sockTcp, (struct sockaddr *)&m_conn, sizeof(struct sockaddr))) < 0 )
					{
						if(errno != EINPROGRESS)
						{
							PRTMSG(MSG_DBG, "connect failed, errno=%d\n", errno);	
							G_RecordDebugInfo("connect failed, errno=%d", errno);	
							perror("");
	
							iConnFailTimes++;
							if( !_JudgeConFailMaxTime(iConnFailTimes) )
							{
								sta_dwLastConTm = GetTickCount() - 57000; // 这样,3秒后可以尝试重新connect,提高效率
							}

							m_bytSockSta = Idle;
							break;
						}
					}
					m_bytSockSta = WaitConn;
				}
				break;
	
			case WaitConn:
				{
					FD_ZERO(&rset);
					FD_ZERO(&wset);
					FD_ZERO(&eset);
					FD_SET(m_sockTcp, &rset);
					FD_SET(m_sockTcp, &wset);
					FD_SET(m_sockTcp, &eset);
	
					tval.tv_sec = 30;
					tval.tv_usec = 0;
	
					iret = select(m_sockTcp+1, &rset, &wset, &eset, &tval);
					if( 0 == iret )
					{
						if( m_dwSymb == DEV_QIAN )
						{
							PRTMSG(MSG_NOR, "Qian Tcp Socket connect time out!\n");
							G_RecordDebugInfo("Tcp Socket connect time out!");
						}

						if( m_dwSymb == DEV_DVR )
						{
							PRTMSG(MSG_NOR, "Dvr Tcp Socket connect time out!\n");
							G_RecordDebugInfo("Dvr Tcp Socket connect time out!");
						}

						goto _CUR_CONNECT_FAIL;
					}
					else if(iret < 0)
					{
						PRTMSG(MSG_NOR, "Tcp Socket select err!\n");
						goto _CUR_CONNECT_FAIL;
					}
					else
					{
						if( FD_ISSET(m_sockTcp, &eset) )
						{
							PRTMSG(MSG_NOR, "Tcp Socket connect except!\n");
							goto _CUR_CONNECT_FAIL;
						}
						else if(FD_ISSET(m_sockTcp, &rset) || FD_ISSET(m_sockTcp, &wset)) 
						{
							m_bConnect = true;
							iConnFailTimes = 0;							

							if( m_dwSymb == DEV_QIAN )
							{
								PRTMSG(MSG_NOR, "Qian Tcp Socket Connect succ!\n");
								G_RecordDebugInfo("Qian Tcp Socket Connect succ!");
							}
							if( m_dwSymb == DEV_DVR )
							{
								PRTMSG(MSG_NOR, "Dvr Socket Connect succ!\n");
								G_RecordDebugInfo("Dvr Tcp Socket Connect succ!");
							}

							if(m_dwSymb == DEV_DVR)
							{
								for(int i=0; i<MAX_TEMP_IP_CNT; i++)
									m_bIPEnabled[i] = false;
							}

							// 通知连接成功
							char szbuf[2];
							szbuf[0] = 0x01;	// 0x01 表示非中心协议帧
							szbuf[1] = 0x01;	// 0x01 表示TCP套接字连接成功
							DataPush((void*)szbuf, 2, DEV_SOCK, m_dwSymb, LV3);
							
							RenewMemInfo(0x02, 0x01, 0x01, 0x01);
							
							m_bytSockSta = Working;
							break;	
						}
						else 
						{
							PRTMSG(MSG_ERR, "Tcp Socket select err: sockfd not set\n" );
							goto _CUR_CONNECT_FAIL;
						}
					}
					break;

_CUR_CONNECT_FAIL:
					close(m_sockTcp);
					m_sockTcp = -1;
					
					iConnFailTimes++;
					if( !_JudgeConFailMaxTime(iConnFailTimes) )
					{
						sta_dwLastConTm = GetTickCount() - 57000; // 这样,3秒后可以尝试重新connect,提高效率
					}
					
					m_bytSockSta = DisConn;
				}
				break;
	
			case Working:
				{
					/// 先写

					FD_ZERO(&wset);
					FD_ZERO(&eset);
					FD_SET(m_sockTcp, &wset);
					FD_SET(m_sockTcp, &eset);
	
					tval.tv_sec = 0;
					tval.tv_usec = 0;

					iret = select(m_sockTcp+1, NULL, &wset, &eset, &tval);
					if( iret > 0 )
					{
						if( FD_ISSET(m_sockTcp, &eset) )
						{
							PRTMSG(MSG_NOR, "Tcp Socket select write except!\n");
							G_RecordDebugInfo("Tcp Socket select write except!");
							goto _CUR_SOCK_EXCEPT;
						}
						else if( FD_ISSET(m_sockTcp, &wset) )
						{
							if( 0 == m_objSendMng.PopData( bytLvl, sizeof(szSendBuf), dwSendLen, szSendBuf, dwPushTm) )
							{
								if( dwSendLen > 0 && dwSendLen <= sizeof(szSendBuf) && -1 != m_sockTcp )
								{
									iret = send( m_sockTcp, szSendBuf, dwSendLen, 0 );
									
									if( iret > 0 )
									{
										if( DEV_QIAN == m_dwSymb )
										{
											PRTMSG(MSG_DBG, "Qian TcpSock send:");
										}
										if( DEV_DVR == m_dwSymb )
										{
											PRTMSG(MSG_DBG, "Dvr TcpSock send:");
										}
										PrintString(szSendBuf,iret);
									}
									else if( iret < 0 )
									{
										goto _CUR_SOCK_EXCEPT;
									}
								}

								dwSleep = 50;
							}
						}
						else
						{
							goto _CUR_SOCK_EXCEPT;
						}
					}
					else if( 0 == iret )
					{
						PRTMSG(MSG_NOR, "Tcp Socket select write block!\n");
						G_RecordDebugInfo("Tcp Socket select write block!");
					}
					else if(iret < 0)
					{
						PRTMSG(MSG_NOR, "Tcp Socket select write err!\n");
						G_RecordDebugInfo("Tcp Socket select write err!");
						goto _CUR_SOCK_EXCEPT;
					}


					/// 后读

					FD_ZERO(&rset);
					FD_ZERO(&eset);
					FD_SET(m_sockTcp, &rset);
					FD_SET(m_sockTcp, &eset);
					
					tval.tv_sec = 0;
					tval.tv_usec = 0;

					iret = select(m_sockTcp+1, &rset, NULL, &eset, &tval);
					if( iret > 0 )
					{
						if( FD_ISSET(m_sockTcp, &eset) )
						{
							PRTMSG(MSG_NOR, "Tcp Socket select read except!\n");
							G_RecordDebugInfo("Tcp Socket select read except!");
							goto _CUR_SOCK_EXCEPT;
						}
						else if( FD_ISSET(m_sockTcp, &rset) )
						{
							iRecvLen = recv( m_sockTcp, szRecvbuf+1, sizeof(szRecvbuf)-1, 0 );
						
							if( iRecvLen > 0 )
							{
								if( DEV_QIAN == m_dwSymb )
								{
									PRTMSG(MSG_NOR, "Qian Rcv Tcp Msg: ");
								}
								if( DEV_DVR == m_dwSymb )
								{
									PRTMSG(MSG_NOR, "Dvr Rcv Tcp Msg: ");
								}
								PrintString(szRecvbuf+1, iRecvLen);
								
								DataPush(szRecvbuf, iRecvLen+1, DEV_SOCK, m_dwSymb, LV2);

								dwSleep = 50;
							}
							else
							{
								if(m_dwSymb == DEV_DVR)
								{
									PRTMSG(MSG_ERR, "Dvr Tcp socket recv err!\n");								
									G_RecordDebugInfo("Dvr Tcp socket recv err, errno=%d", errno);
								}
								if(m_dwSymb == DEV_QIAN)
								{
									PRTMSG(MSG_ERR, "Qian Tcp socket recv err!\n");								
									G_RecordDebugInfo("Qian Tcp socket recv err, errno=%d", errno);
								}
								
								perror("");
								goto _CUR_SOCK_EXCEPT;
							}
						}
					}
					else if( iret < 0 )
					{
						PRTMSG(MSG_ERR, "Tcp socket select err!\n");
						G_RecordDebugInfo("Tcp socket select err!");
						perror("");
						goto _CUR_SOCK_EXCEPT;
					}

					break;

_CUR_SOCK_EXCEPT:
					sta_dwLastConTm = GetTickCount() - 57000; // 这样,3秒后可以尝试重新connect,提高效率
					m_bytSockSta = DisConn;
				}
				break;
	
			case DisConn:
				{
					if( m_dwSymb == DEV_QIAN )
						G_RecordDebugInfo("Qian Tcp socket Disconn!");
					if( m_dwSymb == DEV_DVR )
						G_RecordDebugInfo("Dvr Tcp socket Disconn!");

					if(m_sockTcp > 0)
					{
						shutdown(m_sockTcp, 2);
						close(m_sockTcp);
						m_sockTcp = -1;
					}
	
					// Tcp断开连接,则把Udp也断开
					if( DEV_QIAN == m_dwSymb )
					{
						g_objQianUdp.ReqDestroySock();
					}
					if( DEV_DVR == m_dwSymb )
					{
						g_objDvrUdp.ReqDestroySock();
					}

					// 通知断开连接
					char szbuf[2];
					szbuf[0] = 0x01;	// 0x01 表示非中心协议帧
					szbuf[1] = 0x02;	// 0x02 表示通知网络断开连接
					DataPush((void*)szbuf, 2, DEV_SOCK, m_dwSymb, LV3);
					
					RenewMemInfo(0x02, 0x01, 0x01, 0x00);
	
					m_bytSockSta = Idle;
				}
				break;
	
			default:
				{
					m_bytSockSta = Idle;
				}
				break;
		}
	}
}
Beispiel #20
0
VOID
__cdecl
main(
    _In_ int argc,
    _In_z_ char *argv[]
    )

{
    BOOL status = 0;
    DWORD accessMode = 0, shareMode = 0;
    HANDLE fileHandle = NULL;
    ULONG alignmentMask = 0; // default == no alignment requirement
    UCHAR srbType = 0; // default == SRB_TYPE_SCSI_REQUEST_BLOCK
    PUCHAR dataBuffer = NULL;
    PUCHAR pUnAlignedBuffer = NULL;
    SCSI_PASS_THROUGH_WITH_BUFFERS sptwb;
    SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER sptdwb;
    SCSI_PASS_THROUGH_WITH_BUFFERS_EX sptwb_ex;
    SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX sptdwb_ex;
    CHAR string[NAME_COUNT];

    ULONG length = 0,
          errorCode = 0,
          returned = 0,
          sectorSize = 512;

    if ((argc < 2) || (argc > 3)) {
       printf("Usage:  %s <port-name> [-mode]\n", argv[0] );
       printf("Examples:\n");
       printf("    spti g:       (open the disk class driver in SHARED READ/WRITE mode)\n");
       printf("    spti Scsi2:   (open the miniport driver for the 3rd host adapter)\n");
       printf("    spti Tape0 w  (open the tape class driver in SHARED WRITE mode)\n");
       printf("    spti i: c     (open the CD-ROM class driver in SHARED READ mode)\n");
       return;
    }

    StringCbPrintf(string, sizeof(string), "\\\\.\\%s", argv[1]);

    shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;  // default
    accessMode = GENERIC_WRITE | GENERIC_READ;       // default

    if (argc == 3) {

        switch(tolower(argv[2][0])) {
            case 'r':
                shareMode = FILE_SHARE_READ;
                break;

            case 'w':
                shareMode = FILE_SHARE_WRITE;
                break;

            case 'c':
                shareMode = FILE_SHARE_READ;
                sectorSize = 2048;
                break;

            default:
                printf("%s is an invalid mode.\n", argv[2]);
                puts("\tr = read");
                puts("\tw = write");
                puts("\tc = read CD (2048 byte sector mode)");
                return;
        }
    }

    fileHandle = CreateFile(string,
       accessMode,
       shareMode,
       NULL,
       OPEN_EXISTING,
       0,
       NULL);

    if (fileHandle == INVALID_HANDLE_VALUE) {
        errorCode = GetLastError();
        printf("Error opening %s. Error: %d\n",
               string, errorCode);
        PrintError(errorCode);
        return;
    }

    //
    // Get the alignment requirements
    //

    status = QueryPropertyForDevice(fileHandle, &alignmentMask, &srbType);
    if (!status ) {
        errorCode = GetLastError();
        printf("Error getting device and/or adapter properties; "
               "error was %d\n", errorCode);
        PrintError(errorCode);
        CloseHandle(fileHandle);
        return;
    }

    printf("\n"
           "            *****     Detected Alignment Mask    *****\n"
           "            *****             was %08x       *****\n\n\n",
           alignmentMask);

    //
    // Send SCSI Pass Through
    //

    puts("            ***** MODE SENSE -- return all pages *****");
    puts("            *****      with SenseInfo buffer     *****\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 192;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucSenseBuf);
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf);
        sptwb_ex.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb_ex.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb_ex.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf) +
           sptwb_ex.spt.DataInTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 192;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf);
        sptwb.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucSenseBuf);
        sptwb.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf) +
           sptwb.spt.DataTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    printf("            ***** MODE SENSE -- return all pages *****\n");
    printf("            *****    without SenseInfo buffer    *****\n\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = 0;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 192;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset = 0;
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf);
        sptwb_ex.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb_ex.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb_ex.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf) +
           sptwb_ex.spt.DataInTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = 0;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 192;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf);
        sptwb.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf) +
           sptwb.spt.DataTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    printf("            *****      TEST UNIT READY      *****\n");
    printf("            *****   DataInBufferLength = 0  *****\n\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 0;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucSenseBuf);
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset = 0;
        sptwb_ex.spt.Cdb[0] = SCSIOP_TEST_UNIT_READY;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf);

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 0;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset = 0;
        sptwb.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucSenseBuf);
        sptwb.spt.Cdb[0] = SCSIOP_TEST_UNIT_READY;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf);

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    //
    //  Do a mode sense with a bad data buffer offset.  This will fail.
    //
    printf("            *****      MODE SENSE -- return all pages      *****\n");
    printf("            *****   bad DataBufferOffset -- should fail    *****\n\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 192;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucSenseBuf);
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset = 0;
        sptwb_ex.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb_ex.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb_ex.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf) +
           sptwb_ex.spt.DataInTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = 0;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 192;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset = 0;
        sptwb.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucSenseBuf);
        sptwb.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf) +
           sptwb.spt.DataTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    //
    // Get caching mode sense page.
    //
    printf("            *****               MODE SENSE                  *****\n");
    printf("            *****     return caching mode sense page        *****\n\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 192;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucSenseBuf);
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf);
        sptwb_ex.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb_ex.spt.Cdb[1] = 0x08; // target shall not return any block descriptors
        sptwb_ex.spt.Cdb[2] = MODE_PAGE_CACHING;
        sptwb_ex.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf) +
           sptwb_ex.spt.DataInTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 192;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf);
        sptwb.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucSenseBuf);
        sptwb.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb.spt.Cdb[1] = 0x08; // target shall not return any block descriptors
        sptwb.spt.Cdb[2] = MODE_PAGE_CACHING;
        sptwb.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf) +
           sptwb.spt.DataTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    printf("            *****       WRITE DATA BUFFER operation         *****\n");
    
    dataBuffer = AllocateAlignedBuffer(sectorSize,alignmentMask, &pUnAlignedBuffer);
    FillMemory(dataBuffer,sectorSize/2,'N');
    FillMemory(dataBuffer + sectorSize/2,sectorSize/2,'T');

    if(srbType == 1)
    {
        ZeroMemory(&sptdwb_ex,sizeof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX));
        sptdwb_ex.sptd.Version = 0;
        sptdwb_ex.sptd.Length = sizeof(SCSI_PASS_THROUGH_DIRECT_EX);
        sptdwb_ex.sptd.ScsiStatus = 0;
        sptdwb_ex.sptd.CdbLength = CDB10GENERIC_LENGTH;
        sptdwb_ex.sptd.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptdwb_ex.sptd.SenseInfoLength = SPT_SENSE_LENGTH;
        sptdwb_ex.sptd.DataOutTransferLength = sectorSize;
        sptdwb_ex.sptd.DataInTransferLength = 0;
        sptdwb_ex.sptd.DataDirection = SCSI_IOCTL_DATA_OUT;
        sptdwb_ex.sptd.TimeOutValue = 2;
        sptdwb_ex.sptd.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX,StorAddress);
        sptdwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptdwb_ex.StorAddress.Port = 0;
        sptdwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptdwb_ex.StorAddress.Path = 0;
        sptdwb_ex.StorAddress.Target = 1;
        sptdwb_ex.StorAddress.Lun = 0;
        sptdwb_ex.sptd.SenseInfoOffset = 
           offsetof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX,ucSenseBuf);
        sptdwb_ex.sptd.DataOutBuffer = dataBuffer;
        sptdwb_ex.sptd.DataInBuffer = NULL;
        sptdwb_ex.sptd.Cdb[0] = SCSIOP_WRITE_DATA_BUFF;
        sptdwb_ex.sptd.Cdb[1] = 2;                         // Data mode
        sptdwb_ex.sptd.Cdb[7] = (UCHAR)(sectorSize >> 8);  // Parameter List length
        sptdwb_ex.sptd.Cdb[8] = 0;
        length = sizeof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX);

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_DIRECT_EX,
                                 &sptdwb_ex,
                                 length,
                                 &sptdwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,
           (PSCSI_PASS_THROUGH_WITH_BUFFERS_EX)&sptdwb_ex,length);

        if ((sptdwb_ex.sptd.ScsiStatus == 0) && (status != 0)) {
           PrintDataBuffer(dataBuffer,sptdwb_ex.sptd.DataOutTransferLength);
        }
    }
Beispiel #21
0
main()
{
  tree_sTable* tp;
  sNode* np;
  int key;
  int i;
  char s[256];
  char* cp;
  char c;

  tp = tree_CreateTable(sizeof(int), offsetof(sNode, key), sizeof(sNode), 100,
      tree_eComp_int32, NULL);

  for (i = 0; i < 1000; i += 10) {
    tree_Insert(tp, &i);
  }

  for (;;) {
    printf("Command: ");
    cp = gets(s);
    c = s[0];
    if (cp == NULL || c == '\0') {
      printf("\nGoodbye\n");
      return;
    }
    switch (c) {
    case 'i':
    case 'I':
      printf("Insert, Key: ");
      gets(s);
      key = atoi(s);
      if (tree_Find(tp, &key) == NULL) {
        tree_Insert(tp, &key);
      } else
        printf("\nKey allready exists!\n");
      break;
    case 'd':
    case 'D':
      printf("Delete, Key: ");
      gets(s);
      key = atoi(s);
      if ((np = tree_Find(tp, &key)) != NULL) {
        tree_Remove(tp, &key);
      } else
        printf("\nKey does not exist!\n");
      break;
    case 'f':
    case 'F':
      printf("Find, Key: ");
      gets(s);
      key = atoi(s);
      if ((np = tree_Find(tp, &key)) == NULL) {
        printf("\nKey does not exist!\n");
      } else
        printf("\nKey exists! %d\n", np->key);
      break;
    case 's':
    case 'S':
      printf("Find successor, Key: ");
      gets(s);
      key = atoi(s);
      if ((np = tree_FindSuccessor(tp, &key)) == NULL) {
        printf("\nKey does not exist!\n");
      } else
        printf("\nKey exists! %d\n", np->key);
      break;
    case 'p':
    case 'P':
      printf("Find predecessor, Key: ");
      gets(s);
      key = atoi(s);
      if ((np = tree_FindPredecessor(tp, &key)) == NULL) {
        printf("\nKey does not exist!\n");
      } else
        printf("\nKey exists! %d\n", np->key);
      break;
    case 'q':
    case 'Q':
      printf("\nGoodbye\n");
      return;
      break;
    default:
      printf("Illegal command!\n");

      break;
    }
  }
}
Beispiel #22
0
GLsizei NinePatchFactory::alloc_patch(const glm::uvec2& size, const glm::uvec4& borders, const glm::uvec2& tex_size)
{
	GLsizei patch = -1;

	for (free_list_t::iterator i=m_listFree.begin(); i; ++i)
	{
		if (i->second == 1)
		{
			patch = i->first;
			m_listFree.erase(i);
			break;
		}
		else if (i->second > 1)
		{
			patch = i->first;
			i->first += 1;
			i->second -= 1;
			break;
		}
	}

	if (patch == -1)
	{
		if (!m_ptrProgram && !create_program())
			return patch;

		if (!m_ptrVAO)
		{
			m_ptrVAO = OOBase::allocate_shared<OOGL::VertexArrayObject,OOBase::ThreadLocalAllocator>();
			if (!m_ptrVAO)
				LOG_ERROR_RETURN(("Failed to allocate VAO: %s",OOBase::system_error_text(ERROR_OUTOFMEMORY)),patch);
		}
		m_ptrVAO->bind();

		GLsizei new_size = 16;
		while (new_size < m_allocated + 1)
			new_size *= 2;

		OOBase::SharedPtr<OOGL::BufferObject> ptrNewVertices = OOBase::allocate_shared<OOGL::BufferObject,OOBase::ThreadLocalAllocator>(GL_ARRAY_BUFFER,GL_DYNAMIC_DRAW,new_size * vertices_per_patch * sizeof(vertex_data));
		OOBase::SharedPtr<OOGL::BufferObject> ptrNewElements = OOBase::allocate_shared<OOGL::BufferObject,OOBase::ThreadLocalAllocator>(GL_ELEMENT_ARRAY_BUFFER,GL_DYNAMIC_DRAW,new_size * elements_per_patch * sizeof(GLuint));
		if (!ptrNewVertices || !ptrNewElements)
			LOG_ERROR_RETURN(("Failed to allocate VBO: %s",OOBase::system_error_text(ERROR_OUTOFMEMORY)),patch);

		if (m_ptrVertices)
			ptrNewVertices->copy(0,m_ptrVertices,0,m_allocated * vertices_per_patch * sizeof(vertex_data));

		if (m_ptrElements)
			ptrNewElements->copy(0,m_ptrElements,0,m_allocated * elements_per_patch * sizeof(GLuint));

		m_ptrVertices.swap(ptrNewVertices);
		m_ptrElements.swap(ptrNewElements);

		free_list_t::iterator last = m_listFree.back();
		if (last)
			last->second += new_size - m_allocated;
		else
			last = m_listFree.insert(m_allocated,new_size - m_allocated);
		m_allocated = new_size;

		patch = last->first;
		last->first += 1;
		last->second -= 1;

		GLint a = m_ptrProgram->attribute_location("in_Position");
		m_ptrVAO->attribute(a,m_ptrVertices,2,GL_FLOAT,false,sizeof(vertex_data),offsetof(vertex_data,x));
		m_ptrVAO->enable_attribute(a);

		a = m_ptrProgram->attribute_location("in_TexCoord");
		if (a != -1)
		{
			m_ptrVAO->attribute(a,m_ptrVertices,2,GL_UNSIGNED_SHORT,true,sizeof(vertex_data),offsetof(vertex_data,u));
			m_ptrVAO->enable_attribute(a);
		}

		m_ptrVAO->element_array(m_ptrElements);

		m_ptrVAO->unbind();
	}

	OOBase::SharedPtr<GLuint> ei = m_ptrElements->auto_map<GLuint>(GL_MAP_WRITE_BIT,patch * elements_per_patch * sizeof(GLuint),elements_per_patch * sizeof(GLuint));
	GLuint* e = ei.get();
	GLuint idx = patch * vertices_per_patch;
	for (size_t i=0;i<12;++i)
	{
		e[i*2] = static_cast<GLuint>(idx + i);
		e[i*2 + 1] = static_cast<GLuint>(idx + i + 4);
	}

	layout_patch(patch,size,borders,tex_size);

	return patch;
}
    const void *two);
static ngx_int_t ngx_http_autoindex_error(ngx_http_request_t *r,
    ngx_dir_t *dir, ngx_str_t *name);
static ngx_int_t ngx_http_autoindex_init(ngx_conf_t *cf);
static void *ngx_http_autoindex_create_loc_conf(ngx_conf_t *cf);
static char *ngx_http_autoindex_merge_loc_conf(ngx_conf_t *cf,
    void *parent, void *child);


static ngx_command_t  ngx_http_autoindex_commands[] = {

    { ngx_string("autoindex"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
      ngx_conf_set_flag_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_autoindex_loc_conf_t, enable),
      NULL },

    { ngx_string("autoindex_localtime"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
      ngx_conf_set_flag_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_autoindex_loc_conf_t, localtime),
      NULL },

    { ngx_string("autoindex_exact_size"),
      NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG,
      ngx_conf_set_flag_slot,
      NGX_HTTP_LOC_CONF_OFFSET,
      offsetof(ngx_http_autoindex_loc_conf_t, exact_size),
      NULL },
/*
 * Replace the inode number of an entry in a shortform directory.
 */
int						/* error */
xfs_dir2_sf_replace(
    xfs_da_args_t		*args)		/* operation arguments */
{
    xfs_inode_t		*dp;		/* incore directory inode */
    int			i;		/* entry index */
#if XFS_BIG_INUMS || defined(DEBUG)
    xfs_ino_t		ino=0;		/* entry old inode number */
#endif
#if XFS_BIG_INUMS
    int			i8elevated;	/* sf_toino8 set i8count=1 */
#endif
    xfs_dir2_sf_entry_t	*sfep;		/* shortform directory entry */
    xfs_dir2_sf_t		*sfp;		/* shortform structure */

    xfs_dir2_trace_args("sf_replace", args);
    dp = args->dp;

    ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
    /*
     * Bail out if the shortform directory is way too small.
     */
    if (dp->i_d.di_size < offsetof(xfs_dir2_sf_hdr_t, parent)) {
        ASSERT(XFS_FORCED_SHUTDOWN(dp->i_mount));
        return XFS_ERROR(EIO);
    }
    ASSERT(dp->i_df.if_bytes == dp->i_d.di_size);
    ASSERT(dp->i_df.if_u1.if_data != NULL);
    sfp = (xfs_dir2_sf_t *)dp->i_df.if_u1.if_data;
    ASSERT(dp->i_d.di_size >= XFS_DIR2_SF_HDR_SIZE(sfp->hdr.i8count));
#if XFS_BIG_INUMS
    /*
     * New inode number is large, and need to convert to 8-byte inodes.
     */
    if (args->inumber > XFS_DIR2_MAX_SHORT_INUM && sfp->hdr.i8count == 0) {
        int	error;			/* error return value */
        int	newsize;		/* new inode size */

        newsize =
            dp->i_df.if_bytes +
            (sfp->hdr.count + 1) *
            ((uint)sizeof(xfs_dir2_ino8_t) -
             (uint)sizeof(xfs_dir2_ino4_t));
        /*
         * Won't fit as shortform, convert to block then do replace.
         */
        if (newsize > XFS_IFORK_DSIZE(dp)) {
            error = xfs_dir2_sf_to_block(args);
            if (error) {
                return error;
            }
            return xfs_dir2_block_replace(args);
        }
        /*
         * Still fits, convert to 8-byte now.
         */
        xfs_dir2_sf_toino8(args);
        i8elevated = 1;
        sfp = (xfs_dir2_sf_t *)dp->i_df.if_u1.if_data;
    } else
        i8elevated = 0;
#endif
    ASSERT(args->namelen != 1 || args->name[0] != '.');
    /*
     * Replace ..'s entry.
     */
    if (args->namelen == 2 &&
            args->name[0] == '.' && args->name[1] == '.') {
#if XFS_BIG_INUMS || defined(DEBUG)
        ino = XFS_DIR2_SF_GET_INUMBER(sfp, &sfp->hdr.parent);
        ASSERT(args->inumber != ino);
#endif
        XFS_DIR2_SF_PUT_INUMBER(sfp, &args->inumber, &sfp->hdr.parent);
    }
    /*
     * Normal entry, look for the name.
     */
    else {
        for (i = 0, sfep = XFS_DIR2_SF_FIRSTENTRY(sfp);
                i < sfp->hdr.count;
                i++, sfep = XFS_DIR2_SF_NEXTENTRY(sfp, sfep)) {
            if (sfep->namelen == args->namelen &&
                    sfep->name[0] == args->name[0] &&
                    memcmp(args->name, sfep->name, args->namelen) == 0) {
#if XFS_BIG_INUMS || defined(DEBUG)
                ino = XFS_DIR2_SF_GET_INUMBER(sfp,
                                              XFS_DIR2_SF_INUMBERP(sfep));
                ASSERT(args->inumber != ino);
#endif
                XFS_DIR2_SF_PUT_INUMBER(sfp, &args->inumber,
                                        XFS_DIR2_SF_INUMBERP(sfep));
                break;
            }
        }
        /*
         * Didn't find it.
         */
        if (i == sfp->hdr.count) {
            ASSERT(args->oknoent);
#if XFS_BIG_INUMS
            if (i8elevated)
                xfs_dir2_sf_toino4(args);
#endif
            return XFS_ERROR(ENOENT);
        }
    }
#if XFS_BIG_INUMS
    /*
     * See if the old number was large, the new number is small.
     */
    if (ino > XFS_DIR2_MAX_SHORT_INUM &&
            args->inumber <= XFS_DIR2_MAX_SHORT_INUM) {
        /*
         * And the old count was one, so need to convert to small.
         */
        if (sfp->hdr.i8count == 1)
            xfs_dir2_sf_toino4(args);
        else
            sfp->hdr.i8count--;
    }
    /*
     * See if the old number was small, the new number is large.
     */
    if (ino <= XFS_DIR2_MAX_SHORT_INUM &&
            args->inumber > XFS_DIR2_MAX_SHORT_INUM) {
        /*
         * add to the i8count unless we just converted to 8-byte
         * inodes (which does an implied i8count = 1)
         */
        ASSERT(sfp->hdr.i8count != 0);
        if (!i8elevated)
            sfp->hdr.i8count++;
    }
#endif
    xfs_dir2_sf_check(args);
    xfs_trans_log_inode(args->trans, dp, XFS_ILOG_DDATA);
    return 0;
}
Beispiel #25
0
void
zfs_log_write(zilog_t *zilog, dmu_tx_t *tx, int txtype,
              znode_t *zp, offset_t off, ssize_t resid, int ioflag)
{
    itx_wr_state_t write_state;
    boolean_t slogging;
    uintptr_t fsync_cnt;

    if (zilog == NULL || zp->z_unlinked)
        return;

    ZFS_HANDLE_REPLAY(zilog, tx); /* exits if replay */

    slogging = spa_has_slogs(zilog->zl_spa);
    if (resid > zfs_immediate_write_sz && !slogging && resid <= zp->z_blksz)
        write_state = WR_INDIRECT;
    else if (ioflag & (FSYNC | FDSYNC))
        write_state = WR_COPIED;
    else
        write_state = WR_NEED_COPY;

    if ((fsync_cnt = (uintptr_t)tsd_get(zfs_fsyncer_key)) != 0) {
        (void) tsd_set(zfs_fsyncer_key, (void *)(fsync_cnt - 1));
    }

    while (resid) {
        itx_t *itx;
        lr_write_t *lr;
        ssize_t len;

        /*
         * If the write would overflow the largest block then split it.
         */
        if (write_state != WR_INDIRECT && resid > ZIL_MAX_LOG_DATA)
            len = SPA_MAXBLOCKSIZE >> 1;
        else
            len = resid;

        itx = zil_itx_create(txtype, sizeof (*lr) +
                             (write_state == WR_COPIED ? len : 0));
        lr = (lr_write_t *)&itx->itx_lr;
        if (write_state == WR_COPIED && dmu_read(zp->z_zfsvfs->z_os,
                zp->z_id, off, len, lr + 1, DMU_READ_NO_PREFETCH) != 0) {
            kmem_free(itx, offsetof(itx_t, itx_lr) +
                      itx->itx_lr.lrc_reclen);
            itx = zil_itx_create(txtype, sizeof (*lr));
            lr = (lr_write_t *)&itx->itx_lr;
            write_state = WR_NEED_COPY;
        }

        itx->itx_wr_state = write_state;
        if (write_state == WR_NEED_COPY)
            itx->itx_sod += len;
        lr->lr_foid = zp->z_id;
        lr->lr_offset = off;
        lr->lr_length = len;
        lr->lr_blkoff = 0;
        BP_ZERO(&lr->lr_blkptr);

        itx->itx_private = zp->z_zfsvfs;

        if ((zp->z_sync_cnt != 0) || (fsync_cnt != 0) ||
                (ioflag & (FSYNC | FDSYNC)))
            itx->itx_sync = B_TRUE;
        else
            itx->itx_sync = B_FALSE;

        zp->z_last_itx = zil_itx_assign(zilog, itx, tx);

        off += len;
        resid -= len;
    }
/*
 * Add a name to a shortform directory.
 * There are two algorithms, "easy" and "hard" which we decide on
 * before changing anything.
 * Convert to block form if necessary, if the new entry won't fit.
 */
int						/* error */
xfs_dir2_sf_addname(
    xfs_da_args_t		*args)		/* operation arguments */
{
    int			add_entsize;	/* size of the new entry */
    xfs_inode_t		*dp;		/* incore directory inode */
    int			error;		/* error return value */
    int			incr_isize;	/* total change in size */
    int			new_isize;	/* di_size after adding name */
    int			objchange;	/* changing to 8-byte inodes */
    xfs_dir2_data_aoff_t	offset;		/* offset for new entry */
    int			old_isize;	/* di_size before adding name */
    int			pick;		/* which algorithm to use */
    xfs_dir2_sf_t		*sfp;		/* shortform structure */
    xfs_dir2_sf_entry_t	*sfep;		/* shortform entry */

    xfs_dir2_trace_args("sf_addname", args);
    ASSERT(xfs_dir2_sf_lookup(args) == ENOENT);
    dp = args->dp;
    ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
    /*
     * Make sure the shortform value has some of its header.
     */
    if (dp->i_d.di_size < offsetof(xfs_dir2_sf_hdr_t, parent)) {
        ASSERT(XFS_FORCED_SHUTDOWN(dp->i_mount));
        return XFS_ERROR(EIO);
    }
    ASSERT(dp->i_df.if_bytes == dp->i_d.di_size);
    ASSERT(dp->i_df.if_u1.if_data != NULL);
    sfp = (xfs_dir2_sf_t *)dp->i_df.if_u1.if_data;
    ASSERT(dp->i_d.di_size >= XFS_DIR2_SF_HDR_SIZE(sfp->hdr.i8count));
    /*
     * Compute entry (and change in) size.
     */
    add_entsize = XFS_DIR2_SF_ENTSIZE_BYNAME(sfp, args->namelen);
    incr_isize = add_entsize;
    objchange = 0;
#if XFS_BIG_INUMS
    /*
     * Do we have to change to 8 byte inodes?
     */
    if (args->inumber > XFS_DIR2_MAX_SHORT_INUM && sfp->hdr.i8count == 0) {
        /*
         * Yes, adjust the entry size and the total size.
         */
        add_entsize +=
            (uint)sizeof(xfs_dir2_ino8_t) -
            (uint)sizeof(xfs_dir2_ino4_t);
        incr_isize +=
            (sfp->hdr.count + 2) *
            ((uint)sizeof(xfs_dir2_ino8_t) -
             (uint)sizeof(xfs_dir2_ino4_t));
        objchange = 1;
    }
#endif
    old_isize = (int)dp->i_d.di_size;
    new_isize = old_isize + incr_isize;
    /*
     * Won't fit as shortform any more (due to size),
     * or the pick routine says it won't (due to offset values).
     */
    if (new_isize > XFS_IFORK_DSIZE(dp) ||
            (pick =
                 xfs_dir2_sf_addname_pick(args, objchange, &sfep, &offset)) == 0) {
        /*
         * Just checking or no space reservation, it doesn't fit.
         */
        if (args->justcheck || args->total == 0)
            return XFS_ERROR(ENOSPC);
        /*
         * Convert to block form then add the name.
         */
        error = xfs_dir2_sf_to_block(args);
        if (error)
            return error;
        return xfs_dir2_block_addname(args);
    }
    /*
     * Just checking, it fits.
     */
    if (args->justcheck)
        return 0;
    /*
     * Do it the easy way - just add it at the end.
     */
    if (pick == 1)
        xfs_dir2_sf_addname_easy(args, sfep, offset, new_isize);
    /*
     * Do it the hard way - look for a place to insert the new entry.
     * Convert to 8 byte inode numbers first if necessary.
     */
    else {
        ASSERT(pick == 2);
#if XFS_BIG_INUMS
        if (objchange)
            xfs_dir2_sf_toino8(args);
#endif
        xfs_dir2_sf_addname_hard(args, objchange, new_isize);
    }
    xfs_trans_log_inode(args->trans, dp, XFS_ILOG_CORE | XFS_ILOG_DDATA);
    return 0;
}
Beispiel #27
0
 * Copyright (c) 2016 - Qeo LLC
 *
 * The source code form of this Qeo Open Source Project component is subject
 * to the terms of the Clear BSD license.
 *
 * You can redistribute it and/or modify it under the terms of the Clear BSD
 * License (http://directory.fsf.org/wiki/License:ClearBSD). See LICENSE file
 * for more details.
 *
 * The Qeo Open Source Project also includes third party Open Source Software.
 * See LICENSE file for more details.
 */

/**************************************************************
 ********          THIS IS A GENERATED FILE         ***********
 **************************************************************/

#include "EventWithPrimitives.h"

const DDS_TypeSupport_meta org_qeo_test_EventWithPrimitives_type[] = {
    { .tc = CDR_TYPECODE_STRUCT, .name = "org.qeo.test.EventWithPrimitives", .flags = TSMFLAG_DYNAMIC|TSMFLAG_GENID|TSMFLAG_MUTABLE, .nelem = 7, .size = sizeof(org_qeo_test_EventWithPrimitives_t) },
    { .tc = CDR_TYPECODE_BOOLEAN, .name = "MyBoolean", .offset = offsetof(org_qeo_test_EventWithPrimitives_t, MyBoolean) },
    { .tc = CDR_TYPECODE_OCTET, .name = "MyByte", .offset = offsetof(org_qeo_test_EventWithPrimitives_t, MyByte) },
    { .tc = CDR_TYPECODE_SHORT, .name = "MyInt16", .offset = offsetof(org_qeo_test_EventWithPrimitives_t, MyInt16) },
    { .tc = CDR_TYPECODE_LONG, .name = "MyInt32", .offset = offsetof(org_qeo_test_EventWithPrimitives_t, MyInt32) },
    { .tc = CDR_TYPECODE_LONGLONG, .name = "MyInt64", .offset = offsetof(org_qeo_test_EventWithPrimitives_t, MyInt64) },
    { .tc = CDR_TYPECODE_FLOAT, .name = "MyFloat32", .offset = offsetof(org_qeo_test_EventWithPrimitives_t, MyFloat32) },
    { .tc = CDR_TYPECODE_CSTRING, .name = "MyString", .flags = TSMFLAG_DYNAMIC, .offset = offsetof(org_qeo_test_EventWithPrimitives_t, MyString), .size = 0 },
};

int						/* error */
xfs_dir2_sf_getdents(
    xfs_inode_t		*dp,		/* incore directory inode */
    uio_t			*uio,		/* caller's buffer control */
    int			*eofp,		/* eof reached? (out) */
    xfs_dirent_t		*dbp,		/* caller's buffer */
    xfs_dir2_put_t		put)		/* abi's formatting function */
{
    int			error;		/* error return value */
    int			i;		/* shortform entry number */
    xfs_mount_t		*mp;		/* filesystem mount point */
    xfs_dir2_dataptr_t	off;		/* current entry's offset */
    xfs_dir2_put_args_t	p;		/* arg package for put rtn */
    xfs_dir2_sf_entry_t	*sfep;		/* shortform directory entry */
    xfs_dir2_sf_t		*sfp;		/* shortform structure */
    xfs_off_t			dir_offset;

    mp = dp->i_mount;

    ASSERT(dp->i_df.if_flags & XFS_IFINLINE);
    /*
     * Give up if the directory is way too short.
     */
    if (dp->i_d.di_size < offsetof(xfs_dir2_sf_hdr_t, parent)) {
        ASSERT(XFS_FORCED_SHUTDOWN(mp));
        return XFS_ERROR(EIO);
    }

    dir_offset = uio->uio_offset;

    ASSERT(dp->i_df.if_bytes == dp->i_d.di_size);
    ASSERT(dp->i_df.if_u1.if_data != NULL);

    sfp = (xfs_dir2_sf_t *)dp->i_df.if_u1.if_data;

    ASSERT(dp->i_d.di_size >= XFS_DIR2_SF_HDR_SIZE(sfp->hdr.i8count));

    /*
     * If the block number in the offset is out of range, we're done.
     */
    if (XFS_DIR2_DATAPTR_TO_DB(mp, dir_offset) > mp->m_dirdatablk) {
        *eofp = 1;
        return 0;
    }

    /*
     * Set up putargs structure.
     */
    p.dbp = dbp;
    p.put = put;
    p.uio = uio;
    /*
     * Put . entry unless we're starting past it.
     */
    if (dir_offset <=
            XFS_DIR2_DB_OFF_TO_DATAPTR(mp, mp->m_dirdatablk,
                                       XFS_DIR2_DATA_DOT_OFFSET)) {
        p.cook = XFS_DIR2_DB_OFF_TO_DATAPTR(mp, 0,
                                            XFS_DIR2_DATA_DOTDOT_OFFSET);
        p.ino = dp->i_ino;
#if XFS_BIG_INUMS
        p.ino += mp->m_inoadd;
#endif
        p.name = ".";
        p.namelen = 1;

        error = p.put(&p);

        if (!p.done) {
            uio->uio_offset =
                XFS_DIR2_DB_OFF_TO_DATAPTR(mp, mp->m_dirdatablk,
                                           XFS_DIR2_DATA_DOT_OFFSET);
            return error;
        }
    }

    /*
     * Put .. entry unless we're starting past it.
     */
    if (dir_offset <=
            XFS_DIR2_DB_OFF_TO_DATAPTR(mp, mp->m_dirdatablk,
                                       XFS_DIR2_DATA_DOTDOT_OFFSET)) {
        p.cook = XFS_DIR2_DB_OFF_TO_DATAPTR(mp, mp->m_dirdatablk,
                                            XFS_DIR2_DATA_FIRST_OFFSET);
        p.ino = XFS_DIR2_SF_GET_INUMBER(sfp, &sfp->hdr.parent);
#if XFS_BIG_INUMS
        p.ino += mp->m_inoadd;
#endif
        p.name = "..";
        p.namelen = 2;

        error = p.put(&p);

        if (!p.done) {
            uio->uio_offset =
                XFS_DIR2_DB_OFF_TO_DATAPTR(mp, mp->m_dirdatablk,
                                           XFS_DIR2_DATA_DOTDOT_OFFSET);
            return error;
        }
    }

    /*
     * Loop while there are more entries and put'ing works.
     */
    for (i = 0, sfep = XFS_DIR2_SF_FIRSTENTRY(sfp);
            i < sfp->hdr.count;
            i++, sfep = XFS_DIR2_SF_NEXTENTRY(sfp, sfep)) {

        off = XFS_DIR2_DB_OFF_TO_DATAPTR(mp, mp->m_dirdatablk,
                                         XFS_DIR2_SF_GET_OFFSET(sfep));

        if (dir_offset > off)
            continue;

        p.namelen = sfep->namelen;

        p.cook = XFS_DIR2_DB_OFF_TO_DATAPTR(mp, mp->m_dirdatablk,
                                            XFS_DIR2_SF_GET_OFFSET(sfep) +
                                            XFS_DIR2_DATA_ENTSIZE(p.namelen));

        p.ino = XFS_DIR2_SF_GET_INUMBER(sfp, XFS_DIR2_SF_INUMBERP(sfep));
#if XFS_BIG_INUMS
        p.ino += mp->m_inoadd;
#endif
        p.name = (char *)sfep->name;

        error = p.put(&p);

        if (!p.done) {
            uio->uio_offset = off;
            return error;
        }
    }

    /*
     * They all fit.
     */
    *eofp = 1;

    uio->uio_offset =
        XFS_DIR2_DB_OFF_TO_DATAPTR(mp, mp->m_dirdatablk + 1, 0);

    return 0;
}
Beispiel #29
0
#include <openssl/rand.h>
#endif

#ifdef HAVE_OPENSSL_EVP_H
#include <openssl/evp.h>
#endif

#include "rlm_eap_tls.h"

#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif

static CONF_PARSER module_config[] = {
	{ "tls", PW_TYPE_STRING_PTR,
	  offsetof(rlm_eap_tls_t, tls_conf_name), NULL, NULL },

	{ "virtual_server", PW_TYPE_STRING_PTR,
	  offsetof(rlm_eap_tls_t, virtual_server), NULL, NULL },

 	{ NULL, -1, 0, NULL, NULL }	   /* end the list */
};


/*
 *	Attach the EAP-TLS module.
 */
static int eaptls_attach(CONF_SECTION *cs, void **instance)
{
	rlm_eap_tls_t		*inst;
// TODO: add player payments for chance/chest
int main(int argc, char ** argv)
{
    struct timeval t1, t2;
    MPI_Init(&argc, &argv);
    gettimeofday(&t1, NULL);
    int rank, size;
    MPI_Comm_rank(MPI_COMM_WORLD, &globalrank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    globalsize = size;
    srand(time(NULL) + globalrank);
    struct location board[BSIZE];
    struct player players[NUMPLAYERS];
    int itr = 10000;
    long long bills[4]; // how much you owe each player at end of round
    init_players(players);
    init_board(board);
    char plocation;
    int pvalue;
    int numcomms = 1;
    MPI_Group world_group;
    MPI_Comm_group(MPI_COMM_WORLD, &world_group);
    playerdata d;
    d.money[0] = 0;
    d.money[1] = 0;
    d.money[2] = 0;
    d.money[3] = 0;
    output = (FILE **) malloc(size * sizeof(FILE *));

    // if 1 process created just run sequentially
    if (size == 1)
    {
        int done[4] = {1, 1, 1, 1};
        while (itr)
        {
            itr--;
            int i;
            for (i = 0; i < NUMPLAYERS; i++)
            {
                plocation = 0;
                pvalue = 0;
                if (players[i].money > 0)
                {
                    move(players, board, i, &pvalue, &plocation);
                    if (plocation)
                    {
                        board[plocation].owner = i;
                        players[i].money -= pvalue;
                    }
                }
                else
                {
                    players[i].order = -1;
                    if (done[i])
                    {
                        remove_properties(board, i);
                        done[i] = 0;
                    }
                }
            }
        }
        gettimeofday(&t2, NULL);
        results(players, board);
        double exectime = (t2.tv_sec - t1.tv_sec) * 1000000 + ((t2.tv_usec - t1.tv_usec));
        printf("Exec Time %lf\n", exectime);
        return 0;
    }

    // create a communicator for each monopoly game (for n > 4)
    MPI_Group * gamesel;
    MPI_Comm * games;
    int ranksel[4];
    if (size > 4)
    {
        numcomms = size / 4;
        games = (MPI_Comm *) malloc(numcomms * sizeof(MPI_Comm));
        gamesel = (MPI_Group *) malloc(numcomms * sizeof(MPI_Group));
        int i;
        for (i = 0; i < numcomms; i++)
        {
            ranksel[0] = 4 * i;
            ranksel[1] = 4 * i + 1;
            ranksel[2] = 4 * i + 2;
            ranksel[3] = 4 * i + 3;
            MPI_Group_incl(world_group, 4, ranksel, &gamesel[i]);
            MPI_Comm_create(MPI_COMM_WORLD, gamesel[i], &games[i]);
        }
    }
    else
    {
        // n < 4 so use MPI_COMM_WORLD
        games = (MPI_Comm *) malloc(1 * sizeof(MPI_Comm));
        games[0] = MPI_COMM_WORLD;
        numcomms = 1;
    }

    // create an MPI type so that we can use our player data struct in MPI communication calls
    const int nitems = 5;
    int blocklengths[5] = {4, 1, 1, 1, 1};
    MPI_Datatype types[5] = {MPI_LONG_LONG, MPI_INT, MPI_CHAR, MPI_CHAR, MPI_CHAR};
    MPI_Datatype MPI_MONO_DATA;
    MPI_Aint offsets[5];
    offsets[0] = offsetof(playerdata, money);
    offsets[1] = offsetof(playerdata, pvalue);
    offsets[2] = offsetof(playerdata, plocation);
    offsets[3] = offsetof(playerdata, order);
    offsets[4] = offsetof(playerdata, trade);
    MPI_Type_create_struct(nitems, blocklengths, offsets, types, &MPI_MONO_DATA);
    MPI_Type_commit(&MPI_MONO_DATA);

    MPI_Comm_rank(games[globalrank / 4], &rank);

#ifdef DEBUG
    char fname[10];
    snprintf(fname, 10, "mon%d.dbg", globalrank);
    output[globalrank] = fopen(fname, "w");
    fprintf(output[globalrank], "MAIN begin loop\n");
    print_board_info(board);
#endif
    // run the game for 40000 turns (10000 per player)
    while (itr > 0)
    {
        itr--;
        pvalue = 0;
        plocation = 0;
        d.trade = 0;
        d.order = rank;
#ifdef DEBUG
        fprintf(output[globalrank], "MAIN tag 1 rank %d\n", rank);
#endif
        move(players, board, rank, &pvalue, &plocation);
        d.pvalue = pvalue;
        d.plocation = plocation;
#ifdef DEBUG
        fprintf(output[globalrank], "using comm %d\n", globalrank / 4);
        if (games[globalrank / 4] != MPI_COMM_WORLD)
        {
            fprintf(output[globalrank], "COMM ERROR\n");
        }
#endif
        send_info(&d, players, board, rank, games[globalrank / 4], MPI_MONO_DATA);
#ifdef DEBUG
        fprintf(output[globalrank], "MAIN tag 3 rank %d\n", rank);
        print_board_info(board);
#endif
    }
    
#ifdef DEBUG
    fprintf(output[globalrank], "MAIN last tag rank %d\n", rank);
#endif
    // get results from each process
    gather_results(players, board, games, numcomms, globalrank);
    gettimeofday(&t2, NULL);
    if (globalrank == 0)
    {
        results(players, board);
    }


#ifdef DEBUG
    fclose(output[globalrank]);
#endif
    double exectime = (t2.tv_sec - t1.tv_sec) * 1000000 + ((t2.tv_usec - t1.tv_usec));
    if (globalrank == 0)
    {
        printf("Exec Time %lf\n", exectime);
    }
    MPI_Finalize();

    return 0;
}