Exemplo n.º 1
0
static inline bool init_signals(void)
{
	DWORD pid = GetCurrentProcessId();

	signal_restart = init_event(EVENT_CAPTURE_RESTART, pid);
	if (!signal_restart) {
		return false;
	}

	signal_stop = init_event(EVENT_CAPTURE_STOP, pid);
	if (!signal_stop) {
		return false;
	}

	signal_ready = init_event(EVENT_HOOK_READY, pid);
	if (!signal_ready) {
		return false;
	}

	signal_exit = init_event(EVENT_HOOK_EXIT, pid);
	if (!signal_exit) {
		return false;
	}

	return true;
}
Exemplo n.º 2
0
void start(const Category& category, trace_event* evt) {
	if (!do_trace_events) {
		// No one to process the event is here
		return;
	}

	if (!initialized) {
		return;
	}

	init_event(category, evt);

	evt->duration = 0;
	evt->type = EventType::Complete;
	evt->event_id = ++current_id;

	if (do_gpu_queries && category.usesGPUCounter()) {
		Assertion(get_tid() == main_thread_id, "This function must be called from the main thread!");

		gpu_trace_event gpu_event;
		gpu_event.base_evt.category = &category;
		gpu_event.base_evt.tid = 1;
		gpu_event.base_evt.pid = GPU_PID;
		gpu_event.base_evt.type = EventType::Begin;

		gpu_event.gpu_begin_query = get_gpu_timestamp_query();

		// This does not need to be synchronized since GPU queries are only allowed on the main thread.
		gpu_events.push(gpu_event);
	}
}
Exemplo n.º 3
0
static void doChild(int argc, char** argv)
{
    char* filename;
    HANDLE hFile;
    int i;

    filename=argv[2];
    hFile=CreateFileA(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
    if (hFile == INVALID_HANDLE_VALUE)
        return;

    /* Arguments */
    childPrintf(hFile, "[Arguments]\n");
    if (winetest_debug > 2)
        trace("argcA=%d\n", argc);
    childPrintf(hFile, "argcA=%d\n", argc);
    for (i = 0; i < argc; i++)
    {
        if (winetest_debug > 2)
            trace("argvA%d=%s\n", i, argv[i]);
        childPrintf(hFile, "argvA%d=%s\n", i, encodeA(argv[i]));
    }
    CloseHandle(hFile);

    init_event(filename);
    SetEvent(hEvent);
    CloseHandle(hEvent);
}
Exemplo n.º 4
0
shared_ptr<event>
drag_event( int which, const mouse_t& mouse)
{
	shared_ptr<event> ret( new event());;
	ret->set_drag( true);
	init_event( which, ret, mouse);
	return ret;
}
Exemplo n.º 5
0
shared_ptr<event>
click_event( int which, const mouse_t& mouse)
{
	shared_ptr<event> ret( new event());;
	ret->set_release( true);
	ret->set_click( true);
	init_event( which, ret, mouse);
	return ret;
}
Exemplo n.º 6
0
static void init_serial_port(char *devname, int iobase, int irq, struct unit *unit) {
  struct serial_port *sp;
  dev_t devno;

  sp = (struct serial_port *) kmalloc(sizeof(struct serial_port));
  memset(sp, 0, sizeof(struct serial_port));

  sp->iobase = iobase;
  sp->irq = irq;

  sp->cfg.speed = 115200;
  sp->cfg.databits = 8;
  sp->cfg.parity = PARITY_NONE;
  sp->cfg.stopbits = 1;
  sp->cfg.rx_timeout = INFINITE;
  sp->cfg.tx_timeout = INFINITE;

  init_dpc(&sp->dpc);
  sp->dpc.flags |= DPC_NORAND;

  init_event(&sp->event, 0, 0);

  init_sem(&sp->tx_sem, QUEUE_SIZE);
  init_mutex(&sp->tx_lock, 0);

  init_sem(&sp->rx_sem, 0);
  init_mutex(&sp->rx_lock, 0);

  // Disable interrupts
  outp(sp->iobase + UART_IER, 0);

  // Determine UART type
  check_uart_type(sp);

  // Set baudrate, parity, databits and stopbits
  serial_config(sp);

  // Enable FIFO
  if (sp->type == UART_16550A) {
    outp(sp->iobase + UART_FCR, FCR_ENABLE | FCR_RCV_RST | FCR_XMT_RST | FCR_TRIGGER_14);
  }

  // Turn on DTR, RTS and OUT2
  sp->mcr = MCR_DTR | MCR_RTS | MCR_IENABLE;  
  outp(sp->iobase + UART_MCR, sp->mcr);

  // Create device
  devno = dev_make(devname, &serial_driver, unit, sp);

  // Enable interrupts
  register_interrupt(&sp->intr, IRQ2INTR(sp->irq), serial_handler, sp);
  enable_irq(sp->irq);
  outp((unsigned short) (sp->iobase + UART_IER), IER_ERXRDY | IER_ETXRDY | IER_ERLS | IER_EMSC);

  kprintf(KERN_INFO "%s: %s iobase 0x%x irq %d\n", device(devno)->name, uart_name[sp->type], sp->iobase, sp->irq);
}
Exemplo n.º 7
0
END_TEST

START_TEST(test_zookeeper)
{
	assert_ret(init_event(4096), 0);
#ifdef BUILD_ZOOKEEPER
	zoo_set_debug_level(0);
#endif
	do_test("zookeeper:localhost:2181,timeout=1000");
}
Exemplo n.º 8
0
void init_nsevents(HTMLDocumentNode *doc)
{
    nsDocumentEventListener *listener;
    nsIDOMEventTarget *target;
    nsresult nsres;

    static const PRUnichar wsz_blur[]      = {'b','l','u','r',0};
    static const PRUnichar wsz_focus[]     = {'f','o','c','u','s',0};
    static const PRUnichar wsz_keypress[]  = {'k','e','y','p','r','e','s','s',0};
    static const PRUnichar wsz_load[]      = {'l','o','a','d',0};

    listener = heap_alloc(sizeof(nsDocumentEventListener));
    if(!listener)
        return;

    TRACE("%p %p\n", doc, listener);

    listener->ref = 1;
    listener->doc = doc;

    init_listener(&listener->blur_listener,        listener, &blur_vtbl);
    init_listener(&listener->focus_listener,       listener, &focus_vtbl);
    init_listener(&listener->keypress_listener,    listener, &keypress_vtbl);
    init_listener(&listener->load_listener,        listener, &load_vtbl);
    init_listener(&listener->htmlevent_listener,   listener, &htmlevent_vtbl);

    doc->nsevent_listener = listener;

    nsres = nsIDOMWindow_QueryInterface(doc->basedoc.window->nswindow, &IID_nsIDOMEventTarget, (void**)&target);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDOMEventTarget interface: %08x\n", nsres);
        return;
    }

    init_event(target, wsz_blur,     &listener->blur_listener.nsIDOMEventListener_iface,     TRUE);
    init_event(target, wsz_focus,    &listener->focus_listener.nsIDOMEventListener_iface,    TRUE);
    init_event(target, wsz_keypress, &listener->keypress_listener.nsIDOMEventListener_iface, FALSE);
    init_event(target, wsz_load,     &listener->load_listener.nsIDOMEventListener_iface,     TRUE);

    nsIDOMEventTarget_Release(target);
}
Exemplo n.º 9
0
void init_nsevents(NSContainer *This)
{
    nsIDOMWindow *dom_window;
    nsIDOMEventTarget *target;
    nsresult nsres;

    static const PRUnichar wsz_blur[]      = {'b','l','u','r',0};
    static const PRUnichar wsz_focus[]     = {'f','o','c','u','s',0};
    static const PRUnichar wsz_keypress[]  = {'k','e','y','p','r','e','s','s',0};
    static const PRUnichar wsz_load[]      = {'l','o','a','d',0};
    static const PRUnichar DOMNodeInsertedW[] =
        {'D','O','M','N','o','d','e','I','n','s','e','r','t','e','d',0};

    init_listener(&This->blur_listener,        This, &blur_vtbl);
    init_listener(&This->focus_listener,       This, &focus_vtbl);
    init_listener(&This->keypress_listener,    This, &keypress_vtbl);
    init_listener(&This->load_listener,        This, &load_vtbl);
    init_listener(&This->node_insert_listener, This, &node_insert_vtbl);
    init_listener(&This->htmlevent_listener,   This, &htmlevent_vtbl);

    nsres = nsIWebBrowser_GetContentDOMWindow(This->webbrowser, &dom_window);
    if(NS_FAILED(nsres)) {
        ERR("GetContentDOMWindow failed: %08x\n", nsres);
        return;
    }

    nsres = nsIDOMWindow_QueryInterface(dom_window, &IID_nsIDOMEventTarget, (void**)&target);
    nsIDOMWindow_Release(dom_window);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDOMEventTarget interface: %08x\n", nsres);
        return;
    }

    init_event(target, wsz_blur,       NSEVENTLIST(&This->blur_listener),        TRUE);
    init_event(target, wsz_focus,      NSEVENTLIST(&This->focus_listener),       TRUE);
    init_event(target, wsz_keypress,   NSEVENTLIST(&This->keypress_listener),    FALSE);
    init_event(target, wsz_load,       NSEVENTLIST(&This->load_listener),        TRUE);
    init_event(target, DOMNodeInsertedW,NSEVENTLIST(&This->node_insert_listener),TRUE);

    nsIDOMEventTarget_Release(target);
}
Exemplo n.º 10
0
// --------------------------------------------------------------------------
inline
event::event (
 dom_string const& type,
 event_init event_init_dict
)
// --------------------------------------------------------------------------
{
  m_creation_time = std::chrono::duration_cast<dom_time_stamp>(
   std::chrono::high_resolution_clock::now().time_since_epoch()
  );
  init_event(type, event_init_dict.bubbles, event_init_dict.cancelable);
}
Exemplo n.º 11
0
void value(const Category& category, float value) {
	if (!do_counter_events) {
		return;
	}

	trace_event evt;
	init_event(category, &evt);
	evt.type = EventType::Counter;
	evt.value = value;
	evt.event_id = ++current_id;

	submit_event(&evt);
}
Exemplo n.º 12
0
void end(const Category& category, const Scope& async_scope) {
	if (!do_async_events) {
		return;
	}

	trace_event evt;
	init_event(category, &evt);

	evt.type = EventType::AsyncEnd;
	evt.scope = &async_scope;
	evt.event_id = ++current_id;

	submit_event(&evt);
}
Exemplo n.º 13
0
void init_nsevents(HTMLDocumentNode *doc)
{
    nsDocumentEventListener *listener;
    nsIDOMEventTarget *target;
    nsresult nsres;

    listener = heap_alloc(sizeof(nsDocumentEventListener));
    if(!listener)
        return;

    TRACE("%p %p\n", doc, listener);

    listener->ref = 1;
    listener->doc = doc;

    init_listener(&listener->blur_listener,        listener, &blur_vtbl);
    init_listener(&listener->focus_listener,       listener, &focus_vtbl);
    init_listener(&listener->keypress_listener,    listener, &keypress_vtbl);
    init_listener(&listener->load_listener,        listener, &load_vtbl);
    init_listener(&listener->htmlevent_listener,   listener, &htmlevent_vtbl);

    doc->nsevent_listener = listener;

    nsres = nsIDOMWindow_QueryInterface(doc->basedoc.window->nswindow, &IID_nsIDOMEventTarget, (void**)&target);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDOMEventTarget interface: %08x\n", nsres);
        return;
    }

    init_event(target, blurW,     &listener->blur_listener.nsIDOMEventListener_iface,     TRUE);
    init_event(target, focusW,    &listener->focus_listener.nsIDOMEventListener_iface,    TRUE);
    init_event(target, keypressW, &listener->keypress_listener.nsIDOMEventListener_iface, FALSE);
    init_event(target, loadW,     &listener->load_listener.nsIDOMEventListener_iface,     TRUE);

    nsIDOMEventTarget_Release(target);
}
Exemplo n.º 14
0
void add_nsevent_listener(HTMLDocumentNode *doc, nsIDOMNode *nsnode, LPCWSTR type)
{
    nsIDOMEventTarget *target;
    nsresult nsres;

    if(nsnode)
        nsres = nsIDOMNode_QueryInterface(nsnode, &IID_nsIDOMEventTarget, (void**)&target);
    else
        nsres = nsIDOMWindow_QueryInterface(doc->basedoc.window->nswindow, &IID_nsIDOMEventTarget, (void**)&target);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDOMEventTarget interface: %08x\n", nsres);
        return;
    }

    init_event(target, type, NSEVENTLIST(&doc->nsevent_listener->htmlevent_listener), TRUE);
    nsIDOMEventTarget_Release(target);
}
Exemplo n.º 15
0
void uart3_init(void)
{
	USART_InitTypeDef USART_InitStructure;
 	NVIC_InitTypeDef NVIC_InitStructure;
	
	memset(&u3_send,0,sizeof(UART_SEND));

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);

	gpio_cfg((uint32_t)UART3_TX_PORT_GROUP, UART3_TX_PIN, GPIO_Mode_AF_PP);
	gpio_cfg((uint32_t)UART3_RX_PORT_GROUP, UART3_RX_PIN, GPIO_Mode_AF_IF);
	GPIO_PinAFConfig(UART3_TX_PORT_GROUP, UART3_TX_PIN_SOURSE, GPIO_AF_USART3);
	GPIO_PinAFConfig(UART3_RX_PORT_GROUP, UART3_RX_PIN_SOURSE, GPIO_AF_USART3);

	u3_send.wait = init_event();
	if(u3_send.wait == 0)
	{
		p_err("uart_init sys_sem_new2 err\n");
		return;
	}

	USART_InitStructure.USART_BaudRate = UART3_DEFAULT_BAUD;
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits = USART_StopBits_1;
	USART_InitStructure.USART_Parity = USART_Parity_No ;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	USART_Init(USART3, &USART_InitStructure); 
   	USART_Cmd(USART3, ENABLE);

	USART_ITConfig(USART3, USART_IT_TC, ENABLE);
	USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
