コード例 #1
0
ファイル: pgpug-ui-utils.c プロジェクト: nikmikov/pgpug
static GdkPixbufAnimation*		
pgpug_animated_icon_compose_real	(PgpugPixEnum icon_id, 
					 gint size,
					 va_list var_args)
{

     GdkPixbufAnimation *base_anim = pgpug_animated_icon (icon_id, size);
     g_return_val_if_fail (base_anim != NULL, NULL);


     GPtrArray *anim_array = g_ptr_array_new (); 
     animation_param_entry* p_entry = g_malloc0 (sizeof (animation_param_entry));
     p_entry->anim = pgpug_animated_icon (icon_id, size);
     g_ptr_array_add (anim_array, p_entry);


     gint size_v, pos_v, icon_id_v, param_num; 
     icon_id_v = va_arg (var_args, gint);
     param_num = 0;
     while (icon_id_v >=0) {
	  size_v = va_arg (var_args, gint);
	  pos_v = va_arg (var_args, gint);
	  
	  if (size_v <= 0 ){
	       //incorrect icon size
	       WARN_MSG ("pgpug_animated_icon_compose: var_arg parameter %d expected param correct icon size, got %d value", param_num + 1, size_v);
	       break;
	  }

	  if (pos_v < 0){
	       WARN_MSG ("pgpug_animated_icon_compose: var_arg parameter %d expected param from PgpugPixComposePosEnum, got %d value", param_num + 2, pos_v);
	       //incorrect icon size
	       break;
	  }
	  param_num+=3;
	  p_entry = g_malloc0 (sizeof (animation_param_entry));
	  p_entry->anim = pgpug_animated_icon (icon_id_v, size_v);
	  p_entry->pos = pos_v;
	  g_ptr_array_add (anim_array, p_entry);
	  icon_id_v = va_arg (var_args, gint);

     }

     GdkPixbufAnimation *result;
     result = compose_animation_from_array ((animation_param_entry**)anim_array->pdata, anim_array->len, size);

     guint i;
     for (i=0;i<anim_array->len;i++)
	  g_object_unref ( ((animation_param_entry*)anim_array->pdata[i])->anim);

     g_ptr_array_foreach (anim_array, (GFunc)g_free, NULL);
     g_ptr_array_free (anim_array, TRUE);
     return result;

}
コード例 #2
0
BOOL OpenContext::SetAltSetting(LPUKWD_SET_ALTSETTING_INFO lpSetAltSettingInfo)
{
	MutexLocker lock(mMutex);
	DevicePtr dev (mDevice->GetDeviceList(), lpSetAltSettingInfo->lpDevice);
	if (!Validate(dev)) {
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	// Interface can't be used if device has closed
	if (dev->Closed()) {
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	if (!dev->InterfaceClaimed(lpSetAltSettingInfo->dwInterface, this)) {
		WARN_MSG((TEXT("USBKWrapperDrv!OpenContext::SetAltSetting() - ")
			TEXT("using interface %d on device 0x%08x without claiming\r\n"),
			lpSetAltSettingInfo->dwInterface, lpSetAltSettingInfo->lpDevice));
		if (!dev->ClaimInterface(lpSetAltSettingInfo->dwInterface, this)) {
			return FALSE;
		}
	}
	return dev->SetAltSetting(lpSetAltSettingInfo->dwInterface,
						lpSetAltSettingInfo->dwAlternateSetting);
}
コード例 #3
0
void ctrl_exception_done(void* desc, void* cpu, integer_t val)
{
  int proc_no = SIM_get_proc_no((conf_object_t*) cpu);
  conf_object_t* cpu_obj = (conf_object_t*) cpu;
  uinteger_t trap_level = SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tl")); 
  uinteger_t pc = SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "pc"));
  uinteger_t npc = SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "npc"));
  uinteger_t tpc = 0;
  uinteger_t tnpc = 0;
  //get the return PC,NPC pair based on the trap level
  ASSERT(1 <= trap_level && trap_level <= 5);
  if(trap_level == 1){
    tpc =  SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tpc1"));
    tnpc = SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tnpc1"));
  }
  if(trap_level == 2){
    tpc =  SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tpc2"));
    tnpc = SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tnpc2"));
  }
  if(trap_level == 3){
    tpc =  SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tpc3"));
    tnpc = SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tnpc3"));
  }
  if(trap_level == 4){
    tpc =  SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tpc4"));
    tnpc = SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tnpc4"));
  }
  if(trap_level == 5){
    tpc =  SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tpc5"));
    tnpc = SIM_read_register(cpu_obj, SIM_get_register_number(cpu_obj, "tnpc5"));
  }
  
  if (!XACT_MEMORY) return;
  TransactionInterfaceManager *xact_mgr = XACT_MGR;

  int smt_thread_num = proc_no % RubyConfig::numberofSMTThreads();
  // The simulated processor number
  int sim_proc_no = proc_no / RubyConfig::numberofSMTThreads();

  if (proc_no != SIMICS_current_processor_number()){
    WARN_EXPR(proc_no);
    WARN_EXPR(SIMICS_current_processor_number());
    WARN_MSG("Callback for a different processor");
  }  

  g_system_ptr->getProfiler()->profileExceptionDone(xact_mgr->getTransactionLevel(smt_thread_num) > 0, sim_proc_no, smt_thread_num, val, trap_level, pc, npc, tpc, tnpc);

  if((val >= 0x80 && val <= 0x9f) || (val >= 0xc0 && val <= 0xdf)){
    //xact_mgr->clearLoggedException(smt_thread_num);
  }

  if ((val == 0x122) && xact_mgr->shouldTrap(smt_thread_num)){
    // use software handler
    if (xact_mgr->shouldUseHardwareAbort(smt_thread_num)){
        xact_mgr->hardwareAbort(smt_thread_num);
    } else {          
      xact_mgr->trapToHandler(smt_thread_num);
    }  
  }
}
コード例 #4
0
ファイル: OpenContext.cpp プロジェクト: dsdwew/CEUSBKWrapper
BOOL OpenContext::IsPipeHalted(LPUKWD_ENDPOINT_INFO lpEndpointInfo, LPBOOL halted)
{
	MutexLocker lock(mMutex);
	DevicePtr dev (mDevice->GetDeviceList(), lpEndpointInfo->lpDevice);
	if (!Validate(dev) || halted == NULL) {
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	// Find the interface for this device
	DWORD dwInterface = -1;
	if (lpEndpointInfo->Endpoint != 0) {
		if (!dev->FindInterface(lpEndpointInfo->Endpoint, dwInterface)) {
			ERROR_MSG((TEXT("USBKWrapperDrv!OpenContext::IsPipeHalted() - ")
				TEXT("failed to find interface for endpoint %d on device 0x%08x\r\n"),
				lpEndpointInfo->Endpoint, lpEndpointInfo->lpDevice));
			SetLastError(ERROR_INVALID_PARAMETER);
			return FALSE;
		}

		// See if it's already been claimed
		if (!dev->InterfaceClaimed(dwInterface, this)) {
			WARN_MSG((TEXT("USBKWrapperDrv!OpenContext::IsPipeHalted() - ")
				TEXT("using interface %d on device 0x%08x without claiming\r\n"),
				dwInterface, lpEndpointInfo->lpDevice));
			if (!dev->ClaimInterface(dwInterface, this)) {
				return FALSE;
			}
		}
	}

	return dev->IsEndpointHalted(dwInterface, lpEndpointInfo->Endpoint, *halted);
}
コード例 #5
0
ファイル: UsbDevice.cpp プロジェクト: dsdwew/CEUSBKWrapper
extern "C" BOOL UsbDeviceNotifyRoutine(
	LPVOID lpvNotifyParameter,
	DWORD dwCode,
	LPDWORD* dwInfo1,
	LPDWORD* dwInfo2,
	LPDWORD* dwInfo3,
	LPDWORD* dwInfo4
	)
{
	UsbDevice* dev = static_cast<UsbDevice*>(lpvNotifyParameter);
	switch (dwCode) {
#if _WIN32_WCE >= 0x700
		case USB_RESUMED_DEVICE:
		case USB_SUSPENDED_DEVICE:
			return FALSE;
#endif
		case USB_CLOSE_DEVICE:
		{
			dev->Close();
			UsbDeviceList* list = UsbDeviceList::Get();
			if (list && dev) {
				list->PutDevice(dev);
			}
			return TRUE;
		}
		default:
			WARN_MSG((TEXT("USBKWrapperDrv!UsbDeviceNotifyRoutine")
				TEXT(" received unknown code %d for dev 0x%08x\r\n"),
				dwCode, dev));
			return FALSE;
	}
	return FALSE;
}
コード例 #6
0
BOOL OpenContext::StartBulkTransfer(LPUKWD_BULK_TRANSFER_INFO lpTransferInfo)
{
	MutexLocker lock(mMutex);
	DevicePtr dev (mDevice->GetDeviceList(), lpTransferInfo->lpDevice);
	if (!Validate(dev)) {
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	// Interface can't be used if device has closed
	if (dev->Closed()) {
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	// Find the interface for this transfer
	DWORD dwInterface;
	if (!dev->FindInterface(lpTransferInfo->Endpoint, dwInterface)) {
		ERROR_MSG((TEXT("USBKWrapperDrv!OpenContext::StartBulkTransfer() - ")
			TEXT("failed to find interface for endpoint %d on device 0x%08x\r\n"),
			lpTransferInfo->Endpoint, lpTransferInfo->lpDevice));
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	// See if it's already been claimed
	if (!dev->InterfaceClaimed(dwInterface, this)) {
		WARN_MSG((TEXT("USBKWrapperDrv!OpenContext::StartBulkTransfer() - ")
			TEXT("using interface %d on device 0x%08x without claiming\r\n"),
			dwInterface, lpTransferInfo->lpDevice));
		if (!dev->ClaimInterface(dwInterface, this)) {
			return FALSE;
		}
	}

	TRANSFERLIFETIME_MSG((TEXT("USBKWrapperDrv!OpenContext::StartBulkTransfer() on ep %x, flag 0x%08x and size %d\r\n"),
		lpTransferInfo->Endpoint, lpTransferInfo->dwFlags, lpTransferInfo->dwDataBufferSize));

	// Construct and start the bulk transfer
	BulkTransfer* bt = new (std::nothrow) BulkTransfer(
			this, dev, dwInterface, lpTransferInfo);
	if (!bt) {
		ERROR_MSG((TEXT("USBKWrapperDrv!OpenContext::StartBulkTransfer() - failed to create bulk transfer, aborting\r\n")));
		SetLastError(ERROR_NOT_ENOUGH_MEMORY);
		return FALSE;
	}
	BOOL ret = bt->Start();
	mTransferList->PutTransfer(bt);
	bt = NULL;
	if (!ret) {
		ERROR_MSG((TEXT("USBKWrapperDrv!OpenContext::StartBulkTransfer() - failed to start bulk transfer %d\r\n"), GetLastError()));
		return FALSE;
	}
	// Ownership of ct has passed to the transfer callback
	return TRUE;
}
コード例 #7
0
ファイル: diff_test_func.c プロジェクト: leobago/fti
bool valid( dcp_info_t * info ) {
    unsigned char hash[MD5_DIGEST_LENGTH];
    bool success = true;
    int idx;
    for( idx=0; idx<info->nbuffer; ++idx ){
        MD5( info->buffer[idx], info->size[idx], hash );
        if ( memcmp( hash, info->hash[idx], MD5_DIGEST_LENGTH ) != 0 ) {
            WARN_MSG("hashes for buffer id %d differ", idx);
            success = false;
        }
    }
}
コード例 #8
0
ファイル: ir-a2xx.c プロジェクト: John-Gee/Mesa-3D
/* resolve addr/cnt/sequence fields in the individual CF's */
static int shader_resolve(struct ir2_shader *shader, struct ir2_shader_info *info)
{
	uint32_t addr;
	unsigned i;
	int j;

	addr = shader->cfs_count / 2;
	for (i = 0; i < shader->cfs_count; i++) {
		struct ir2_cf *cf = shader->cfs[i];
		if ((cf->cf_type == EXEC) || (cf->cf_type == EXEC_END)) {
			uint32_t sequence = 0;

			if (cf->exec.addr && (cf->exec.addr != addr))
				WARN_MSG("invalid addr '%d' at CF %d", cf->exec.addr, i);
			if (cf->exec.cnt && (cf->exec.cnt != cf->exec.instrs_count))
				WARN_MSG("invalid cnt '%d' at CF %d", cf->exec.cnt, i);

			for (j = cf->exec.instrs_count - 1; j >= 0; j--) {
				struct ir2_instruction *instr = cf->exec.instrs[j];
				sequence <<= 2;
				if (instr->instr_type == IR2_FETCH)
					sequence |= 0x1;
				if (instr->sync)
					sequence |= 0x2;
			}

			cf->exec.addr = addr;
			cf->exec.cnt  = cf->exec.instrs_count;
			cf->exec.sequence = sequence;

			addr += cf->exec.instrs_count;
		}
	}

	info->sizedwords = 3 * addr;

	return 0;
}
コード例 #9
0
ファイル: OpenContext.cpp プロジェクト: dsdwew/CEUSBKWrapper
// Checks that device is valid and is open
// by this context.
BOOL OpenContext::Validate(DevicePtr& device)
{
	if (!device.Valid())
		return FALSE;
	PtrArray<UsbDevice>::iterator it
		= mOpenDevices.find(device.Get());
	if (it == mOpenDevices.end()) {
	    WARN_MSG((TEXT("USBKWrapperDrv!OpenContext::Validate")
			TEXT(" - failed to find device in this context for identifier 0x%08x\r\n"),
			device->GetIdentifier()));
		return FALSE;
	} 
	return TRUE;
}
コード例 #10
0
UsbDevice* UsbDeviceList::GetDevice(UKWD_USB_DEVICE identifier)
{
	MutexLocker lock(mMutex);
	PtrArray<UsbDevice>::iterator it
		= mDevices.find(static_cast<UsbDevice*>(identifier));
	if (it == mDevices.end()) {
	    WARN_MSG((TEXT("USBKWrapperDrv!UsbDeviceList::GetDevice")
			TEXT(" - failed to find device for identifier 0x%08x\r\n"), identifier));
		return NULL;
	} else {
		(*it)->IncRef();
	}
	return *it;
}
コード例 #11
0
ファイル: pgpug-ui-utils.c プロジェクト: nikmikov/pgpug
GdkPixbufAnimation*	
pgpug_animated_icon_compose_from_anim_list (GdkPixbufAnimation * anim,
					    ...)
{
     g_return_val_if_fail (anim != NULL, NULL);
     g_return_val_if_fail (GDK_IS_PIXBUF_ANIMATION (anim), NULL);

     int width, height;
     width = gdk_pixbuf_animation_get_width (anim);
     height = gdk_pixbuf_animation_get_height (anim);
     g_return_val_if_fail (height == width, NULL);

     va_list anim_p;
     va_start (anim_p, anim);
     //get all animation into an array
     GPtrArray *anim_array = g_ptr_array_new (); 
     animation_param_entry* p_entry = g_malloc0 (sizeof (animation_param_entry));
     p_entry->anim = anim;
     g_ptr_array_add (anim_array, p_entry);
     
     gint anim_pos, param_num = 0;
     anim_pos = va_arg (anim_p, gint);

     while (anim_pos >= 0){
	  gpointer ptr = va_arg (anim_p, gpointer);
	  p_entry = g_malloc (sizeof (animation_param_entry));
	  param_num += 2;
	  if (!GDK_IS_PIXBUF_ANIMATION (ptr)) {
	       WARN_MSG ("pgpug_animated_icon_compose_from_anim_list: var_arg parameter %d expected GdkPixbufAnimation*", param_num);
	       break;
	  }

	  p_entry->anim = GDK_PIXBUF_ANIMATION (ptr);
	  p_entry->pos = anim_pos;

	  g_ptr_array_add (anim_array, p_entry);
	  anim_pos = va_arg (anim_p, gint);
     }
     va_end (anim_p);     

     GdkPixbufAnimation *result;
     result = compose_animation_from_array ((animation_param_entry**)anim_array->pdata, anim_array->len, width);

     g_ptr_array_foreach (anim_array, (GFunc)g_free, NULL);
     g_ptr_array_free (anim_array, TRUE);
     return result;
}
コード例 #12
0
ファイル: ec_linux.c プロジェクト: Ettercap/ettercap
/*
 * disable segmentation offload on interface
 * this prevents L3 send errors (payload too large)
 */
void disable_interface_offload(void)
{
	int param_length= 0;
	char *command;
	char **param = NULL;
	char *p;
	int ret_val, i = 0;

	SAFE_CALLOC(command, 100, sizeof(char));

	BUG_IF(command==NULL);

	memset(command, '\0', 100);	
	snprintf(command, 99, "ethtool -K %s tso off gso off gro off lro off", EC_GBL_OPTIONS->iface);

	DEBUG_MSG("disable_interface_offload: Disabling offload on %s", EC_GBL_OPTIONS->iface);

	for(p = strsep(&command, " "); p != NULL; p = strsep(&command, " ")) {
		SAFE_REALLOC(param, (i+1) * sizeof(char *));
		param[i++] = strdup(p);	
	}

	SAFE_REALLOC(param, (i+1) * sizeof(char *));
	param[i] = NULL;
	param_length= i + 1; //because there is a SAFE_REALLOC after the for.

	switch(fork()) {
		case 0:
#ifndef DEBUG
			/* don't print on console if the ethtool cannot disable some offloads unless you are in debug mode */
			close(2);
#endif
			execvp(param[0], param);
			WARN_MSG("cannot disable offload on %s, do you have ethtool installed?", EC_GBL_OPTIONS->iface);
			safe_free_mem(param, &param_length, command);
			_exit(-E_INVALID);
		case -1:
			safe_free_mem(param, &param_length, command);
         break;
		default:
			safe_free_mem(param, &param_length, command);
			wait(&ret_val);
	} 	
}
コード例 #13
0
ファイル: OpenContext.cpp プロジェクト: dsdwew/CEUSBKWrapper
OpenContext::~OpenContext()
{
	if (mMutex)
		CloseHandle(mMutex);

	delete mTransferList;

	// Release any leaked devices
	DWORD count = 0;
	PtrArray<UsbDevice>::iterator it = mOpenDevices.begin();
	while(it != mOpenDevices.end()) {
		(*it)->ReleaseAllInterfaces(this);
		mDevice->GetDeviceList()->PutDevice(*it);
		++count;
		++it;
	}
	if (count > 0) {
		WARN_MSG((TEXT("USBKWrapperDrv!OpenContext::~OpenContext() - detected %d leaked devices\r\n"), count));
	}
}
コード例 #14
0
ファイル: pgpug-window.c プロジェクト: nikmikov/pgpug
gint
pgpug_window_deinstall_pane (PgpugWindow *self, 
			     PgpugPane *tab,
			     PgpugPaneLocation location)
{
     g_return_if_fail (PGPUG_IS_WINDOW (self));
     g_return_if_fail (PGPUG_IS_PANE (tab));

     GtkWidget *view = pgpug_pane_get_view (tab);
     GtkWidget *parent = gtk_widget_get_parent (view); 

     PgpugPane *pgpug_pane = g_hash_table_lookup (self->priv->view_pane_map, view);

     if (parent != NULL) {
	  gtk_container_remove (GTK_CONTAINER (parent), view);
     }else {
	  WARN_MSG ("PgpugWindow: deinstall pane: pane is not installed");
     }
     
     g_hash_table_remove (self->priv->view_pane_map, view);
}
コード例 #15
0
ファイル: pgpug-window.c プロジェクト: nikmikov/pgpug
gint
pgpug_window_install_pane (PgpugWindow *self, 
			   PgpugPane *tab,
			   PgpugPaneLocation location)
{
     g_return_if_fail (PGPUG_IS_WINDOW (self));
     g_return_if_fail (PGPUG_IS_PANE (tab));

     GtkWidget *view = pgpug_pane_get_view (tab);
     const gchar* label_text = pgpug_pane_get_label_text (tab);
  
     g_hash_table_insert (self->priv->view_pane_map, view, tab);

     gint reslt = -1;     
     switch (location) {
     case PGPUG_PANE_BROWSER:
	  reslt = folding_tab_pane_append_page (FOLDING_TAB_PANE (self->priv->browser_pane), 
						view, gtk_label_new (label_text));
	  break;
     case PGPUG_PANE_CONTENT:
	  reslt = pgpug_content_pane_append_page (self->priv->content_pane, tab, 0);
	  break;
     case PGPUG_PANE_DETAIL:
	  reslt = folding_tab_pane_append_page (FOLDING_TAB_PANE (self->priv->detail_pane), 
						view, gtk_label_new (label_text));

	  break;
     default:
	  WARN_MSG("PgpugWindow: install pane: invalid location specified.");
     }

     if (reslt >= 0) {
	  pgpug_window_install_pane_data (self, tab, location);	  
     }else {
	  g_hash_table_remove (self->priv->view_pane_map, view);
     }

     return reslt;
}
コード例 #16
0
BOOL OpenContext::ClearHaltDevice(LPUKWD_ENDPOINT_INFO lpEndpointInfo)
{
	MutexLocker lock(mMutex);
	DevicePtr dev (mDevice->GetDeviceList(), lpEndpointInfo->lpDevice);
	if (!Validate(dev)) {
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	// Interface can't be used if device has closed
	if (dev->Closed()) {
		SetLastError(ERROR_INVALID_HANDLE);
		return FALSE;
	}

	// Find the interface for this device
	DWORD dwInterface;
	if (!dev->FindInterface(lpEndpointInfo->Endpoint, dwInterface)) {
		ERROR_MSG((TEXT("USBKWrapperDrv!OpenContext::ClearHalt() - ")
			TEXT("failed to find interface for endpoint %d on device 0x%08x\r\n"),
			lpEndpointInfo->Endpoint, lpEndpointInfo->lpDevice));
		SetLastError(ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	// See if it's already been claimed
	if (!dev->InterfaceClaimed(dwInterface, this)) {
		WARN_MSG((TEXT("USBKWrapperDrv!OpenContext::ClearHalt() - ")
			TEXT("using interface %d on device 0x%08x without claiming\r\n"),
			dwInterface, lpEndpointInfo->lpDevice));
		if (!dev->ClaimInterface(dwInterface, this)) {
			return FALSE;
		}
	}

	return dev->ClearHaltDevice(dwInterface, lpEndpointInfo->Endpoint);
}
コード例 #17
0
ファイル: pgpug-window.c プロジェクト: nikmikov/pgpug
void 
pgpug_window_set_pane_permanent (PgpugWindow *self,
				 PgpugPane *tab)
{
     g_return_if_fail (PGPUG_IS_WINDOW (self));
     g_return_if_fail (PGPUG_IS_PANE (tab));

     /* check if the pane already set as permanent */
     gint elem_index = g_list_index (self->priv->permanent_panes, tab);
     if (elem_index>=0){
	  WARN_MSG ("PgpugWindow: pane %s is already set as permanent",
		    pgpug_pane_get_menu_text (tab));
	  return;
     }

     /* Increase references count to preserve pane 
	from destroying when removed from container*/
     g_object_ref (tab);

     self->priv->permanent_panes = g_list_append (self->priv->permanent_panes, tab);

     /* rebuild the View menu */
     pgpug_window_rebuild_view_menu (self);
}
コード例 #18
0
ファイル: diff_test_func.c プロジェクト: leobago/fti
void init( dcp_info_t * info, unsigned long alloc_size ) {

    int wsize;
    MPI_Comm_size(MPI_COMM_WORLD, &wsize);
    MPI_Comm_rank(MPI_COMM_WORLD, &grank);
    
    dictionary* ini;

    if (access("config.fti", R_OK) == 0) {
        ini = iniparser_load("config.fti");
        if (ini == NULL) {
            WARN_MSG("failed to parse FTI config file!");
            exit(EXIT_FAILURE);
        }
    } else {
        EXIT_STD_ERR("cannot access FTI config file!");
    }

    finalTag = (int)iniparser_getint(ini, "Advanced:final_tag", 3107);
    numHeads = (int)iniparser_getint(ini, "Basic:head", 0);
    int nodeSize = (int)iniparser_getint(ini, "Basic:node_size", -1);

    headRank = grank - grank%nodeSize;

    char* env = getenv( "TEST_MODE" );
    if( env ) {
        if( strcmp( env, "ICP" ) == 0 ) {
            info->test_mode = TEST_ICP;
            INFO_MSG("TEST MODE -> ICP");
        } else if ( strcmp( env, "NOICP") == 0 ) {
            info->test_mode = TEST_NOICP;
            INFO_MSG("TEST MODE -> NOICP");
        } else {
            info->test_mode = TEST_NOICP;
            INFO_MSG("TEST MODE -> NOICP");
        }
    } else {
        info->test_mode = TEST_NOICP;
        INFO_MSG("TEST MODE -> NOICP");
    }

    //DBG_MSG("alloc_size: %lu",0,alloc_size);
    init_share();
    
    // init pattern
    pat = (uint32_t) rand();
    
    // protect pattern and xor_info
    FTI_InitType( &FTI_UI, UI_UNIT ); 
    FTI_Protect( PAT_ID, &pat, 1, FTI_UI );  
    FTI_InitType( &FTI_XOR_INFO, sizeof(xor_info_t) ); 
    FTI_Protect( XOR_INFO_ID, info->xor_info, NUM_DCKPT, FTI_XOR_INFO );  
    FTI_Protect( NBUFFER_ID, &info->nbuffer,  1, FTI_INTG );  

    // check if alloc_size is sufficiant large
    if ( alloc_size < 101 ) EXIT_CFG_ERR("insufficiant allocation size"); 
    
    // determine number of buffers
    usleep(5000*grank);
    srand(get_seed());
    if ( FTI_Status() == 0 ) {
        info->nbuffer = rand()%10+1;
    } else {
        FTI_RecoverVar( NBUFFER_ID );
    }

    // initialize structure
    info->buffer = (void**) malloc(info->nbuffer*sizeof(void*));
    info->size = (unsigned long*) malloc(info->nbuffer*sizeof(unsigned long));
    info->oldsize = (unsigned long*) malloc(info->nbuffer*sizeof(unsigned long));
    info->hash = (unsigned char**) malloc(info->nbuffer*sizeof(unsigned char*));
    int idx;
    for ( idx=0; idx<info->nbuffer; ++idx ) {
        info->buffer[idx] = NULL;
        info->hash[idx] = (unsigned char*) malloc(MD5_DIGEST_LENGTH);
    }
    allocate_buffers( info, alloc_size );
    generate_data( info );
    init_srand();
}
コード例 #19
0
ファイル: pgpug-ui-utils.c プロジェクト: nikmikov/pgpug
GdkPixbufAnimation*	
pgpug_animated_icon (PgpugPixEnum icon_id,
		     gint size)
{
     g_return_val_if_fail (icon_id < PIX_NUMBER, NULL);
     GdkPixbufSimpleAnim *result = NULL;
     PgpugPixEntry entry =  icon_entries_array [icon_id];

     /* assert that ids are in order */
     g_return_val_if_fail (entry.id == icon_id, NULL);

     GPtrArray *frames_array = g_ptr_array_new ();
     GtkIconTheme* theme;
     GdkPixbuf *pixbuf;
     GError *error = NULL, *error_anim = NULL;


     theme = gtk_icon_theme_get_default ();
     pixbuf = gtk_icon_theme_load_icon (theme, entry.name, size, 
					GTK_ICON_LOOKUP_FORCE_SIZE, &error);
     if (error == NULL && pixbuf != NULL) {
	  DEBG_MSG ("Loaded icon with name %s", entry.name);
	  //it's a static image
	  g_ptr_array_add (frames_array, (gpointer)pixbuf);
     }else{ 
	  //else try to get frame sequence
	  gchar *name_template = g_strconcat (entry.name, "%02d", NULL);
	  int i = 1;
	  do {
	       gchar *name = g_strdup_printf (name_template, i++);
	  
	       pixbuf = gtk_icon_theme_load_icon (theme, name, size, 
						  GTK_ICON_LOOKUP_FORCE_SIZE, &error_anim);
	       if (pixbuf != NULL){
		    DEBG_MSG ("Loaded animation frame with name %s, address %p", name, pixbuf);
		    g_ptr_array_add (frames_array, (gpointer)pixbuf);
	       }
	       g_free (name);
	  } while (error_anim == NULL && i < 100);

	  g_free (name_template);
     }

  
     if (frames_array->len != 0){
	  //construct animation
	  result = gdk_pixbuf_simple_anim_new (size, size, frames_array->len);
	  guint i;
	  for (i = 0;i < frames_array->len; i++)
	       gdk_pixbuf_simple_anim_add_frame (result, frames_array->pdata[i]);	       

     } else{
	  //we didn't find any images 
	  gchar **search_paths;
	  gint index;
	  gchar *search_path_str;
	  gtk_icon_theme_get_search_path (theme, &search_paths, &index);

	  search_path_str = g_strjoinv ("\n", search_paths);

	  WARN_MSG ("Icon with name \"%s\" can not be loaded.\n"
		   "Icon search paths are: \n%s\n"
		   "Error message: %s",
		   entry.name,
		   search_path_str, 
		   error->message);
	  g_strfreev (search_paths);
	  g_free (search_path_str);
     }

     g_ptr_array_foreach (frames_array, (GFunc)g_object_unref, NULL);
     g_ptr_array_free (frames_array, TRUE);
     if (error != NULL)	  	  g_error_free (error);
     if (error_anim != NULL)	  g_error_free (error_anim);

     return GDK_PIXBUF_ANIMATION (result);
}
コード例 #20
0
ファイル: config.c プロジェクト: kleopatra999/calcurse-1
static void
config_file_walk(config_fn_walk_cb_t fn_cb,
		 config_fn_walk_junk_cb_t fn_junk_cb, void *data)
{
	FILE *data_file;
	char buf[BUFSIZ], e_conf[BUFSIZ];
	char *key, *value;

	data_file = fopen(path_conf, "r");
	EXIT_IF(data_file == NULL, _("failed to open configuration file"));

	pthread_mutex_lock(&nbar.mutex);
	for (;;) {
		if (fgets(buf, sizeof buf, data_file) == NULL)
			break;
		io_extract_data(e_conf, buf, sizeof buf);

		if (*e_conf == '\0' || *e_conf == '#') {
			if (fn_junk_cb)
				fn_junk_cb(buf, data);
			continue;
		}

		key = e_conf;
		value = strchr(e_conf, '=');
		if (value) {
			*value = '\0';
			value++;
		} else {
			EXIT(_("invalid configuration directive: \"%s\""),
			     e_conf);
		}

		if (strcmp(key, "auto_save") == 0 ||
		    strcmp(key, "auto_gc") == 0 ||
		    strcmp(key, "periodic_save") == 0 ||
		    strcmp(key, "confirm_quit") == 0 ||
		    strcmp(key, "confirm_delete") == 0 ||
		    strcmp(key, "skip_system_dialogs") == 0 ||
		    strcmp(key, "skip_progress_bar") == 0 ||
		    strcmp(key, "calendar_default_view") == 0 ||
		    strcmp(key, "week_begins_on_monday") == 0 ||
		    strcmp(key, "color-theme") == 0 ||
		    strcmp(key, "layout") == 0 ||
		    strcmp(key, "side-bar_width") == 0 ||
		    strcmp(key, "notify-bar_show") == 0 ||
		    strcmp(key, "notify-bar_date") == 0 ||
		    strcmp(key, "notify-bar_clock") == 0 ||
		    strcmp(key, "notify-bar_warning") == 0 ||
		    strcmp(key, "notify-bar_command") == 0 ||
		    strcmp(key, "notify-all") == 0 ||
		    strcmp(key, "output_datefmt") == 0 ||
		    strcmp(key, "input_datefmt") == 0 ||
		    strcmp(key, "notify-daemon_enable") == 0 ||
		    strcmp(key, "notify-daemon_log") == 0) {
			WARN_MSG(_("Pre-3.0.0 configuration file format detected, "
				  "please upgrade running `calcurse-upgrade`."));
		}

		if (value && (*value == '\0' || *value == '\n')) {
			/* Backward compatibility mode. */
			if (fgets(buf, sizeof buf, data_file) == NULL)
				break;
			io_extract_data(e_conf, buf, sizeof buf);
			if (*e_conf == '#')
				*e_conf = '\0';
			value = e_conf;
		}

		fn_cb(key, value, data);
	}
	file_close(data_file, __FILE_POS__);
	pthread_mutex_unlock(&nbar.mutex);
}
コード例 #21
0
ファイル: mist_in.cpp プロジェクト: DDVTECH/mistserver
int main(int argc, char * argv[]) {
    Util::Config conf(argv[0]);
    mistIn conv(&conf);
    if (conf.parseArgs(argc, argv)) {
        std::string streamName = conf.getString("streamname");
        conv.argumentsParsed();

        IPC::semaphore playerLock;
        if (conv.needsLock()) {
            if (streamName.size()) {
                char semName[NAME_BUFFER_SIZE];
                snprintf(semName, NAME_BUFFER_SIZE, SEM_INPUT, streamName.c_str());
                playerLock.open(semName, O_CREAT | O_RDWR, ACCESSPERMS, 1);
                if (!playerLock.tryWait()) {
                    DEBUG_MSG(DLVL_DEVEL, "A player for stream %s is already running", streamName.c_str());
                    return 1;
                }
            }
        }
        conf.activate();
        uint64_t reTimer = 0;
        while (conf.is_active) {
            pid_t pid = fork();
            if (pid == 0) {
                if (conv.needsLock()) {
                    playerLock.close();
                }
                return conv.run();
            }
            if (pid == -1) {
                DEBUG_MSG(DLVL_FAIL, "Unable to spawn player process");
                if (conv.needsLock()) {
                    playerLock.post();
                }
                return 2;
            }
            //wait for the process to exit
            int status;
            while (waitpid(pid, &status, 0) != pid && errno == EINTR) {
                if (!conf.is_active) {
                    DEBUG_MSG(DLVL_DEVEL, "Shutting down input for stream %s because of signal interrupt...", streamName.c_str());
                    Util::Procs::Stop(pid);
                }
                continue;
            }
            //if the exit was clean, don't restart it
            if (WIFEXITED(status) && (WEXITSTATUS(status) == 0)) {
                DEBUG_MSG(DLVL_MEDIUM, "Input for stream %s shut down cleanly", streamName.c_str());
                break;
            }
#if DEBUG >= DLVL_DEVEL
            WARN_MSG("Aborting autoclean; this is a development build.");
#else
            conv.onCrash();
#endif
            if (DEBUG >= DLVL_DEVEL) {
                DEBUG_MSG(DLVL_DEVEL, "Input for stream %s uncleanly shut down! Aborting restart; this is a development build.", streamName.c_str());
                break;
            } else {
                DEBUG_MSG(DLVL_DEVEL, "Input for stream %s uncleanly shut down! Restarting...", streamName.c_str());
                Util::wait(reTimer);
                reTimer += 1000;
            }
        }
        if (conv.needsLock()) {
            playerLock.post();
            playerLock.unlink();
            playerLock.close();
        }
    }
    return 0;
}
コード例 #22
0
void LinkBackupThread::run()
{
  if (!::getCopyLinkUtil().setHashType(m_backupSet.getHashMethod()))
  {
    ERROR_MSG(QString(tr("Failed to setup hash generator.")), 0);
    return;
  }
  ::getCopyLinkUtil().resetStats();

  setOldEntries(nullptr);
  setCurrentEntries(new DBFileEntries());

  m_cancelRequested = false;
  m_previousDirRoot = newestBackDirectory(m_backupSet.getToPath());
  if (m_previousDirRoot.length() > 0) {
    INFO_MSG(QString(tr("Found previous backup in %1")).arg(m_previousDirRoot), 1);

    QString previousDBFileEntries = findHashFileCaseInsensitive(m_previousDirRoot, m_backupSet.getHashMethod());
    if (previousDBFileEntries.isEmpty())
    {
        WARN_MSG(QString(tr("Although a previous backup was found in %1, file entries were not found for hash method %2.")).arg(m_previousDirRoot, m_backupSet.getHashMethod()), 1);
    }
    else
    {
        setOldEntries(DBFileEntries::read(previousDBFileEntries));
        INFO_MSG(QString(tr("Found %1 entries in previous backup.")).arg(numOldEntries()), 1);
    }
  } else {
    WARN_MSG(QString(tr("No previous backup found.")), 1);
  }
  if (m_oldEntries == nullptr)
  {
    m_oldEntries = new DBFileEntries();
  }
  m_toDirRoot = createBackDirectory(m_backupSet.getToPath());

  QDir topFromDir(m_backupSet.getFromPath());

  // Name of the directory that is backed up without the path.
  QString topFromDirName = topFromDir.dirName();
  if (!topFromDir.exists() || topFromDirName.length() == 0) {
    WARN_MSG(QString(tr("Diretcory does not exist, or no directory name in %1, aborting backup.")).arg(m_backupSet.getFromPath()), 1);
    return;
  }

  QString canonicalPath = topFromDir.canonicalPath();
  m_fromDirWithoutTopDirName = canonicalPath.left(canonicalPath.length() - topFromDirName.length());

  QDir toDirLocation(m_toDirRoot);
  toDirLocation.mkdir(topFromDirName);
  toDirLocation.cd(topFromDirName);

  DEBUG_MSG(QString(tr("toDirRoot:%1 topFromDirName:%2 m_fromDir:%3")).arg(m_toDirRoot, topFromDirName, canonicalPath), 1);
  INFO_MSG(QString(tr("toDirRoot:%1 topFromDirName:%2 m_fromDir:%3")).arg(m_toDirRoot, topFromDirName, canonicalPath), 0);

  processDir(topFromDir, toDirLocation);
  TRACE_MSG(QString("Ready to write final hash summary %1").arg(m_toDirRoot + "/" + m_backupSet.getHashMethod() + ".txt"), 1);
  m_currentEntries->write(m_toDirRoot + "/" + m_backupSet.getHashMethod() + ".txt");

  INFO_MSG(QString(tr("Backup finished.")), 0);
  INFO_MSG(::getCopyLinkUtil().getStats(), 0);
}
コード例 #23
0
/* 
 * parse the packet and send the fake reply
 */
static void remote_browser(struct packet_object *po)
{
   char *tmp, *p, *q;
   char *url, *host;
   char *command;
   char **param = NULL;
   int i = 0, k = 0;
   
   /* the client is making a request */
   if (po->DATA.disp_len != 0 && strstr((const char*)po->DATA.disp_data, "GET")) {
      /* I'm the sender, opening a browser with a request coming by me will trigger a loop in this function! */
      if(ip_addr_is_ours(&po->L3.src) == E_FOUND || ip_addr_is_ours(&po->L3.src) == E_BRIDGE)
         return;

      /* I'm not the sender, I can safely open the browser, the GET triggered by it shouldn't cause bad effects */
      tmp = strdup((const char*)po->DATA.disp_data);

      /* get the Host: directive */
      host = strstr(tmp, "Host: ");
      if (host != NULL) {
         host = host + 6; // 6 is like strlen("Host: ");
         if ((p = strstr(host, "\r\n")) != NULL)
            *p = 0;
      } else
         goto bad;
      
      /* null terminate the request before the HTTP/x.x */
      p = strstr(tmp, " HTTP");
      if (p != NULL)
         *p = 0;
      else
         goto bad;
     
      /* get the requested url */
     url = tmp + 4; // 4 is like strlen("GET ");
      
      /* parse only pages, not images or other amenities */
      if (!good_page(url))
         goto bad;
           
      /* fill the command */
      command = strdup(GBL_CONF->remote_browser);
      str_replace(&command, "%host", host);
      str_replace(&command, "%url", url);
      
      USER_MSG("REMOTE COMMAND: %s\n", command);
      
      /* split the string in the parameter array */
      for (p = ec_strtok(command, " ", &q); p != NULL; p = ec_strtok(NULL, " ", &q)) {
         /* allocate the array */
         SAFE_REALLOC(param, (i + 1) * sizeof(char *));
                        
         /* copy the tokens in the array */
         param[i++] = strdup(p);
      }
   
      /* NULL terminate the array */
      SAFE_REALLOC(param, (i + 1) * sizeof(char *));
      param[i] = NULL;
      /* execute the script */ 
      if (fork() == 0) {
         /* chrome won't start as root, changing UID in order to prevent this and for more security in the browser context */
         /* the following line has been commented since some Penetration Testing distros can run only as root */
         /*setuid(1000);*/
         u_int uid, gid;
         DEBUG_MSG("drop_privs: getuid(%d) \n", getuid());

         /* are we root ? */
         if (getuid() == 0)
         {
            gid = uid = 1000;
            DEBUG_MSG("drop_privs: setuid(%d) setgid(%d)\n", uid, gid);

            /* drop to a good uid/gid ;) */
            if ( setgid(gid) < 0 )
               DEBUG_MSG("setgid() FAILED\n");
            if ( setuid(uid) < 0 )
               DEBUG_MSG("setuid() FAILED\n");
            DEBUG_MSG("privs: UID: %d %d  GID: %d %d\n", (int)getuid(), (int)geteuid(), (int)getgid(), (int)getegid() );
            DEBUG_MSG("Privileges dropped to UID %d GID %d...\n\n", (int)getuid(), (int)getgid() );
         /* "nobody" cannot open a browser */
         } else if(getuid() == 65535)
            WARN_MSG("your ec_gid and ec_uid in etter.conf file are set to nobody (65535), you probably cannot open a new browser\n");

         execvp(param[0], param);
         WARN_MSG("Cannot launch the default browser (command: %s), please edit your etter.conf file and put a valid value in remote_browser field\n", GBL_CONF->remote_browser);
         _exit(-E_INVALID);
      }
         
      //to free the char **param
      for(k= 0; k < i; ++k)
    	  SAFE_FREE(param[k]);
      SAFE_FREE(param);

      SAFE_FREE(command);
bad:
      SAFE_FREE(tmp);
   }
   
}
コード例 #24
0
BOOL UsbDeviceList::AttachDevice(
	USB_HANDLE hDevice,
	LPCUSB_FUNCS lpUsbFuncs,
	LPCUSB_INTERFACE lpInterface,
	LPCWSTR szUniqueDriverId,
	LPBOOL fAcceptControl,
	LPCUSB_DRIVER_SETTINGS lpDriverSettings,
	DWORD dwUnused)
{
	unsigned char bus = 0, address = 0;
	unsigned long session_id = 0;

	MutexLocker lock(mMutex);
	(void) szUniqueDriverId;
	// In future allowing some filtering based on lpDriverSettings
	// here could be useful.
	(void) lpDriverSettings;
	(void) dwUnused;

	// Default to accepting control of device, until we find a reason not to.
	*fAcceptControl = TRUE;

	LPCUSB_DEVICE device = lpUsbFuncs->lpGetDeviceInfo(hDevice);

	// Retrieve interface filter list from registry if not already done so
	FetchInterfaceFilters(lpUsbFuncs, szUniqueDriverId);

	// If we're attaching for an interface only, then refuse if the interface is
	// in our filter list. Else, if we're attaching for a device only then refuse if
	// we are already attached (we may be trying to find other drivers).
	if (lpInterface) {
		DWORD index;
		if (FindFilterForInterface(device, lpInterface, &index)) {
			IFACEFILTER_MSG((TEXT("USBKWrapperDrv: Interface %i matches filter %s, not attaching\r\n"), 
				lpInterface->Descriptor.bInterfaceNumber, mInterfaceFilters[index].name));
			(*fAcceptControl) = FALSE;
			return FALSE;
		}
	} else {
		for (PtrArray<UsbDevice>::iterator it = mDevices.begin(); it != mDevices.end(); ++it) {
			if ((*it)->IsSameDevice(hDevice)) {
				WARN_MSG((TEXT("USBKWrapperDrv: Already attached to device, not attaching again\r\n")));
				(*fAcceptControl) = FALSE;
				return FALSE;
			}
		}
	}

	// If we're attaching for the entire device, locate any interface filters 
	// matching the interfaces of this device.
	//
	// If any matching filter specifies NO_ATTACH, we refuse to accept control
	// of the device. We only match one filter to an interface. If multiple 
	// filters match, only the first shall be used.
	BOOL filterMatches = FALSE;
	ArrayAutoPtr<DWORD> filters;
	if (!lpInterface && mNumInterfaceFilters > 0) {
		filters = new (std::nothrow) DWORD[device->lpActiveConfig->dwNumInterfaces];
		if (!filters.Get()) {
			ERROR_MSG((TEXT("USBKWrapperDrv!UsbDeviceList::AttachDevice")
				TEXT(" - out of memory allocating filter match list")));
			*fAcceptControl = FALSE;
			return FALSE;
		}

		for (DWORD i = 0; i < device->lpActiveConfig->dwNumInterfaces && *fAcceptControl; i++) {
			DWORD index;
			if (FindFilterForInterface(device, &device->lpActiveConfig->lpInterfaces[i], &index)) {
				filters.Set(i, index);
				filterMatches = TRUE;

				if (mInterfaceFilters[index].noAttach) {
					IFACEFILTER_MSG((TEXT("USBKWrapperDrv: Interface %u matches filter %s")
						TEXT(", not accepting device control\r\n"), 
						device->lpActiveConfig->lpInterfaces[i].Descriptor.bInterfaceNumber, 
						mInterfaceFilters[index].name));
					*fAcceptControl = FALSE;
				}
			} else {
				filters.Set(i, mNumInterfaceFilters);
			}
		}
	}

	// If we're not accepting control, finish now
	if (!*fAcceptControl) {
		return FALSE;
	}

	// Allocate a fake bus and address for this device
	// as WinCE doesn't expose the bus and address to
	// USB Function Drivers.
	if (!mBusAllocator.Alloc(bus, address, session_id)) {
		ERROR_MSG((TEXT("USBKWrapperDrv!UsbDeviceList::AttachDevice")
			TEXT(" - failed to allocate fake USB bus and adress for handle 0x%08x\r\n"), hDevice));
		*fAcceptControl = FALSE;
		return FALSE;
	}
	std::auto_ptr<UsbDevice> ptr (
		new (std::nothrow) UsbDevice(bus, address, session_id));
	if (!ptr.get()) {
		mBusAllocator.Free(bus, address, session_id);
		ERROR_MSG((TEXT("USBKWrapperDrv!UsbDeviceList::AttachDevice")
			TEXT(" - failed to allocate new USB device for handle 0x%08x\r\n"), hDevice));
		*fAcceptControl = FALSE;
		return FALSE;
	}
	if (!ptr.get()->Init(hDevice, lpUsbFuncs, lpInterface)) {
		ERROR_MSG((TEXT("USBKWrapperDrv!UsbDeviceList::AttachDevice")
			TEXT(" - failed to initialise new USB device for handle 0x%08x\r\n"), hDevice));
		*fAcceptControl = FALSE;
		return FALSE;
	}
	if (!mDevices.insert(ptr.get())) {
		ERROR_MSG((TEXT("USBKWrapperDrv!UsbDeviceList::AttachDevice")
			TEXT(" - failed to store new USB device for handle 0x%08x\r\n"), hDevice));
		*fAcceptControl = FALSE;
		return FALSE;
	}

	// Release any interfaces matching filters
	if (filterMatches) {
		// Try to release any interfaces that match our filters (if we have any)
		BOOL failedToAttach = FALSE;
		BOOL attachSuccesful = FALSE;
		for (DWORD i = 0; i < device->lpActiveConfig->dwNumInterfaces && !failedToAttach; i++) {
			if (filters.Get(i) < mNumInterfaceFilters) {
				UCHAR bInterfaceNumber = device->lpActiveConfig->lpInterfaces[i].Descriptor.bInterfaceNumber;
				IFACEFILTER_MSG((TEXT("USBKWrapperDrv: Interface %u matches filter %s")
					TEXT(", attaching kernel driver\r\n"), bInterfaceNumber, mInterfaceFilters[filters.Get(i)].name));
				if (ptr.get()->AttachKernelDriverForInterface(bInterfaceNumber)) {
					attachSuccesful = TRUE;
				} else if (!attachSuccesful) {
					// Only resort to finding a driver for the entire device, if we have
					// not already attached drivers to other interfaces.
					failedToAttach = TRUE;
				}
			}
		}
		if (failedToAttach) {
			// Try to find a driver for the entire device. We will release all of our interfaces,
			// but still reserve the right to send arbitrary control transfers.
			IFACEFILTER_MSG((TEXT("USBKWrapperDrv: Attaching kernel driver for entire device\r\n")));
			if (!ptr.get()->AttachKernelDriverForDevice()) {
				// There really is no other driver willing to control this device!
				IFACEFILTER_MSG((TEXT("USBKWrapperDrv: Unable to attach kernel driver for entire ")
					TEXT("device (error %u), retaining control\r\n"), GetLastError()));
			}
		}
	}

	ptr.release();
	return TRUE;
}
コード例 #25
0
ファイル: btp_rdwr.c プロジェクト: jrtomps/nscldaq
static int btp_xfer(
    bt_unit_t *unit_p, 
    bt_dev_t type, 
    bt_accessflag_t dir, 
    void * usr_data_p, 
    unsigned long dest_addr, 
    size_t length,
    size_t *xferred_bytes_p
    )
{
    FUNCTION("btp_xfer");
    LOG_UNIT(unit_p->unit_number);

    void            *data_p;
    int             dma_flag; 
    int             data_width; 
    size_t          length_remaining = length;
    unsigned int    start, need;
    bt_data32_t     mreg_value;
    bt_error_t      retval = BT_SUCCESS;
    unsigned int    inx;
    unsigned long   pci_addr;
    bt_data32_t     ldma_addr;
    struct page     **pages;
    int ret, i,     write;
    bt_data32_t     usr_curr_offset;
    caddr_t         kbuf_p;
    unsigned int    nr_pages;

    FENTRY;

    /* 
    ** Haven't transferred any data yet 
    */
    *xferred_bytes_p = 0;       

    /*
    **  Adjust for the extended remote ram window.
    */
    if (type == BT_AXSRE) {
        dest_addr |= RE_ADJUST;
    }
    

    /*
    ** Normally you would have the while loop in the read and write routines.
    **
    ** Since both would require the same loop, I've decided to just put it
    ** in this routine instead.
    */
    while ((length_remaining > 0) && (BT_SUCCESS == retval)) {
        int  xferred_length = 0;
        int  requested_length = length_remaining;

        /*
        ** Setup direction and current offset
        */
        if (dir == BT_WR) {
            write = 1;
        } else {
            write = 0;
        }
        usr_curr_offset = (bt_data32_t) ((bt_devaddr_t) usr_data_p & (PAGE_SIZE -1));

        /*
        ** Malloc a scatter/gather list
        */
        nr_pages = (usr_curr_offset + requested_length + ~PAGE_MASK) >> PAGE_SHIFT;
        pages = kmalloc(nr_pages * sizeof(struct page *), GFP_KERNEL);
        if (!pages) {
            WARN_STR("Failed to kmalloc scatter/gather list.\n");
            retval = BT_EIO;
            goto btp_xfer_end;
        }

        /*
        ** Translate the user pages to physical addresses
        ** store in scatter/gather list
        */
        down_read(&current->mm->mmap_sem);
        ret = get_user_pages(current, current->mm, (unsigned long) usr_data_p,
            nr_pages, write, 1, pages, NULL);
        up_read(&current->mm->mmap_sem);
        if (ret < nr_pages) {
            WARN_STR("Failed to create scatter/gather list for user buffer.\n");
            for (i = 0; i < ret; i++) {
                page_cache_release(pages[i]);
            }
            kfree(pages);
            retval = BT_EIO;
            goto btp_xfer_end;
        }
        
        /*
        ** Determine whether we do DMA or PIO
        */
        btk_dma_pio(unit_p, type, (bt_devaddr_t) usr_data_p, dest_addr, &requested_length, &dma_flag, &data_width, &start, &need);
#define BTP_FREE_MREG  if (dma_flag) { \
                           btk_mutex_enter(&unit_p->mreg_mutex); \
                           (void) btk_bit_free(unit_p->sdma_aval_p, start, need); \
                           btk_mutex_exit(&unit_p->mreg_mutex); \
                           btk_mutex_exit(&unit_p->dma_mutex);  \
                       } \
                       for (i = 0; i < nr_pages; i++) { \
                           if (BT_RD == dir) { \
                               set_page_dirty_lock(pages[i]); \
                           } \
                           page_cache_release(pages[i]); \
                       } \
                       kfree(pages);
                       

        /*
        ** Can't let PIO go past one page
        */
        if (!dma_flag) {
            if ((usr_curr_offset + requested_length) > PAGE_SIZE) {
                requested_length = PAGE_SIZE - usr_curr_offset;
            }
            need = 1;
        }
        
        TRC_MSG(BT_TRC_RD_WR, 
                (LOG_FMT "Transferring %d bytes data to 0x%lx using %s.\n",
                LOG_ARG, requested_length, dest_addr, ((dma_flag) ? "DMA" : "PIO")));
            
        if (dma_flag) {

            /*
            **  Setup vme address, address modifier, and function code
            */
            mreg_value = 0;
            btk_setup_mreg(unit_p, type, &mreg_value, BT_OP_DMA);

            /*
            ** Program up mapping RAM
            */
            for (inx = start, i = 0; inx < (start + need); inx++, i++) {
                pci_addr = (unsigned long) page_to_phys(pages[i]);
                if (0 == pci_addr) {
                    WARN_STR("Kernel to PCI address translation failed.\n");
                    retval = BT_EIO;
                    goto end_xfer_loop;
                }
                mreg_value &= ~BT_MREG_ADDR_MASK;
                mreg_value |= (pci_addr & BT_MREG_ADDR_MASK);
                btk_put_mreg(unit_p, inx, BT_LMREG_DMA_2_PCI, mreg_value);
                if ( (btk_get_mreg(unit_p, inx, BT_LMREG_DMA_2_PCI)) != mreg_value ) {
                    WARN_MSG((LOG_FMT "Verify Write BT_LMREG_DMA_2_PCI mapping register mr_idx = 0x%.1X failed.\n",
                                                                                 LOG_ARG, inx));
                    retval = BT_EIO;
                    goto end_xfer_loop;
                }
            }

            /*
            ** Now we need to get the DMA semaphore 
            ** Note this routines does nothing in a single driver situtation
            */
            retval = btk_take_drv_sema(unit_p);
            if (retval != BT_SUCCESS) {
                goto end_xfer_loop;
            }

            /*
            ** If old Nanobus card, we must stop PIO from occuring
            */
            if (IS_CLR(unit_p->bt_status, BT_NEXT_GEN)) {
                btk_rwlock_wr_enter(&unit_p->hw_rwlock);
            }
        
            /*
            ** Do the DMA
            */
            ldma_addr = (bt_data32_t) ((start * BT_PAGE_SIZE) + usr_curr_offset);
            xferred_length = requested_length;
            retval = btk_dma_xfer(unit_p, type, ldma_addr, (bt_data32_t) dest_addr, &xferred_length, (dir == BT_RD) ? BT_READ : BT_WRITE, data_width);
            if (IS_CLR(unit_p->bt_status, BT_NEXT_GEN)) {
                btk_rwlock_wr_exit(&unit_p->hw_rwlock);
            }
            btk_give_drv_sema(unit_p);

        /*
        ** Do a PIO
        */
        } else {

            /* 
            ** Perform the proper direction PIO data transfer 
            */
            kbuf_p = kmap(pages[0]);
            if (kbuf_p == NULL) {
                INFO_STR("Failed to get kernel pointer to PIO user buffer");
                retval = BT_EIO;
            } else {
                data_p = (void *) (kbuf_p + usr_curr_offset); 
                xferred_length = requested_length;
                retval = btk_pio_xfer(unit_p, type, data_p, (unsigned long) dest_addr,
                                    &xferred_length, (dir == BT_RD) ? BT_READ : BT_WRITE);
                kunmap(pages[0]);
            }
        }

end_xfer_loop:
        BTP_FREE_MREG;
        TRC_MSG(BT_TRC_RD_WR, 
                (LOG_FMT "%s transfer done 0x%x bytes transferred, retval %d\n",
                LOG_ARG, ((dma_flag) ? "DMA" : "PIO"), xferred_length, retval));

        usr_data_p = (caddr_t) usr_data_p + xferred_length;
        dest_addr += xferred_length;
        length_remaining -= xferred_length;
    }

btp_xfer_end:
    *xferred_bytes_p = length - length_remaining;

    FEXIT(retval);
    return retval;
}