//	USART_ITConfig(USART2, USART_IT_TXE, ENABLE);
	NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = USART3_IRQn_Priority;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	USART_ClearITPendingBit(USART3, USART_IT_TC);
	USART_ClearITPendingBit(USART3, USART_IT_RXNE);
	
	NVIC_EnableIRQ(USART3_IRQn);

}
Exemplo n.º 16
0
void init_sdl(void /*char *rom_name*/) {
    int surface_type = (CF_BOOL(cf_get_item_by_name("hwsurface"))? SDL_HWSURFACE : SDL_SWSURFACE);


    char *nomouse = getenv("SDL_NOMOUSE");
    SDL_Surface *icon;

    SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_NOPARACHUTE);

#ifdef GP2X
    atexit(gp2x_quit);
#else
    atexit(SDL_Quit);
#endif

    if (screen_init() == SDL_FALSE) {
	printf("Screen initialization failed.\n");
	exit(-1);
    }

    buffer = SDL_CreateRGBSurface(surface_type, 352, 256, 16, 0xF800, 0x7E0,
				  0x1F, 0);
    SDL_FillRect(buffer,NULL,SDL_MapRGB(buffer->format,0xE5,0xE5,0xE5));

    fontbuf = SDL_CreateRGBSurfaceFrom(font_image.pixel_data, font_image.width, font_image.height
				       , 24, font_image.width * 3, 0xFF0000, 0xFF00, 0xFF, 0);
    SDL_SetColorKey(fontbuf,SDL_SRCCOLORKEY,SDL_MapRGB(fontbuf->format,0xFF,0,0xFF));
    fontbuf=SDL_DisplayFormat(fontbuf);
    icon = SDL_CreateRGBSurfaceFrom(gngeo_icon.pixel_data, gngeo_icon.width,
				    gngeo_icon.height, gngeo_icon.bytes_per_pixel*8,
				    gngeo_icon.width * gngeo_icon.bytes_per_pixel,
				    0xFF, 0xFF00, 0xFF0000, 0);
    
    SDL_WM_SetIcon(icon,NULL);

    calculate_hotkey_bitmasks();    
	init_event();

    //if (nomouse == NULL)
	//SDL_ShowCursor(SDL_DISABLE);
}
Exemplo n.º 17
0
void add_nsevent_listener(NSContainer *container, LPCWSTR type)
{
    nsIDOMWindow *dom_window;
    nsIDOMEventTarget *target;
    nsresult nsres;

    nsres = nsIWebBrowser_GetContentDOMWindow(container->webbrowser, &dom_window);
    if(NS_FAILED(nsres)) {
        ERR("GetContentDOMWindow failed: %08x\n", nsres);
        return;
    }

    nsres = nsIDOMWindow_QueryInterface(dom_window, &IID_nsIDOMEventTarget, (void**)&target);
    nsIDOMWindow_Release(dom_window);
    if(NS_FAILED(nsres)) {
        ERR("Could not get nsIDOMEventTarget interface: %08x\n", nsres);
        return;
    }

    init_event(target, type, NSEVENTLIST(&container->htmlevent_listener), TRUE);
    nsIDOMEventTarget_Release(target);
}
Exemplo n.º 18
0
void gwave_main(void *p, int argc, char **argv)
{
	int c;
	int i;
	int nobacktrace = 0;

	/* In guile-1.5 and later, need to use scm_primitive_eval_x
	 * in order to change modules so that our C primitives
	 * registered below become globals, instead of hidden away
	 * in the guile-user module
	 */
	{
		SCM exp = scm_c_read_string("(define-module (guile))");
		scm_primitive_eval_x(exp);
	}

	init_scwm_guile();
	init_gtkmisc();
	init_gwave();
	init_cmd();
	init_wavewin();
	init_wavelist();
	init_wavepanel();
	init_event();
	init_draw();
	
	gtk_init(&argc, &argv);

	prog_name = argv[0];

	/* simple pre-processing of debugging options that we need to set up
	 * before we get into guile.   These options cannot be bundled.
	 * Most of the general user options are handled in std-args.scm  */
	for(i = 1; i < argc; i++) {
		if(strcmp(argv[i], "-n") == 0) {
			nobacktrace = 1;
		} else if (strcmp(argv[i], "-v") == 0) {
			v_flag = 1;
		} else if (strcmp(argv[i], "-x") == 0) {
			x_flag = 1;
			SCM_SETCDR(scm_gwave_debug, SCM_BOOL_T);
		}
	}

	gtk_rc_parse_string(gwave_base_gtkrc);
	gtk_rc_parse("gwave.gtkrc");
//	assert( SCM_CONSP(scm_gwave_tooltips) );

#ifdef GUILE_GTK_EXTRA_LOADPATH
	scm_c_eval_string("(set! %load-path (cons \"" GUILE_GTK_EXTRA_LOADPATH "\" %load-path))");
#endif

	/* the default for this seems to have changed between guile-1.3
	   and guile-1.3.2;  only the first clause is needed when 
	   we drop support for guile-1.3.2 */
	if (!nobacktrace) {
		scm_c_eval_string("(debug-enable 'debug)(debug-enable 'backtrace) (read-enable 'positions)");
	} /* else {
	scm_c_eval_str("(debug-disable 'debug)(read-disable 'positions)");
	}*/

	/* the compiled-in initial scheme code comes from minimal.scm,
	   built into init_scheme_string.c by the Makefile
	   Among other things, it finds and loads system and user .gwaverc
	   files.
	*/
	{ /* scope */
		extern char *init_scheme_string;
		SCM res;
		if(v_flag) {fprintf(stderr, "running init_scheme_string\n");}
		res = scwm_safe_eval_str(init_scheme_string);
		if(v_flag) {
			printf("result="); fflush(stdout);
			scm_display(res, scm_cur_outp);
			printf("\n"); fflush(stdout);
		}
                if(!SCM_NFALSEP(res)) {
                        fprintf(stderr, "gwave: aborting due to errors.\n");
                        exit(1);
                }

	} /* end scope */

	wtable = g_new0(WaveTable, 1);
	wtable->cursor[0] = g_new0(VBCursor, 1);
	wtable->cursor[1] = g_new0(VBCursor, 1);
	wtable->srange = g_new0(SelRange, 1);
	wtable->npanels = 0;
	wtable->panels = NULL;

	setup_colors(wtable);
	setup_waveform_window();

	xg_init(NULL);  /* X-server interprocess communication for Gtk+ */

	gtk_main();
	exit(0);
}
void lua_player::run_global_scope()
{
  QObject::disconnect(this, SIGNAL (started ()));

  luaL_openlibs(L);

  luabind::open(L);

  luabind::module(L, "ghtv")
  [
   luabind::class_<lua_player>("lua_player")
  ];

  init_sandbox();
  init_canvas();
  init_event();

  start_time = boost::posix_time::microsec_clock::universal_time();

  QObject::connect(this, SIGNAL(resume_current_frame_signal (int)), this
                   , SLOT(resume_current_frame (int)), Qt::QueuedConnection);
  QObject::connect(this, SIGNAL(run_require_signal (std::string)), this
                   , SLOT(run_require_slot (std::string)), Qt::QueuedConnection);

  try
  {
    main_file_url = player::create_url(path, root_path);
    lua_path = main_file_url.path ().toStdString ();

    {
      std::string::reverse_iterator
        iterator = std::find(lua_path.rbegin(), lua_path.rend(), '/')
        , iterator_backslash = std::find(lua_path.rbegin(), lua_path.rend(), '\\');
      iterator = (std::min)(iterator, iterator_backslash);
      if(iterator != lua_path.rend())
        lua_path.erase(boost::prior(iterator.base()), lua_path.end());
      else
      {
        std::string error_msg = "Couldn't create a absolute path from the path for the NCL file: ";
        error_msg += lua_path;
        ncl_window->error_occurred(error_msg);
        return;
      }
    }

    activate_frame(path, main_file_url.toString ().toStdString ());

    QObject::connect(current_activation_frame (), SIGNAL(execution_finished ())
                     , this, SLOT(global_scope_finished ()));
    QObject::connect(this, SIGNAL(signal_all_execution_finished ())
                     , this, SLOT(try_unqueue_events ()), Qt::QueuedConnection);
    QObject::connect(this, SIGNAL(signal_try_unqueue_event ())
                     , this, SLOT(try_unqueue_event ()), Qt::QueuedConnection);

    assert(pending_download_file == 0);
    pending_download_file = new player::url_file(main_file_url, this);
    if(!pending_download_file->local())
    {
      QObject::connect(this, SIGNAL(download_lua_signal ()), this
                       , SLOT(download_global ()), Qt::QueuedConnection);
      QObject::connect(pending_download_file, SIGNAL(download_finished_signal()), this
                       , SLOT(download_lua()));
      QObject::connect(pending_download_file, SIGNAL(error_signal(std::string)), this
                       , SLOT(download_error(std::string)));
    }
    else
    {
      QObject::connect(this, SIGNAL(download_lua_signal ()), this
                       , SLOT(download_global ()), Qt::QueuedConnection);
      Q_EMIT download_lua_signal();
    }
  }
  catch(std::exception const& e)
  {
    std::string error = "Error loading file ";
    error += root_path;
    error += '/';
    error += path;
    error += " with error: ";
    error += e.what();
    ncl_window->error_occurred(error);
  }
}
Exemplo n.º 20
0
/**
* \fn int main(int argc, char *argv[])
* \brief Fonction principale.
*
*
* La fonction principale récupère les arguments et le fichier de configuration,
* initialise la vue, le modèle, puis éxécute la boucle de calcul.
* Une fois cette boucle terminée, elle libère la mémoire et finalise l'éxécution.
*
*
*/
int main(int argc, char *argv[])
{
	config_t *conf = parse_args(argc, argv);

	int error = 0;
	error_t *error_cell = NULL;

	if(conf == NULL)
	{
		return 1;
	}

	view_t *view = init_view(conf);

	model_t *model = init_model(conf);

	double delta_time = 0;
	event_t event;

	init_event(&event);

	vect_t chunk_pos;
	init_vect(&chunk_pos, 0.4, 0.4, 0.4);
	add_chunk(model, &chunk_pos);
	//add_chunk(model, &chunk_pos);
	//add_chunk(model, &chunk_pos);
	//add_chunk(model, &chunk_pos);
	//add_chunk(model, &chunk_pos);
	//add_chunk(model, &chunk_pos);


	while(!event.exit_wanted)
	{
		delta_time = temporize(conf);
		get_event(&event, view);

		if(event.click_callback != NULL)
			(*(event.click_callback))(model);

		error = update_model(model, &event, delta_time);

		if(error)
		{
			printf("ERREUR DETECTEE !\n");
			error_cell = get_error_list();
			int error_count = 0;

			while(error_cell != NULL)
			{
				printf("%s\n", error_cell->comment);
				error_cell = error_cell->next;
				error_count++;
				if(error_count >= 10)
				{
					printf("Appuyez sur ENTREE pour voir la suite, q puis ENTREE pour quitter.\n");
					if(getchar() == 'q')
						return 1;
					error_count = 0;
				}
			}
			return 1;
		}

		update_view(view, model, &event);
	}

	close_conf(conf);
	close_view(view);
	close_model(model);

	return 0;
}
Exemplo n.º 21
0
int main(int argc, char **argv)
{
	int ch, longindex, ret;
	unsigned long flags;
	struct option *long_options;
	const struct command *commands;
	const char *short_options;
	char *p;
	const struct sd_option *sd_opts;
	uint8_t sdhost[16];
	int sdport;

	log_dog_operation(argc, argv);

	install_crash_handler(crash_handler);

	init_commands(&commands);

	if (argc < 2)
		usage(commands, 0);

	flags = setup_commands(commands, argv[1], argv[2]);

	optind = 3;

	sd_opts = build_sd_options(command_opts);
	long_options = build_long_options(sd_opts);
	short_options = build_short_options(sd_opts);

	while ((ch = getopt_long(argc, argv, short_options, long_options,
				&longindex)) >= 0) {

		switch (ch) {
		case 'a':
			if (!str_to_addr(optarg, sdhost)) {
				sd_err("Invalid ip address %s", optarg);
				return EXIT_FAILURE;
			}
			memcpy(sd_nid.addr, sdhost, sizeof(sdhost));
			break;
		case 'p':
			sdport = strtol(optarg, &p, 10);
			if (optarg == p || sdport < 1 || sdport > UINT16_MAX) {
				sd_err("Invalid port number '%s'", optarg);
				exit(EXIT_USAGE);
			}
			sd_nid.port = sdport;
			break;
		case 'r':
			raw_output = true;
			break;
		case 'v':
			verbose = true;
			break;
		case 'h':
			subcommand_usage(argv[1], argv[2], EXIT_SUCCESS);
			break;
		case '?':
			usage(commands, EXIT_USAGE);
			break;
		default:
			if (command_parser)
				command_parser(ch, optarg);
			else
				usage(commands, EXIT_USAGE);
			break;
		}
	}

	if (!is_stdout_console() || raw_output)
		highlight = false;

	if (flags & CMD_NEED_NODELIST) {
		ret = update_node_list(SD_MAX_NODES);
		if (ret < 0) {
			sd_err("Failed to get node list");
			exit(EXIT_SYSFAIL);
		}
	}

	if (flags & CMD_NEED_ARG && argc == optind)
		subcommand_usage(argv[1], argv[2], EXIT_USAGE);

	if (init_event(EPOLL_SIZE) < 0)
		exit(EXIT_SYSFAIL);

	if (init_work_queue(get_nr_nodes) != 0) {
		sd_err("Failed to init work queue");
		exit(EXIT_SYSFAIL);
	}

	if (sockfd_init()) {
		sd_err("sockfd_init() failed");
		exit(EXIT_SYSFAIL);
	}

	ret = command_fn(argc, argv);
	if (ret == EXIT_USAGE)
		subcommand_usage(argv[1], argv[2], EXIT_USAGE);
	return ret;
}
Exemplo n.º 22
0
int main(int argc, char **argv)
{
	int ch, longindex, ret;
	unsigned long flags;
	struct option *long_options;
	const struct command *commands;
	const char *short_options;
	char *p, *env;
	const struct sd_option *sd_opts;
	uint8_t sdhost[16];
	int sdport;
	struct timespec start, end;

	start = get_time_tick();

	log_dog_operation(argc, argv);

	install_crash_handler(crash_handler);

	init_commands(&commands);

	if (argc < 2)
		usage(commands, 0);

	flags = setup_commands(commands, argv[1], argv[2]);

	optind = 3;

	sd_opts = build_sd_options(command_opts);
	long_options = build_long_options(sd_opts);
	short_options = build_short_options(sd_opts);

	env = getenv("SHEEPDOG_DOG_ADDR");
	if (env) {
		if (!str_to_addr(env, sdhost)) {
			sd_err("Invalid ip address %s", env);
			return EXIT_FAILURE;
		}
		memcpy(sd_nid.addr, sdhost, sizeof(sdhost));
	}

	env = getenv("SHEEPDOG_DOG_PORT");
	if (env) {
		sdport = strtol(env, &p, 10);
		if (env == p || sdport < 1 || sdport > UINT16_MAX
		    || !is_numeric(env)) {
			sd_err("Invalid port number '%s'", env);
			exit(EXIT_USAGE);
		}
		sd_nid.port = sdport;
	}

	while ((ch = getopt_long(argc, argv, short_options, long_options,
				&longindex)) >= 0) {

		switch (ch) {
		case 'a':
			if (!str_to_addr(optarg, sdhost)) {
				sd_err("Invalid ip address %s", optarg);
				return EXIT_FAILURE;
			}
			memcpy(sd_nid.addr, sdhost, sizeof(sdhost));
			break;
		case 'p':
			sdport = strtol(optarg, &p, 10);
			if (optarg == p || sdport < 1 || sdport > UINT16_MAX
					|| !is_numeric(optarg)) {
				sd_err("Invalid port number '%s'", optarg);
				exit(EXIT_USAGE);
			}
			sd_nid.port = sdport;
			break;
		case 'r':
			raw_output = true;
			break;
		case 'v':
			verbose = true;
			break;
		case 'h':
			subcommand_usage(argv[1], argv[2], EXIT_SUCCESS);
			break;
		case 'T':
			elapsed_time = true;
			break;
		case '?':
			usage(commands, EXIT_USAGE);
			break;
		default:
			if (command_parser)
				command_parser(ch, optarg);
			else
				usage(commands, EXIT_USAGE);
			break;
		}
	}

	if (sd_inode_actor_init(dog_bnode_writer, dog_bnode_reader) < 0)
		exit(EXIT_SYSFAIL);

	if (!is_stdout_console() || raw_output)
		highlight = false;

	if (flags & CMD_NEED_NODELIST) {
		ret = update_node_list(SD_MAX_NODES);
		if (ret < 0) {
			sd_err("Failed to get node list");
			exit(EXIT_SYSFAIL);
		}
	}

	if (flags & CMD_NEED_ARG && argc == optind)
		subcommand_usage(argv[1], argv[2], EXIT_USAGE);

	if (init_event(EPOLL_SIZE) < 0)
		exit(EXIT_SYSFAIL);

	if (wq_trace_init() < 0)
		exit(EXIT_SYSFAIL);

	if (init_work_queue(get_nr_nodes) != 0) {
		sd_err("Failed to init work queue");
		exit(EXIT_SYSFAIL);
	}

	if (sockfd_init()) {
		sd_err("sockfd_init() failed");
		exit(EXIT_SYSFAIL);
	}

	ret = command_fn(argc, argv);
	if (ret == EXIT_USAGE)
		subcommand_usage(argv[1], argv[2], EXIT_USAGE);

	if (elapsed_time) {
		end = get_time_tick();
		printf("\nElapsed time: %.3lf seconds\n",
				get_time_interval(&start, &end));
	}

	return ret;
}
Exemplo n.º 23
0
int
init_ecb(void)
{

#ifdef KDEBUG
  int debug_level = options.send_kdebug;
#endif /* KDEBUG */

  int ret;
  int group = 1;
  int size = 0;
  int alt_size = 0;
  int i = 0;
  int zero_fd;
  int num_evts = 0;

  zero_fd = open("/dev/zero", O_RDONLY);
  if (zero_fd < 0) {
    perror("open /dev/zero");
    exit(-1);
  }
  DEBG(MSG_SEND, "init_ecb: zero_fd = %d\n", zero_fd);

  if (options.ecb_size != OPT_DEFAULT_ECB_SIZE) {
    num_evts = options.ecb_size;
  } else {
    num_evts = maxconns + 1;
    /* num_evts = max_fds + 1; */
  }
  size = ((num_evts) * sizeof(struct event)) + sizeof(struct event_control);
  DEBG(MSG_SEND, "init_ecb: num_evts = %d\n", num_evts);
  DEBG(MSG_SEND, "init_ecb: maxconns = %d\n", maxconns);
  DEBG(MSG_SEND, "init_ecb: sizeof(struct event) = %d\n",
    sizeof(struct event));
  DEBG(MSG_SEND, "init_ecb: sizeof(struct event_control) = %d\n",
    sizeof(struct event_control));
  DEBG(MSG_SEND, "init_ecb: ecb size = %d\n", size);

  /* round size to next highest page size */
  if (size % PAGE_SIZE != 0) {
    alt_size = ((size / PAGE_SIZE) * PAGE_SIZE) + PAGE_SIZE;
  }
  DEBG(MSG_SEND, "rounded up ecb alt_size = %d\n", alt_size);
  assert(alt_size % PAGE_SIZE == 0);

  ecb = (struct event_control *) mmap(0, alt_size,
    PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE, zero_fd, 0);

  if (ecb == MAP_FAILED) {
    printf("init_ecb: - no memory\n");
    exit(1);
  }

  printf("init_ecb: ecb size = %d\n", alt_size);

  printf("init_ecb: ecb = %p\n", ecb);
  DEBG(MSG_SEND, "ecb = %p\n", ecb);

  stack = (char *) mmap(0, STACK_SIZE,
    PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE, zero_fd, 0);

  if (stack == MAP_FAILED) {
    printf("init_ecb - no memory\n");
    exit(1);
  }

  printf("init_ecb: stack size = %d\n", STACK_SIZE);

  saved_stack_addr = stack;
  *saved_stack_addr = 0xbe;

  DEBG(MSG_SEND, "Got stack: %p\n", stack);
  DEBG(MSG_SEND, "Saved stack addr = %p\n", saved_stack_addr);
  DEBG(MSG_SEND, "      value at stack addr = 0x%x\n", *saved_stack_addr);
  printf("init_ecb: stack top = %p\n", stack);
  stack += STACK_SIZE - 4;  /* 4092; */
  printf("init_ecb: stack bottom = %p\n", stack);

  ret = init_event(ecb, size);
  if (ret < 0) {
    printf("init_ecb: bad init_event %i %s\n", errno, strerror(errno));
    printf("init_ecb: ret = %d\n", ret);
    if (errno == ENOSYS) {
      printf("init_ecb: system call not supported in this kernel\n");
    }
    exit(-1);
  }
  printf("init_ecb: ecb->eventbuf[0] = %p\n", &ecb->eventbuf[0]);
  printf("init_ecb: ecb->eventbuf[ecb->event_list_size-1] = %p\n",
    &ecb->eventbuf[ecb->event_list_size - 1]);

  /*NEW */
  for (i = 0; i < ecb->event_list_size; ++i) {
    /* ecb->eventbuf[i].type = (u32)-1; */
  }

  /* DEBG(MSG_SEND, "init_ecb: calling print_ecb_types\n"); */
  /* print_ecb_types(); */


  if (options.auto_accept) {
    group = AUTO_ACCEPT_GRP_NUM;
    ret = evtctl(EVT_IPACCEPT, SEVTGROUP, &group, sizeof(int));
    if (ret < 0) {
      printf("init_ecb: bad SEVTGROUP %i %s\n", errno, strerror(errno));
      printf("init_ecb: ret = %d\n", ret);
      exit(-1);
    }
  }


  group = SIG_GRP_NUM;
  ret = evtctl(EVT_SIG, SEVTGROUP, &group, sizeof(int));
  if (ret < 0) {
    printf("init_ecb: bad SEVTGROUP: %i %s\n", errno, strerror(errno));
    printf("init_ecb: ret = %d\n", ret);
    exit(-1);
  }

  group = MSG_GRP_NUM;
  ret = evtctl(EVT_MSG, SEVTGROUP, &group, sizeof(int));
  if (ret < 0) {
    printf("init_ecb: bad SEVTGROUP: %i %s\n", errno, strerror(errno));
    printf("init_ecb: ret = %d\n", ret);
    exit(-1);
  }

  /* Define critical section */
  ret = evtctl(EVT_ANY, SEVTCRITCODE, start_critical,
    (int) end_critical - (int) start_critical);
  if (ret < 0) {
    printf("init_ecb: bad SEVTCRITCODE: %i %s\n", errno, strerror(errno));
    printf("init_ecb: ret = %d\n", ret);
    exit(-1);
  }

  /* Set stack for event handler */
  ecb->stack = stack;
  printf("init_ecb: ECB: list_size:%i notify:%08x pid:%i\n",
    ecb->event_list_size, (u32) ecb->notify, getpid());
  printf("init_ecb: ECB: ecb: %08x stack: %08x buf:%08x end_buf: %08x\n",
    (unsigned) ecb, (u32) ecb->stack,
    (unsigned) &ecb->eventbuf[0],
    (unsigned) &ecb->eventbuf[ecb->event_list_size - 1]);

  if (ecb->stack == NULL) {
    printf("init_ecb: Bad ECB stack %p\n", __builtin_return_address(0));
    exit(-1);
  }
#ifdef KDEBUG
  if (evtctl(EVT_ANY, SEVTDEBUG, (void *) debug_level,
      sizeof(debug_level)) < 0) {
    printf("init_ecb: evtctl call failed\n");
    exit(1);
  }
#endif

  ecb->queue = 0;
  ecb->notify = 0;
  ecb->handler = &send_handler;
  ecb->no_block = 0;
  ecb->threshold = 0;

#ifdef SEND_AUTO_ACCEPT_CONTROL
  /*
     ecb->aperture = maxconns;
   */
  ecb->aperture = options.auto_accept_aperture;
  ecb->completed = 0;
#endif /* SEND_AUTO_ACCEPT_CONTROL */

  for (i = 0; i < NSIG; i++) {
    sigs[i] = NULL;
  } /* for */

  sigs[SIGUSR1] = (sighandlerfn_t) send_sig_usr1_handler;
  /* For a while these we not generating core dumps so this was an attempt */
  /* sigs[SIGSEGV]  = (sighandlerfn_t) send_sig_crash_handler; */
  /* sigs[SIGBUS]   = (sighandlerfn_t) send_sig_crash_handler; */
  sigs[SIGUSR2] = (sighandlerfn_t) send_sig_usr2_handler;
  /* sigs[20]    = handle_sigstop; */
  sigs[SIGIO] = (sighandlerfn_t) (-1);
  /* Don't know where the SIGCHLD comes from but for now die if we get this */
  sigs[SIGCHLD] = (sighandlerfn_t) send_sig_kill_handler;
  sigs[SIGINT] = (sighandlerfn_t) send_sig_kill_handler;
  sigs[SIGHUP] = (sighandlerfn_t) send_sig_kill_handler;
  sigs[SIGTERM] = (sighandlerfn_t) send_sig_kill_handler;
  sigs[SIGPIPE] = (sighandlerfn_t) send_sig_pipe_handler;
  /* sigs[SIGTRAP]    = (sighandlerfn_t)(-1); */
  /* sigs[SIGTRAP]  = (sighandlerfn_t) send_sig_crash_handler; */

  for (i = 0; i < NSIG; i++) {
    DEBG(MSG_SEND, "sigs[%d] = %p\n", i, sigs[i]);
  } /* for */
  return 0;
}
Exemplo n.º 24
0
int main(int argc, char *argv[])
{
	struct sigaction sa;
	struct rlimit limit;
	int i, c, rc;
	int opt_foreground = 0, opt_allow_links = 0;
	enum startup_state opt_startup = startup_enable;
	extern char *optarg;
	extern int optind;
	struct ev_loop *loop;
	struct ev_io netlink_watcher;
	struct ev_signal sigterm_watcher;
	struct ev_signal sighup_watcher;
	struct ev_signal sigusr1_watcher;
	struct ev_signal sigusr2_watcher;
	struct ev_signal sigchld_watcher;

	/* Get params && set mode */
	while ((c = getopt(argc, argv, "flns:")) != -1) {
		switch (c) {
		case 'f':
			opt_foreground = 1;
			break;
		case 'l':
			opt_allow_links=1;
			break;
		case 'n':
			do_fork = 0;
			break;
		case 's':
			for (i=0; i<startup_INVALID; i++) {
				if (strncmp(optarg, startup_states[i],
					strlen(optarg)) == 0) {
					opt_startup = i;
					break;
				}
			}
			if (i == startup_INVALID) {
				fprintf(stderr, "unknown startup mode '%s'\n",
					optarg);
				usage();
			}
			break;
		default:
			usage();
		}
	}

	/* check for trailing command line following options */
	if (optind < argc) {
		usage();
	}

	if (opt_allow_links)
		set_allow_links(1);

	if (opt_foreground) {
		config.daemonize = D_FOREGROUND;
		set_aumessage_mode(MSG_STDERR, DBG_YES);
	} else {
		config.daemonize = D_BACKGROUND;
		set_aumessage_mode(MSG_SYSLOG, DBG_NO);
		(void) umask( umask( 077 ) | 022 );
	}

#ifndef DEBUG
	/* Make sure we are root */
	if (getuid() != 0) {
		fprintf(stderr, "You must be root to run this program.\n");
		return 4;
	}
#endif

	/* Register sighandlers */
	sa.sa_flags = 0 ;
	sigemptyset( &sa.sa_mask ) ;
	/* Ignore all signals by default */
	sa.sa_handler = SIG_IGN;
	for (i=1; i<NSIG; i++)
		sigaction( i, &sa, NULL );

	atexit(clean_exit);

	/* Raise the rlimits in case we're being started from a shell
         * with restrictions. Not a fatal error.  */
	limit.rlim_cur = RLIM_INFINITY;
	limit.rlim_max = RLIM_INFINITY;
	setrlimit(RLIMIT_FSIZE, &limit);
	setrlimit(RLIMIT_CPU, &limit);

	/* Load the Configuration File */
	if (load_config(&config, TEST_AUDITD))
		return 6;

	if (config.priority_boost != 0) {
		errno = 0;
		rc = nice((int)-config.priority_boost);
		if (rc == -1 && errno) {
			audit_msg(LOG_ERR, "Cannot change priority (%s)", 
					strerror(errno));
			return 1;
		}
	} 
	
	/* Daemonize or stay in foreground for debugging */
	if (config.daemonize == D_BACKGROUND) {
		if (become_daemon() != 0) {
			audit_msg(LOG_ERR, "Cannot daemonize (%s)",
				strerror(errno));
			tell_parent(FAILURE);
			return 1;
		} 
		openlog("auditd", LOG_PID, LOG_DAEMON);
	}

	/* Init netlink */
	if ((fd = audit_open()) < 0) {
        	audit_msg(LOG_ERR, "Cannot open netlink audit socket");
		tell_parent(FAILURE);
		return 1;
	}

	/* Init the event handler thread */
	write_pid_file();
	if (init_event(&config)) {
		if (pidfile)
			unlink(pidfile);
		tell_parent(FAILURE);
		return 1;
	}

	if (init_dispatcher(&config)) {
		if (pidfile)
			unlink(pidfile);
		tell_parent(FAILURE);
		return 1;
	}

	/* Get machine name ready for use */
	if (resolve_node(&config)) {
		if (pidfile)
			unlink(pidfile);
		tell_parent(FAILURE);
		return 1;
	}

	/* Write message to log that we are alive */
	{
		struct utsname ubuf;
		char start[DEFAULT_BUF_SZ];
		const char *fmt = audit_lookup_format((int)config.log_format);
		if (fmt == NULL)
			fmt = "UNKNOWN";
		if (uname(&ubuf) != 0) {
			if (pidfile)
				unlink(pidfile);
			tell_parent(FAILURE);
			return 1;
		}
		if (getsubj(subj))
			snprintf(start, sizeof(start),
				"auditd start, ver=%s format=%s "
			    "kernel=%.56s auid=%u pid=%d subj=%s res=success",
				VERSION, fmt, ubuf.release,
				audit_getloginuid(), getpid(), subj);
		else
			snprintf(start, sizeof(start),
				"auditd start, ver=%s format=%s "
				"kernel=%.56s auid=%u pid=%d res=success",
				VERSION, fmt, ubuf.release,
				audit_getloginuid(), getpid());
		if (send_audit_event(AUDIT_DAEMON_START, start)) {
        		audit_msg(LOG_ERR, "Cannot send start message");
			if (pidfile)
				unlink(pidfile);
			shutdown_dispatcher();
			tell_parent(FAILURE);
			return 1;
		}
	}

	/* Tell kernel not to kill us */
	avoid_oom_killer();

	/* let config manager init */
	init_config_manager();

	if (opt_startup != startup_nochange && (audit_is_enabled(fd) < 2) &&
	    audit_set_enabled(fd, (int)opt_startup) < 0) {
		char emsg[DEFAULT_BUF_SZ];
		if (*subj)
			snprintf(emsg, sizeof(emsg),
			"auditd error halt, auid=%u pid=%d subj=%s res=failed",
				audit_getloginuid(), getpid(), subj);
		else
			snprintf(emsg, sizeof(emsg),
				"auditd error halt, auid=%u pid=%d res=failed",
				audit_getloginuid(), getpid());
		stop = 1;
		send_audit_event(AUDIT_DAEMON_ABORT, emsg);
		audit_msg(LOG_ERR,
		"Unable to set initial audit startup state to '%s', exiting",
			startup_states[opt_startup]);
		close_down();
		if (pidfile)
			unlink(pidfile);
		shutdown_dispatcher();
		tell_parent(FAILURE);
		return 1;
	}

	/* Tell the kernel we are alive */
	if (audit_set_pid(fd, getpid(), WAIT_YES) < 0) {
		char emsg[DEFAULT_BUF_SZ];
		if (*subj)
			snprintf(emsg, sizeof(emsg),
			"auditd error halt, auid=%u pid=%d subj=%s res=failed",
				audit_getloginuid(), getpid(), subj);
		else
			snprintf(emsg, sizeof(emsg),
				"auditd error halt, auid=%u pid=%d res=failed",
				audit_getloginuid(), getpid());
		stop = 1;
		send_audit_event(AUDIT_DAEMON_ABORT, emsg);
		audit_msg(LOG_ERR, "Unable to set audit pid, exiting");
		close_down();
		if (pidfile)
			unlink(pidfile);
		shutdown_dispatcher();
		tell_parent(FAILURE);
		return 1;
	}

	/* Depending on value of opt_startup (-s) set initial audit state */
	loop = ev_default_loop (EVFLAG_NOENV);

	ev_io_init (&netlink_watcher, netlink_handler, fd, EV_READ);
	ev_io_start (loop, &netlink_watcher);

	ev_signal_init (&sigterm_watcher, term_handler, SIGTERM);
	ev_signal_start (loop, &sigterm_watcher);

	ev_signal_init (&sighup_watcher, hup_handler, SIGHUP);
	ev_signal_start (loop, &sighup_watcher);

	ev_signal_init (&sigusr1_watcher, user1_handler, SIGUSR1);
	ev_signal_start (loop, &sigusr1_watcher);

	ev_signal_init (&sigusr2_watcher, user2_handler, SIGUSR2);
	ev_signal_start (loop, &sigusr2_watcher);

	ev_signal_init (&sigchld_watcher, child_handler, SIGCHLD);
	ev_signal_start (loop, &sigchld_watcher);

	if (auditd_tcp_listen_init (loop, &config)) {
		char emsg[DEFAULT_BUF_SZ];
		if (*subj)
			snprintf(emsg, sizeof(emsg),
			"auditd error halt, auid=%u pid=%d subj=%s res=failed",
				audit_getloginuid(), getpid(), subj);
		else
			snprintf(emsg, sizeof(emsg),
				"auditd error halt, auid=%u pid=%d res=failed",
				audit_getloginuid(), getpid());
		stop = 1;
		send_audit_event(AUDIT_DAEMON_ABORT, emsg);
		tell_parent(FAILURE);
	} else {
		/* Now tell parent that everything went OK */
		tell_parent(SUCCESS);
		audit_msg(LOG_NOTICE,
	    "Init complete, auditd %s listening for events (startup state %s)",
			VERSION,
			startup_states[opt_startup]);
	}

	/* Parent should be gone by now...   */
	if (do_fork)
		close(init_pipe[1]);

	// Init complete, start event loop
	if (!stop)
		ev_loop (loop, 0);

	auditd_tcp_listen_uninit (loop, &config);

	// Tear down IO watchers Part 1
	ev_signal_stop (loop, &sighup_watcher);
	ev_signal_stop (loop, &sigusr1_watcher);
	ev_signal_stop (loop, &sigusr2_watcher);
	ev_signal_stop (loop, &sigterm_watcher);

	/* Write message to log that we are going down */
	rc = audit_request_signal_info(fd);
	if (rc > 0) {
		struct audit_reply trep;

		rc = get_reply(fd, &trep, rc);
		if (rc > 0) {
			char txt[MAX_AUDIT_MESSAGE_LENGTH];
			snprintf(txt, sizeof(txt),
				"auditd normal halt, sending auid=%u "
				"pid=%d subj=%s res=success",
				 trep.signal_info->uid,
				 trep.signal_info->pid, 
				 trep.signal_info->ctx); 
			send_audit_event(AUDIT_DAEMON_END, txt);
		} 
	} 
	if (rc <= 0)
		send_audit_event(AUDIT_DAEMON_END, 
				"auditd normal halt, sending auid=? "
				"pid=? subj=? res=success");
	free(rep);

	// Tear down IO watchers Part 2
	ev_io_stop (loop, &netlink_watcher);

	// Give DAEMON_END event a little time to be sent in case
	// of remote logging
	usleep(10000); // 10 milliseconds
	shutdown_dispatcher();

	// Tear down IO watchers Part 3
	ev_signal_stop (loop, &sigchld_watcher);

	close_down();
	free_config(&config);
	ev_default_destroy();

	return 0;
}
Exemplo n.º 25
0
int main(int argc, char *argv[])
{
	dhcpctl_handle conn = NULL;
	char *conffile=NULL;
	char ch;
	
	name = strdup("OMAPI");
	    
	openlog("dhcparpd", LOG_PID, LOG_DAEMON);

	/* Parse Commandline Options */
	while((ch = getopt(argc, argv, "c:dh")) != -1) {
		switch(ch){
			case 'c':
				conffile = strdup(optarg);
				break;
			case 'd':
				do_daemonise=0;
				break;
			case 'h':
				usage(argv[0]);
				return 0;
			default:
				fprintf(stderr, "Unknown option '%c'!", ch);
				usage(argv[0]);
				return 1;
		}
	}

	/* Try a default configfile if non specified */
	if (conffile==NULL) {
		conffile = strdup("/etc/dhcparpd.conf");
	}
	if (parse_config(config,conffile)) {
		fprintf(stderr,"Unable to parse configfile: %s\n", 
				conffile);
		return 1;
	}
	free(conffile);

	/* Daemonise */
	if (do_daemonise) {
		daemonise(argv[0]);
		put_pid(pidfile);
	}
	
	parse_mappings();

	conn = dhcpd_connect(servername, port, name, key);

	if (!conn) {
		Log(LOG_CRIT, "failed to connect to dhcp server");
		return 1;
	}

	arp_init(interface,conn);

	init_event();
	init_netlink();

	if (pcap_init(interface))
		return 1;

        Log(LOG_NOTICE, "Ready for action! Lets Go...");
	run();

	return 0;
}
Exemplo n.º 26
0
/*
 * 函数名:USART1_Config
 * 描述  :USART1 GPIO 配置,工作模式配置。115200 8-N-1
 * 输入  :无
 * 输出  : 无
 * 调用  :外部调用
 */
void uart1_init(void)
{
	USART_InitTypeDef USART_InitStructure;
 	NVIC_InitTypeDef NVIC_InitStructure;
	
	memset(&u1_recv,0,sizeof(UART_RECV));
	
	u1_recv.pkg.pending.val = 1;  //防止用户输入
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); 
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2,ENABLE);

	gpio_cfg((uint32_t)UART1_TX_PORT_GROUP, UART1_TX_PIN, GPIO_Mode_AF_PP);
	gpio_cfg((uint32_t)UART1_RX_PORT_GROUP, UART1_RX_PIN, GPIO_Mode_AF_IF);
	GPIO_PinAFConfig(UART1_TX_PORT_GROUP, UART1_TX_PIN_SOURSE, GPIO_AF_USART1);
	GPIO_PinAFConfig(UART1_RX_PORT_GROUP, UART1_RX_PIN_SOURSE, GPIO_AF_USART1);

	
	u1_send.wait = init_event();
	if(u1_send.wait  == 0)
	{
		p_err("uart_init sys_sem_new1 err\n");
		return;
	}

	USART_InitStructure.USART_BaudRate = UART1_DEFAULT_BAUD;
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits = USART_StopBits_1;
	USART_InitStructure.USART_Parity = USART_Parity_No ;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
	USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
	USART_Init(USART1, &USART_InitStructure); 
	USART_Cmd(USART1, ENABLE);
	//USART_ITConfig(USART1, USART_IT_TC, ENABLE);
	USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
//	USART_ITConfig(USART2, USART_IT_TXE, ENABLE);

	NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = USART1_IRQn_Priority;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
#if UART1_USE_DMA
	DMA_RxConfiguration((uint32_t *)u1_recv.c_buff, UART_RECV_BUFF_SIZE);  //循环缓冲区
#endif	
	USART_ClearITPendingBit(USART1, USART_IT_TC);
	USART_ClearITPendingBit(USART1, USART_IT_RXNE);
	NVIC_EnableIRQ(USART1_IRQn);

#if UART1_USE_DMA
	NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream5_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = DMA2_Stream5_IRQn_Priority;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);

	NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream7_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = DMA2_Stream7_IRQn_Priority;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
#endif
}
Exemplo n.º 27
0
/***************************************************************************** 
 * this function handles the direct memory access to the buffer
 * and copies objects to and from memory
 *****************************************************************************/
int dmarequest(const message_t *request, message_t **response_ptr) {
  unsigned int offset;
  /*
     int blockrequest = 0;
     */
  int verbose = 0;

  /* these are used for blocking the read requests */
  struct timeval tp;
  struct timespec ts;

  /* use a local variable for datasel (in GET_DAT) */
  datasel_t datasel;

  /* these are for typecasting */
  headerdef_t    *headerdef;
  datadef_t      *datadef;
  eventdef_t     *eventdef;
  eventsel_t     *eventsel;

  /* this will hold the response */
  message_t *response;
  response      = (message_t*)malloc(sizeof(message_t));

  /* check for "out of memory" problems */
  if (response == NULL) {
    *response_ptr = NULL;
    return -1;
  }
  response->def = (messagedef_t*)malloc(sizeof(messagedef_t));

  /* check for "out of memory" problems */
  if (response->def == NULL) {
    *response_ptr = NULL;
    free(response);
    return -1;
  }
  response->buf = NULL;
  /* the response should be passed to the calling function, where it should be freed */
  *response_ptr = response;

  if (verbose>1) print_request(request->def);

  switch (request->def->command) {

    case PUT_HDR:
      if (verbose>1) fprintf(stderr, "dmarequest: PUT_HDR\n");
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);
      pthread_mutex_lock(&mutexevent);

      headerdef = (headerdef_t*)request->buf;
      if (verbose>1) print_headerdef(headerdef);

      /* delete the old header, data and events */
      free_header();
      free_data();
      free_event();

      /* store the header and re-initialize */
      header      = (header_t*)malloc(sizeof(header_t));
      DIE_BAD_MALLOC(header);
      header->def = (headerdef_t*)malloc(sizeof(headerdef_t));
      DIE_BAD_MALLOC(header->def);
      header->buf = malloc(headerdef->bufsize);
      DIE_BAD_MALLOC(header->buf);
      memcpy(header->def, request->buf, sizeof(headerdef_t));
      memcpy(header->buf, (char*)request->buf+sizeof(headerdef_t), headerdef->bufsize);
      header->def->nsamples = 0;
      header->def->nevents  = 0;

      init_data();
      init_event();

      response->def->version = VERSION;
      response->def->bufsize = 0;
      /* check whether memory could indeed be allocated */
      if (data!= NULL && data->buf != NULL && data->def != NULL) {
        response->def->command = PUT_OK;
      } else {
        /* let's at least tell the client that something's wrong */
        response->def->command = PUT_ERR;	
      }

      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case PUT_DAT:
      if (verbose>1) fprintf(stderr, "dmarequest: PUT_DAT\n");
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);

      datadef = (datadef_t*)request->buf;
      if (verbose>1) print_datadef(datadef);
      if (verbose>2) print_buf(request->buf, request->def->bufsize);

      response->def->version = VERSION;
      response->def->bufsize = 0;
      if (request->def->bufsize < sizeof(datadef_t))
        response->def->command = PUT_ERR;
      else if (header==NULL || data==NULL)
        response->def->command = PUT_ERR;
      else if (header->def->nchans != datadef->nchans)
        response->def->command = PUT_ERR;
      else if (header->def->data_type != datadef->data_type)
        response->def->command = PUT_ERR;
      else if (datadef->nsamples > current_max_num_sample)
        response->def->command = PUT_ERR;
      else {
        unsigned int i;
        unsigned int wordsize = wordsize_from_type(header->def->data_type);
        unsigned int datasize = wordsize * datadef->nsamples * datadef->nchans;

        response->def->command = PUT_OK;

        if (wordsize == 0) {
          fprintf(stderr, "dmarequest: unsupported data type (%d)\n", datadef->data_type);
          response->def->command = PUT_ERR;
        } else if (datasize > datadef->bufsize || (datadef->bufsize + sizeof(datadef_t)) > request->def->bufsize) {
          fprintf(stderr, "dmarequest: invalid size definitions in PUT_DAT request\n");
          response->def->command = PUT_ERR;
        } else {

          /* record the time at which the data was received */
          if (clock_gettime(CLOCK_REALTIME, &putdat_clock) != 0) {
            perror("clock_gettime");
            return -1;
          }

          /* number of bytes per sample (all channels) is given by wordsize x number of channels */
          unsigned int chansize = wordsize * data->def->nchans;
          /* request_data points to actual data samples within the request, use char* for convenience */
          const char *request_data = (const char *) request->buf + sizeof(datadef_t);
          char *buffer_data = (char *)data->buf;

          for (i=0; i<datadef->nsamples; i++) {
            memcpy(buffer_data+(thissample*chansize), request_data+(i*chansize), chansize);
            header->def->nsamples++;
            thissample++;
            thissample = WRAP(thissample, current_max_num_sample);
          }
          /* Signal possibly waiting threads that we have received data */
          pthread_cond_broadcast(&getData_cond);
        }
      }

      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case PUT_EVT:
      if (verbose>1) fprintf(stderr, "dmarequest: PUT_EVT\n");
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexevent);

      /* record the time at which the event was received */
      if (clock_gettime(CLOCK_REALTIME, &putevt_clock) != 0) {
        perror("clock_gettime");
        return -1;
      }

      /* Give an error message if there is no header, or if the given event array is defined badly */
      if (header==NULL || event==NULL || check_event_array(request->def->bufsize, request->buf) < 0) {
        response->def->version = VERSION;
        response->def->command = PUT_ERR;
        response->def->bufsize = 0;
      }
      else {	/* go over all events and store them one by one */
        response->def->version = VERSION;
        response->def->command = PUT_OK;
        response->def->bufsize = 0;

        offset = 0; /* this represents the offset of the event in the buffer */
        while (offset<request->def->bufsize) {
          FREE(event[thisevent].def);
          FREE(event[thisevent].buf);

          eventdef = (eventdef_t*)((char*)request->buf+offset);
          if (verbose>1) print_eventdef(eventdef);

          event[thisevent].def = (eventdef_t*)malloc(sizeof(eventdef_t));
          DIE_BAD_MALLOC(event[thisevent].def);
          memcpy(event[thisevent].def, (char*)request->buf+offset, sizeof(eventdef_t));

          if (event[thisevent].def->sample == EVENT_AUTO_SAMPLE) {
            /* automatically convert event->def->sample to current sample number */
            /* make some fine adjustment of the assigned sample number */
            double adjust = (putevt_clock.tv_sec - putdat_clock.tv_sec) + (double)(putevt_clock.tv_nsec - putdat_clock.tv_nsec) / 1000000000L;
            event[thisevent].def->sample = header->def->nsamples + (int)(header->def->fsample*adjust);
          }

          offset += sizeof(eventdef_t);
          event[thisevent].buf = malloc(eventdef->bufsize);
          DIE_BAD_MALLOC(event[thisevent].buf);
          memcpy(event[thisevent].buf, (char*)request->buf+offset, eventdef->bufsize);
          offset += eventdef->bufsize;
          if (verbose>1) print_eventdef(event[thisevent].def);
          thisevent++;
          thisevent = WRAP(thisevent, MAXNUMEVENT);
          header->def->nevents++;
        }
      }

      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexheader);
      break;

    case GET_HDR:
      if (verbose>1) fprintf(stderr, "dmarequest: GET_HDR\n");
      if (header==NULL) {
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
        break;
      }

      pthread_mutex_lock(&mutexheader);

      response->def->version = VERSION;
      response->def->command = GET_OK;
      response->def->bufsize = 0;
      response->def->bufsize = append(&response->buf, response->def->bufsize, header->def, sizeof(headerdef_t));
      response->def->bufsize = append(&response->buf, response->def->bufsize, header->buf, header->def->bufsize);

      pthread_mutex_unlock(&mutexheader);
      break;

    case GET_DAT:
      if (verbose>1) fprintf(stderr, "dmarequest: GET_DAT\n");
      if (header==NULL || data==NULL) {
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
        break;
      }

      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);

      if (request->def->bufsize) {
        /* the selection has been specified */
        memcpy(&datasel, request->buf, sizeof(datasel_t));
        /* If endsample is -1 read the buffer to the end */
        if(datasel.endsample == -1)
        {
          datasel.endsample = header->def->nsamples - 1;
        }
      }
      else {
        /* determine a valid selection */
        if (header->def->nsamples>current_max_num_sample) {
          /* the ringbuffer is completely full */
          datasel.begsample = header->def->nsamples - current_max_num_sample;
          datasel.endsample = header->def->nsamples - 1;
        }
        else {
          /* the ringbuffer is not yet completely full */
          datasel.begsample = 0;
          datasel.endsample = header->def->nsamples - 1;
        }
      }

      /*

      // if the read should block...
      if(blockrequest == 1)
      {
      // check whether data is available
      while((datasel.begsample >= (datasel.endsample+1)) || (datasel.endsample > header->def->nsamples - 1))
      {
      // if not unlock all mutexes
      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);

      // wait for the condition to be signaled
      pthread_mutex_lock(&getData_mutex);
      gettimeofday(&tp, NULL);
      ts.tv_sec = tp.tv_sec;
      ts.tv_nsec = tp.tv_usec * 1000;
      ts.tv_sec += 1;
      pthread_cond_timedwait(&getData_cond, &getData_mutex, &ts);
      pthread_mutex_unlock(&getData_mutex);

      // Lock the mutexes again
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);
      if(datasel.begsample == (datasel.endsample+1))
      datasel.endsample = header->def->nsamples - 1;
      }
      }
      */

      if (verbose>1) print_headerdef(header->def);
      if (verbose>1) print_datasel(&datasel);

      if (datasel.begsample < 0 || datasel.endsample < 0) {
        fprintf(stderr, "dmarequest: err1\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if (datasel.begsample >= header->def->nsamples || datasel.endsample >= header->def->nsamples) {
        fprintf(stderr, "dmarequest: err2\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if ((header->def->nsamples - datasel.begsample) > current_max_num_sample) {
        fprintf(stderr, "dmarequest: err3\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else {
        unsigned int wordsize = wordsize_from_type(data->def->data_type);
        if (wordsize==0) {
          fprintf(stderr, "dmarequest: unsupported data type (%d)\n", data->def->data_type);
          response->def->version = VERSION;
          response->def->command = GET_ERR;
          response->def->bufsize = 0;
        }  else {
          unsigned int n;
          response->def->version = VERSION;
          response->def->command = GET_OK;
          response->def->bufsize = 0;

          /* determine the number of samples to return */
          n = datasel.endsample - datasel.begsample + 1;

          response->buf = malloc(sizeof(datadef_t) + n*data->def->nchans*wordsize);
          if (response->buf == NULL) {
            /* not enough space for copying data into response */
            fprintf(stderr, "dmarequest: out of memory\n");
            response->def->command = GET_ERR;
          } 
          else {
            /* number of bytes per sample (all channels) */
            unsigned int chansize = data->def->nchans * wordsize;

            /* convenience pointer to start of actual data in response */
            char *resp_data = ((char *) response->buf) + sizeof(datadef_t);

            /* this is the location of begsample within the ringbuffer */
            unsigned int start_index = 	WRAP(datasel.begsample, current_max_num_sample);

            /* have datadef point into the freshly allocated response buffer and directly
               fill in the information */
            datadef = (datadef_t *) response->buf;
            datadef->nchans    = data->def->nchans;
            datadef->data_type = data->def->data_type;
            datadef->nsamples  = n;
            datadef->bufsize   = n*chansize;

            response->def->bufsize = sizeof(datadef_t) + datadef->bufsize;

            if (start_index + n <= current_max_num_sample) {
              /* we can copy everything in one go */
              memcpy(resp_data, (char*)(data->buf) + start_index*chansize, n*chansize);
            } else {
              /* need to wrap around at current_max_num_sample */
              unsigned int na = current_max_num_sample - start_index;
              unsigned int nb = n - na;

              memcpy(resp_data, (char*)(data->buf) + start_index*chansize, na*chansize);
              memcpy(resp_data + na*chansize, (char*)(data->buf), nb*chansize);

              /* printf("Wrapped around!\n"); */
            }
          }
        }
      }

      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case GET_EVT:
      if (verbose>1) fprintf(stderr, "dmarequest: GET_EVT\n");
      if (header==NULL || event==NULL || header->def->nevents==0) {
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
        break;
      }

      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexevent);

      eventsel = (eventsel_t*)malloc(sizeof(eventsel_t));
      DIE_BAD_MALLOC(eventsel);

      /* determine the selection */
      if (request->def->bufsize) {
        /* the selection has been specified */
        memcpy(eventsel, request->buf, sizeof(eventsel_t));
      }
      else {
        /* determine a valid selection */
        if (header->def->nevents>MAXNUMEVENT) {
          /* the ringbuffer is completely full */
          eventsel->begevent = header->def->nevents - MAXNUMEVENT;
          eventsel->endevent = header->def->nevents - 1;
        }
        else {
          /* the ringbuffer is not yet completely full */
          eventsel->begevent = 0;
          eventsel->endevent = header->def->nevents - 1;
        }
      }

      if (verbose>1) print_headerdef(header->def);
      if (verbose>1) print_eventsel(eventsel);

      if (eventsel==NULL) {
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if (eventsel->begevent < 0 || eventsel->endevent < 0) {
        fprintf(stderr, "dmarequest: err1\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if (eventsel->begevent >= header->def->nevents || eventsel->endevent >= header->def->nevents) {
        fprintf(stderr, "dmarequest: err2\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else if ((header->def->nevents-eventsel->begevent) > MAXNUMEVENT) {
        fprintf(stderr, "dmarequest: err3\n");
        response->def->version = VERSION;
        response->def->command = GET_ERR;
        response->def->bufsize = 0;
      }
      else {
        unsigned int j,n;

        response->def->version = VERSION;
        response->def->command = GET_OK;
        response->def->bufsize = 0;

        /* determine the number of events to return */
        n = eventsel->endevent - eventsel->begevent + 1;

        for (j=0; j<n; j++) {
          if (verbose>1) print_eventdef(event[WRAP(eventsel->begevent+j, MAXNUMEVENT)].def);
          response->def->bufsize = append(&response->buf, response->def->bufsize, event[WRAP(eventsel->begevent+j, MAXNUMEVENT)].def, sizeof(eventdef_t));
          response->def->bufsize = append(&response->buf, response->def->bufsize, event[WRAP(eventsel->begevent+j, MAXNUMEVENT)].buf, event[WRAP(eventsel->begevent+j, MAXNUMEVENT)].def->bufsize);
        }
      }

      FREE(eventsel);
      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexheader);
      break;

    case FLUSH_HDR:
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);
      pthread_mutex_lock(&mutexevent);
      if (header) {
        free_header();
        free_data();
        free_event();
        response->def->version = VERSION;
        response->def->command = FLUSH_OK;
        response->def->bufsize = 0;
      }
      else {
        response->def->version = VERSION;
        response->def->command = FLUSH_ERR;
        response->def->bufsize = 0;
      }
      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case FLUSH_DAT:
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexdata);
      if (header && data) {
        header->def->nsamples = thissample = 0;
        response->def->version = VERSION;
        response->def->command = FLUSH_OK;
        response->def->bufsize = 0;
      }
      else {
        response->def->version = VERSION;
        response->def->command = FLUSH_ERR;
        response->def->bufsize = 0;
      }
      pthread_mutex_unlock(&mutexdata);
      pthread_mutex_unlock(&mutexheader);
      break;

    case FLUSH_EVT:
      pthread_mutex_lock(&mutexheader);
      pthread_mutex_lock(&mutexevent);
      if (header && event) {
        unsigned int i;

        header->def->nevents = thisevent = 0;
        for (i=0; i<MAXNUMEVENT; i++) {
          FREE(event[i].def);
          FREE(event[i].buf);
        }
        response->def->version = VERSION;
        response->def->command = FLUSH_OK;
        response->def->bufsize = 0;
      }
      else {
        response->def->version = VERSION;
        response->def->command = FLUSH_ERR;
        response->def->bufsize = 0;
      }
      pthread_mutex_unlock(&mutexevent);
      pthread_mutex_unlock(&mutexheader);
      break;

    case WAIT_DAT:
      /* SK: This request means that the client wants to wait until
         MORE than waitdef_t.threshold.nsamples samples OR 
         MORE THAN waitdef_t.threshold.nevents events 
         are in the buffer, BUT 
         only for the time given in waitdef_t.milliseconds. 
         The response is just the number of samples and events 
         in the buffer as described by samples_events_t.
         */
      response->def->version = VERSION;
      if (header==NULL || request->def->bufsize!=sizeof(waitdef_t)) {
        response->def->command = WAIT_ERR;
        response->def->bufsize = 0;
      } else {
        int waiterr;
        waitdef_t *wd = (waitdef_t *) request->buf;
        samples_events_t *nret = malloc(sizeof(samples_events_t));
        UINT32_T nsmp, nevt;

        if (nret == NULL) {
          /* highly unlikely, but we cannot allocate a sample_event_t - return an error */
          response->def->command = WAIT_ERR;
          response->def->bufsize = 0;
          break;
        }
        /* Let response->buf point to the new sample_event_t structure */
        response->def->command = WAIT_OK;
        response->def->bufsize = sizeof(samples_events_t);
        response->buf = nret;

        /* get current number of samples */
        pthread_mutex_lock(&mutexheader);
        nsmp = header->def->nsamples;
        nevt = header->def->nevents;
        pthread_mutex_unlock(&mutexheader);

        if (wd->milliseconds == 0 || nsmp > wd->threshold.nsamples || nevt > wd->threshold.nevents) {
          /* the client doesn't want to wait, or
             we're already above the threshold: 
             return immediately */
          nret->nsamples = nsmp;
          nret->nevents = nevt;
          break;
        }
        gettimeofday(&tp, NULL);
        ts.tv_sec = tp.tv_sec + (wd->milliseconds/1000);
        ts.tv_nsec = 1000 * (tp.tv_usec + (wd->milliseconds % 1000)*1000);
        while (ts.tv_nsec >= 1000000000) {
          ts.tv_sec++;
          ts.tv_nsec-=1000000000;
        }

        /* FIXME: The getData condition variable is only triggered by incoming data, not events */
        do {
          pthread_mutex_lock(&getData_mutex);
          waiterr = pthread_cond_timedwait(&getData_cond, &getData_mutex, &ts);
          pthread_mutex_unlock(&getData_mutex);

          /* get current number of samples */
          pthread_mutex_lock(&mutexheader);
          nsmp = header->def->nsamples;
          nevt = header->def->nevents;
          pthread_mutex_unlock(&mutexheader);
        } while (nsmp <= wd->threshold.nsamples && nevt <= wd->threshold.nevents && waiterr==0);
        nret->nsamples = nsmp;
        nret->nevents = nevt;				
      }
      break;
    default:
      fprintf(stderr, "dmarequest: unknown command\n");
  }

  if (verbose>0) fprintf(stderr, "dmarequest: thissample = %u, thisevent = %u\n", thissample, thisevent);

  /* everything went fine */
  return 0;
}
Exemplo n.º 28
0
/**
* Initializes all the routers in the network.
*
* Prepares all structures needed for the simulation (routers & all their stuff for
* requesting, arbitring & stating). Event queues & occurred list are initilized here
* if compiled with the TRACE_SUPPORT != 0 .
*/
void router_init(void) {
    long i, j;

    network = alloc(sizeof(router) * NUMNODES);

    for(i = 0; i < NUMNODES; ++i) {

        // In topologies with NICs, these must be initialized with only one transit queue.
        // or define a data structure similar to the router for them.
        if (i<nprocs) { // Injection queues only in processors
            network[i].qi = alloc(sizeof(inj_queue) * ninj);
            for (j=0; j<ninj; j++)
                network[i].qi[j].pos = alloc(sizeof(phit) * inj_ql);
        }
        else {
            network[i].qi=NULL;
            network[i].source=NO_SOURCE;
        }

        network[i].p = alloc(sizeof(port) * (n_ports+1));
        for(j = 0; j < n_ports+1; ++j) {
            network[i].p[j].req = alloc(sizeof(CLOCK_TYPE) * n_ports+1);
            network[i].p[j].histo = alloc(sizeof(CLOCK_TYPE) * (buffer_cap + 1));
            network[i].p[j].faulty = 0;
        }

        network[i].op_i = alloc(sizeof(long) * radix);
        network[i].nbor = alloc(sizeof(long) * radix);
        network[i].nborp = alloc(sizeof(long) * radix);

        if (topo<DIRECT)
            coords(i, &network[i].rcoord[D_X], &network[i].rcoord[D_Y], &network[i].rcoord[D_Z]);
        else if (topo==ICUBE)
            coords_icube(i, &network[i].rcoord[D_X], &network[i].rcoord[D_Y], &network[i].rcoord[D_Z]);
        // Tree coordinates will be written when the topology is created.

        network[i].injecting_port = NULL_PORT;
        network[i].next_port = 0;
#if (PCOUNT!=0)
        network[i].pcount = 0;
#endif
        // Congestion with timeouts.
        network[i].timeout_counter = (CLOCK_TYPE) 0L;
        network[i].timeout_packet = NULL_PACKET;
        network[i].congested = FALSE;

        network[i].triggered=0;

#if (TRACE_SUPPORT == 1)
        if (i<nprocs) {
            init_event(&network[i].events);
            init_occur(&network[i].occurs);
        }
        else
            network[i].source=NO_SOURCE;
#endif

#if (TRACE_SUPPORT > 1)
        if (i<nprocs) {
            init_event(&network[i].events);
            network[i].occurs = alloc(sizeof(event_l) * nprocs);
            init_occur(&network[i].occurs);
        }
        else
            network[i].source=NO_SOURCE;
#endif
    }

    p_con = n_ports - 1;
    p_drop = n_ports;   // For transit dropping
    p_inj_first = radix*nchan;
    p_inj_last = n_ports - 2;

    if (topo<DIRECT) {
        port_coord_dim = alloc(sizeof(dim) * p_inj_first);
        port_coord_way = alloc(sizeof(way) * p_inj_first);
        port_coord_channel = alloc(sizeof(channel) * p_inj_first);
        for (j = 0; j < p_inj_first; j++)
            port_coords(j, &port_coord_dim[j], &port_coord_way[j], &port_coord_channel[j]);
    }

    if (topo==ICUBE) {
        port_coord_dim = alloc(sizeof(dim) * p_inj_first);
        port_coord_way = alloc(sizeof(way) * p_inj_first);
        port_coord_channel = alloc(sizeof(channel) * p_inj_first);
        for (j = 0; j < p_inj_first; j++) {
            port_type a1 = ( j - (nodes_per_switch*nchan) ) / (links_per_direction);
            port_coord_dim[j] = a1 / ( nways * nchan );
            a1 = a1 % ( nways * nchan );
            port_coord_way[j] = a1 / nchan;
            port_coord_channel[j] = a1 % nchan;
        }
    }

    if (shotmode)
        for (i=0; i<nprocs; i++)
            network[i].source=OTHER_SOURCE; // Bursty Source

    /* Allocates space for transit queues */
    for(i = 0; i < NUMNODES; ++i)
        for(j = 0; j < n_ports+1; ++j)
            network[i].p[j].q.pos = alloc(sizeof(phit) * tr_ql);
}