Пример #1
0
/* 
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= **
 *
 *
 * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= **
 */
NTSTATUS
DriverEntry( IN PDRIVER_OBJECT theDriverObject,
             IN PUNICODE_STRING theRegistryPath )

{
NTSTATUS              Status; 
PSECURITY_DESCRIPTOR  SecurityDescriptor;
OBJECT_ATTRIBUTES     ObjectAttributes;
UNICODE_STRING        uPortName;


    // Open the registry and read in all the setting we will use in kernel mode
    EnumerateRegistryValues( theRegistryPath );

   // DDK : "...Add itself to the global list of registered minifilters and to provide 
   //        the Filter Manager with a list of callback functions and other information 
   //        about the minifilter."
   Status = FltRegisterFilter( theDriverObject,
                               &cfsd_FilterRegistration,
                               &gFilterPointer );

    if ( NT_SUCCESS( Status ) )
    {

#if ENABLE_USER_INTERFACE

     Status  = FltBuildDefaultSecurityDescriptor( &SecurityDescriptor,
                                                  FLT_PORT_ALL_ACCESS );

     if ( NT_SUCCESS( Status ) ) 
     {

      RtlInitUnicodeString( &uPortName, USER_COMMUNICATION_PORT_NAME );

      InitializeObjectAttributes( &ObjectAttributes,
                                  &uPortName,
                                  OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
                                  NULL,
                                  SecurityDescriptor );

        Status = FltCreateCommunicationPort( gFilterPointer,                 // Filter
                                             &gUserModeConnection.ServerPort,// *ServerPort
                                             &ObjectAttributes,              // ObjectAttributes
                                             NULL,                           // ServerPortCookie
                                             cfsd_UserModeConnect,           // ConnectNotifyCallback
                                             cfsd_UserModeDisconnect,        // DisconnectNotifyCallback
                                             cfsd_UserModeCommunication,     // MessageNotifyCallback
                                             1 );                            // MaxConnections

        FltFreeSecurityDescriptor( SecurityDescriptor );

        // If we failed to create a communications port then we are going to fail the driver
        if ( !NT_SUCCESS( Status ) ) 
        {

 KdPrint( (PRINT_TAG "Failed FltCreateCommunicationPort() with NTSTATUS 0x%x\n",Status ) );

         // Release our hidden data memory
         ExFreePoolWithTag( gFileData, 'parC' );

         return Status;
        }

 DBG_PRINT( DbgOutput, DBG_USERMODE, (PRINT_TAG_USERMODE "Created communication server port 0x%X for usermode access\n", gUserModeConnection.ServerPort ));

     }

#endif // End #if ENABLE_USER_INTERFACE

     // DDK : "...Notifies the Filter Manager that the minifilter is ready to 
     //        begin attaching to volumes and filtering I/O requests"
     Status = FltStartFiltering( gFilterPointer );

     if ( !NT_SUCCESS( Status )) 
     {

#if ENABLE_USER_INTERFACE
      FltCloseCommunicationPort( gUserModeConnection.ServerPort );
#endif // End #if ENABLE_USER_INTERFACE

      // If we failed FltStartFiltering() then we unregister ourself with the Filter Manager 
      // so that we no longer recieve calls to process I/O operations.
      FltUnregisterFilter( gFilterPointer );

      // Release our hidden data memory
      ExFreePoolWithTag( gFileData, 'parC' );
     }
    }

 return Status;
}
Пример #2
0
void ProcKernelModuleLoaded(PUNICODE_STRING FullImageName, HANDLE  ProcessId, PIMAGE_INFO  ImageInfo)
{
	char buf[256], *s, *sbuf;
	ANSI_STRING AS;
	ULONG l;
	modctl_t *ctl;
	int reloaded = 0;
	
	if (ImageInfo->SystemModeImage) {
		l = RtlUnicodeStringToAnsiSize(FullImageName);
		if (l == 0)
			return;

		RtlInitAnsiString(&AS, NULL);
		RtlUnicodeStringToAnsiString(&AS, FullImageName, TRUE);
		if (AS.MaximumLength >= AS.Length + 1) {
 			AS.Buffer[AS.Length] = '\0';
 		} else {
 			RtlFreeAnsiString(&AS);
 			return;
 		}
 	
		s = strrchr(AS.Buffer, '\\');
		if (s == NULL) {
			RtlFreeAnsiString(&AS);
			return;
		}
		
		s++;
		ctl = modules;
		do {
			if (strcmp(ctl->mod_modname, s) == 0 && ctl->size == ImageInfo->ImageSize) {
				ctl->imgbase = (uintptr_t) ImageInfo->ImageBase;
				ctl->loadcnt++;
				reloaded = 1;
				dprintf("dtrace.sys: module %s reloaded\n", s);
				break;
			}
				
		} while ((ctl = ctl->mod_next) != modules);
		
		if (reloaded == 0) {
			ctl = ExAllocatePoolWithTag(NonPagedPool, sizeof(modctl_t), 'Tag1');
			
			if (ctl == NULL) {
				return;
			}
			sbuf = ExAllocatePoolWithTag(NonPagedPool, strlen(s)+1, 'Tag1');
			RtlFreeAnsiString(&AS);
			
			if (sbuf == NULL) {
				ExFreePoolWithTag(ctl, 'Tag1');
				return;
			}
			strcpy(sbuf, s);
			ctl->imgbase = (uintptr_t) ImageInfo->ImageBase;
			ctl->size = ImageInfo->ImageSize;
			ctl->mod_modname = sbuf;
			ctl->loadcnt = 0;
			ctl->nenabled = 0;
			ctl->fbt_nentries = 0;
			dprintf("dtrace.sys: module %s loaded\n", s);
			
			ctl->mod_next = modules->mod_next;
			modules->mod_next = ctl;
		}	
		dtrace_module_loaded(ctl);
	}
}
Пример #3
0
NTSTATUS
LurCreate(
		PLURELATION_DESC	LurDesc,
		UINT32				DefaultLurFlags,
		PLURELATION			*Lur,
		PVOID				AdapterFdo,
		LURN_EVENT_CALLBACK	LurnEventCallback
	) {
	LONG					idx_lurn;
	LONG					idx_child;
	PLURELATION_NODE_DESC	cur_lurndesc;
	PLURELATION_NODE		cur_lurn;
	LURNDESC_ENTRY			lurndesc_table[LUR_MAX_LURNS_PER_LUR];
	NTSTATUS				status;
	ULONG					child;
	PLURELATION				tmpLur;
	ULONG					tmpLurLength;

	ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL);
	ASSERT(LurDesc->LurnDescCount > 0);
	ASSERT(LurDesc->LurnDescCount <= LUR_MAX_LURNS_PER_LUR);

	if(LurDesc->LurnDescCount <= 0) {
		KDPrintM(DBG_LURN_ERROR, ("No child node.\n"));
		return STATUS_INVALID_PARAMETER;
	}

	RtlZeroMemory(lurndesc_table, sizeof(LURNDESC_ENTRY) * LUR_MAX_LURNS_PER_LUR);
	tmpLur = NULL;

	//
	//	create LURELATION
	//
	tmpLurLength = sizeof(LURELATION) + sizeof(PLURELATION_NODE) * (LurDesc->LurnDescCount - 1);
	tmpLur = (PLURELATION)ExAllocatePoolWithTag(NonPagedPool, tmpLurLength, LUR_POOL_TAG);
	if(!tmpLur) {
		KDPrintM(DBG_LURN_ERROR, ("ExAllocatePoolWithTag() failed.\n"));
		return STATUS_INSUFFICIENT_RESOURCES;
	}
	tmpLur->Type				= LSSTRUC_TYPE_LUR;
	tmpLur->Length				= sizeof(LURELATION);
	tmpLur->MaxBlocksPerRequest = LurDesc->MaxBlocksPerRequest;
	tmpLur->DesiredAccess		= tmpLur->GrantedAccess = LurDesc->AccessRight;
	tmpLur->DevType				= LurDesc->DevType;
	tmpLur->DevSubtype			= LurDesc->DevSubtype;
	tmpLur->NodeCount			= LurDesc->LurnDescCount;
	RtlCopyMemory(tmpLur->LurId, LurDesc->LurId, LURID_LENGTH);

	tmpLur->AdapterFdo			= AdapterFdo;
	tmpLur->LurnEventCallback	= LurnEventCallback;

	//
	//	Set LurFlags to default values or values set by a user.
	//
	LurSetDefaultConfiguration(tmpLur, DefaultLurFlags);
	LurModifyConfiguration(tmpLur, LurDesc);

	//
	//	Content encryption
	//
	tmpLur->CntEcrMethod		= LurDesc->CntEcrMethod;
	tmpLur->CntEcrKeyLength		= LurDesc->CntEcrKeyLength;
	if(LurDesc->CntEcrKeyLength) {
		RtlCopyMemory(tmpLur->CntEcrKey, LurDesc->CntEcrKey, tmpLur->CntEcrKeyLength);
#if DBG
		{
			ULONG	keyIdx;
			KDPrintM(DBG_LURN_INFO, ("Encryption key method:%02x, key length:%d * 4bytes, ",
												LurDesc->CntEcrMethod,
												(int)LurDesc->CntEcrKeyLength)
												);
			for(keyIdx = 0; keyIdx<tmpLur->CntEcrKeyLength; keyIdx++) {
				KDPrintM(DBG_LURN_INFO, ("%02x ", (int)tmpLur->CntEcrKey[keyIdx]));
				if((keyIdx%4) == 0)
					KDPrintM(DBG_LURN_INFO, (" "));
			}
			KDPrintM(DBG_LURN_INFO, ("\n"));
		}
#endif

	}

	//
	//	Allocate LURNs to Lurndesc Table and sanity check.
	//
	RtlZeroMemory(lurndesc_table, sizeof(LURNDESC_ENTRY)*LUR_MAX_LURNS_PER_LUR);
	cur_lurndesc = LurDesc->LurnDesc;
	for(idx_lurn = 0; idx_lurn < (LONG)LurDesc->LurnDescCount; idx_lurn++) {

		KDPrintM(DBG_LURN_INFO, ("Idx:%d LurnDesc:%p NextOffset:%d\n", idx_lurn, cur_lurndesc, cur_lurndesc->NextOffset)) ;
		lurndesc_table[idx_lurn].LurnDesc = cur_lurndesc;

		if(cur_lurndesc->NextOffset == 0 && (LONG)idx_lurn + 1 < (LONG)LurDesc->LurnDescCount) {
			KDPrintM(DBG_LURN_ERROR, ("Invaild NextOffset.\n"));
			status = STATUS_INVALID_PARAMETER;
			goto error_out;
		}
		if(cur_lurndesc->LurnType < 0 || cur_lurndesc->LurnType >= LurnInterfaceCnt) {
			KDPrintM(DBG_LURN_ERROR, ("Invaild LurnType:%x.\n", cur_lurndesc->LurnType));
			status = STATUS_INVALID_PARAMETER;
			goto error_out;
		}

		status = LurnAllocate(&lurndesc_table[idx_lurn].Lurn, lurndesc_table[idx_lurn].LurnDesc->LurnChildrenCnt);
		if(!NT_SUCCESS(status)) {
			KDPrintM(DBG_LURN_ERROR, ("LurnAllocate() failed.\n"));
			goto error_out;
		}

		//
		//	Also initialize LURN index in the LUR.
		//
		lurndesc_table[idx_lurn].Lurn->LurnStatus = LURN_STATUS_INIT;
		tmpLur->Nodes[idx_lurn] = lurndesc_table[idx_lurn].Lurn;

		cur_lurndesc = (PLURELATION_NODE_DESC)((PBYTE)LurDesc + cur_lurndesc->NextOffset);
	}

	//
	//	Build tree. Set up LURN.
	//	Initialize nodes from leaves to a root.
	//
retry_init:

	for(idx_lurn = LurDesc->LurnDescCount - 1; idx_lurn >= 0; idx_lurn--) {
		cur_lurndesc= lurndesc_table[idx_lurn].LurnDesc;
		cur_lurn	= lurndesc_table[idx_lurn].Lurn;

		//
		//	Set LURN IDs of itself, parent,and  children.
		//	LURN ID must be the index number in LUR->Nodes[] array.
		//

		cur_lurn->LurnId			= cur_lurndesc->LurnId;
		cur_lurn->LurnParent		= lurndesc_table[cur_lurndesc->LurnParent].Lurn;

		// Children
		cur_lurn->LurnChildrenCnt	= cur_lurndesc->LurnChildrenCnt;
		for(idx_child = 0; idx_child < (LONG)cur_lurndesc->LurnChildrenCnt; idx_child++) {
			child = cur_lurndesc->LurnChildren[idx_child];
			if(child < 0 || child > LurDesc->LurnDescCount)
			{
				if(!NT_SUCCESS(status)) {
					KDPrintM(DBG_LURN_ERROR, ("invalid child number.\n"));
					goto error_out;
				}
			}
			cur_lurn->LurnChildren[idx_child] = lurndesc_table[child].Lurn;
		}

		//
		//	Access right
		//
		cur_lurndesc->AccessRight = tmpLur->GrantedAccess;

		//
		//	Initialize the LURN
		//
		ASSERT(cur_lurn->LurnDesc == NULL);

		status = LurnInitialize(cur_lurn, tmpLur, cur_lurndesc);
		if(cur_lurndesc->LurnOptions & LURNOPTION_MISSING &&
			!NT_SUCCESS(status)) {
			ULONG					lurndesc_len;
			PLURELATION_NODE_DESC	lurnDesc;
			

			//
			//	Save LURN Descriptor.
			//

			lurndesc_len = FIELD_OFFSET(LURELATION_NODE_DESC, LurnChildren) +
				cur_lurndesc->LurnChildrenCnt * sizeof(ULONG);

			lurnDesc = ExAllocatePoolWithTag(
										NonPagedPool,
										lurndesc_len,
										LURN_POOL_TAG);
			if(lurnDesc == NULL) {
				KDPrintM(DBG_LURN_ERROR, ("ExAllocatePoolWithTag() failed.\n"));
			} else {
				//
				//	Destroy the LURN to initialize later.
				//

				LurnDestroy(cur_lurn);

				RtlCopyMemory(lurnDesc, cur_lurndesc, lurndesc_len);

				KDPrintM(DBG_LURN_ERROR, ("LURELATION_NODE_DESC #%u copied.\n", cur_lurn->LurnId));

				cur_lurn->LurnDesc = lurnDesc;

				KDPrintM(DBG_LURN_ERROR, ("Saved pointer the lurn desc:%p\n", cur_lurn->LurnDesc));
				continue;
			}

		}

		if((LURN_IDE_ODD != cur_lurndesc->LurnType) 
			&& (LURN_IDE_MO != cur_lurndesc->LurnType) ){


			if(tmpLur->LurFlags & LURFLAG_WRITESHARE_PS) {

				if(status == STATUS_ACCESS_DENIED && (tmpLur->GrantedAccess & GENERIC_WRITE)) {
						LONG	idx_closinglurn;

					if(LurDesc->LurOptions & LUROPTION_OFF_FAKEWRITE) {
						KDPrintM(DBG_LURN_ERROR, ("LUROPTION_OFF_FAKEWRITE is set. Can not go to Secondary mode.\n"));
					} else {
						for(idx_closinglurn = idx_lurn; idx_closinglurn < (LONG)LurDesc->LurnDescCount; idx_closinglurn++) {
							SendStopCcbToLurn(lurndesc_table[idx_closinglurn].Lurn);
							LurnDestroy(lurndesc_table[idx_closinglurn].Lurn);
						}

						KDPrintM(DBG_LURN_ERROR, ("Degrade access right and retry.\n"));
						tmpLur->GrantedAccess &= ~GENERIC_WRITE;
						tmpLur->LurFlags |= LURFLAG_FAKEWRITE;

						goto retry_init;
					}
				}
			}
		}
		if(!NT_SUCCESS(status)) {
			LONG	idx_closinglurn;

			KDPrintM(DBG_LURN_ERROR, ("LurnInitialize() failed. LURN#:%d NTSTATUS:%08lx\n", idx_lurn, status));
			for(idx_closinglurn = idx_lurn; idx_closinglurn < (LONG)LurDesc->LurnDescCount; idx_closinglurn++) {
				SendStopCcbToLurn(lurndesc_table[idx_closinglurn].Lurn);
				LurnDestroy(lurndesc_table[idx_closinglurn].Lurn);
			}
			goto error_out;
		}
	}

	//
	// set Lur
	//
	*Lur = tmpLur;

	return STATUS_SUCCESS;

error_out:
	for(idx_lurn = 0; (ULONG)idx_lurn < LurDesc->LurnDescCount; idx_lurn++) {
		PLURELATION_NODE	lurn;

		lurn = lurndesc_table[idx_lurn].Lurn;
		if(lurn) {
			KDPrintM(DBG_LURN_ERROR, ("Freeing LURN:%p(%d)\n", lurn, idx_lurn));

			if(lurn->LurnStatus == LURN_STATUS_RUNNING) {
				SendStopCcbToLurn(lurn);
				LurnDestroy(lurn);
			}
			LurnFree(lurn);
			lurndesc_table[idx_lurn].Lurn = NULL;
		}
	}

	if(tmpLur) {
		ExFreePoolWithTag(tmpLur, LUR_POOL_TAG);

	}

	return status;
}
Пример #4
0
VOID VIOSerialPortWrite(IN WDFQUEUE Queue,
                        IN WDFREQUEST Request,
                        IN size_t Length)
{
    NTSTATUS status;
    PVOID InBuf;
    PVOID buffer;
    PVIOSERIAL_PORT Port;
    PWRITE_BUFFER_ENTRY entry;

    TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE,
        "--> %s Request: %p Length: %d\n", __FUNCTION__, Request, Length);

    PAGED_CODE();

    Port = RawPdoSerialPortGetData(WdfIoQueueGetDevice(Queue))->port;
    if (Port->Removed)
    {
        TraceEvents(TRACE_LEVEL_WARNING, DBG_WRITE,
            "Write request on a removed port %d\n", Port->PortId);
        WdfRequestComplete(Request, STATUS_OBJECT_NO_LONGER_EXISTS);
        return;
    }

    status = WdfRequestRetrieveInputBuffer(Request, Length, &InBuf, NULL);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE,
            "Failed to retrieve input buffer: %x\n", status);
        WdfRequestComplete(Request, status);
        return;
    }

    if (VIOSerialWillWriteBlock(Port))
    {
        WdfRequestComplete(Request, STATUS_CANT_WAIT);
        return;
    }

    buffer = ExAllocatePoolWithTag(NonPagedPool, Length,
        VIOSERIAL_DRIVER_MEMORY_TAG);

    if (buffer == NULL)
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE, "Failed to allocate.\n");
        WdfRequestComplete(Request, STATUS_INSUFFICIENT_RESOURCES);
        return;
    }

    entry = (PWRITE_BUFFER_ENTRY)ExAllocatePoolWithTag(NonPagedPool,
        sizeof(WRITE_BUFFER_ENTRY), VIOSERIAL_DRIVER_MEMORY_TAG);

    if (entry == NULL)
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE,
            "Failed to allocate write buffer entry.\n");
        ExFreePoolWithTag(buffer, VIOSERIAL_DRIVER_MEMORY_TAG);
        WdfRequestComplete(Request, STATUS_INSUFFICIENT_RESOURCES);
        return;
    }

    status = WdfRequestMarkCancelableEx(Request,
        VIOSerialPortWriteRequestCancel);

    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE,
            "Failed to mark request as cancelable: %x\n", status);
        ExFreePoolWithTag(entry, VIOSERIAL_DRIVER_MEMORY_TAG);
        ExFreePoolWithTag(buffer, VIOSERIAL_DRIVER_MEMORY_TAG);
        WdfRequestComplete(Request, status);
        return;
    }

    RtlCopyMemory(buffer, InBuf, Length);
    WdfRequestSetInformation(Request, (ULONG_PTR)Length);

    entry->Buffer = buffer;
    PushEntryList(&Port->WriteBuffersList, &entry->ListEntry);

    Port->PendingWriteRequest = Request;

    if (VIOSerialSendBuffers(Port, buffer, Length) <= 0)
    {
        PSINGLE_LIST_ENTRY removed;

        TraceEvents(TRACE_LEVEL_ERROR, DBG_WRITE,
            "Failed to send user's buffer.\n");

        ExFreePoolWithTag(buffer, VIOSERIAL_DRIVER_MEMORY_TAG);

        removed = PopEntryList(&Port->WriteBuffersList);
        NT_ASSERT(entry == CONTAINING_RECORD(removed, WRITE_BUFFER_ENTRY, ListEntry));
        ExFreePoolWithTag(entry, VIOSERIAL_DRIVER_MEMORY_TAG);

        if ((Port->PendingWriteRequest != NULL) &&
            (WdfRequestUnmarkCancelable(Request) != STATUS_CANCELLED))
        {
            Port->PendingWriteRequest = NULL;

            WdfRequestComplete(Request, Port->Removed ?
                STATUS_INVALID_DEVICE_STATE : STATUS_INSUFFICIENT_RESOURCES);
        }
    }

    TraceEvents(TRACE_LEVEL_VERBOSE, DBG_WRITE,"<-- %s\n", __FUNCTION__);
}
Пример #5
0
/**
 * Used In B+ Tree Delete Node
 */
void Free_Record( record * r )
{
	PCACHE_BLOCK p = (PCACHE_BLOCK)r;
	ExFreePoolWithTag(p, CACHE_POOL_TAG);
}
Пример #6
0
// Get Usb Device Descriptor
NTSTATUS UsbDev::GetDeviceDescriptor()
{
	NTSTATUS	ntStatus;
    PURB		pUrb;

	DBGU_TRACE(">>>UsbDev::GetDeviceDescriptor !\n");
    pUrb = (PURB) ExAllocatePoolWithTag(NonPagedPool, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST), USBDEV_POOLTAG);

    if (pUrb) 
	{//pUrb != NULL
		RtlZeroMemory((void *) pUrb, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST));
        UsbBuildGetDescriptorRequest(
			pUrb,
			(USHORT) sizeof (struct _URB_CONTROL_DESCRIPTOR_REQUEST),
			USB_DEVICE_DESCRIPTOR_TYPE,
			0,
			0,
			&m_DevDesc,
			NULL,
			sizeof(USB_DEVICE_DESCRIPTOR),
			NULL);
        ntStatus = SendAwaitUrb(pUrb);
	    ExFreePoolWithTag(pUrb,USBDEV_POOLTAG);

#if DBG
        if (NT_SUCCESS(ntStatus)) {

			//Print the infomation of device descriptor
            DBGU_TRACE("  Device Descriptor:\n");
            DBGU_TRACE("  -------------------------\n");
            DBGU_TRACE("  bLength %x\n", m_DevDesc.bLength);
            DBGU_TRACE("  bDescriptorType 0x%x\n", m_DevDesc.bDescriptorType);
            DBGU_TRACE("  bcdUSB 0x%x\n", m_DevDesc.bcdUSB);
            DBGU_TRACE("  bDeviceClass 0x%x\n", m_DevDesc.bDeviceClass);
            DBGU_TRACE("  bDeviceSubClass 0x%x\n", m_DevDesc.bDeviceSubClass);
            DBGU_TRACE("  bDeviceProtocol 0x%x\n", m_DevDesc.bDeviceProtocol);
            DBGU_TRACE("  bMaxPacketSize0 0x%x\n", m_DevDesc.bMaxPacketSize0);
            DBGU_TRACE("  idVendor 0x%x\n", m_DevDesc.idVendor);
            DBGU_TRACE("  idProduct 0x%x\n", m_DevDesc.idProduct);
            DBGU_TRACE("  bcdDevice 0x%x\n", m_DevDesc.bcdDevice);
            DBGU_TRACE("  iManufacturer 0x%x\n", m_DevDesc.iManufacturer);
            DBGU_TRACE("  iProduct 0x%x\n", m_DevDesc.iProduct);
            DBGU_TRACE("  iSerialNumber 0x%x\n", m_DevDesc.iSerialNumber);
            DBGU_TRACE("  bNumConfigurations 0x%x\n", m_DevDesc.bNumConfigurations);
            DBGU_TRACE("  -------------------------\n");
			
        } 
		else 
		{
			DBGU_TRACE("ERR: Cannot get device descriptor !!\n");
		}
#endif
    }//pUrb != NULL 
	else 
	{//pUrb == NULL	
		DBGU_TRACE("ERR: Fail to allocate memory for pUrb !!\n");
        ntStatus = STATUS_INSUFFICIENT_RESOURCES;
    }//pUrb == NULL

    return ntStatus;
}
Пример #7
0
// Set the alternate setting of the interface.
NTSTATUS UsbDev::SetAlternate(UCHAR AlternateNo, UCHAR InterfaceNo)
{
	NTSTATUS ntStatus = STATUS_SUCCESS;
	PURB pUrb = NULL;
	PUSBD_INTERFACE_INFORMATION pInterfaceInfo = NULL;
	int i;

	DBGU_TRACE(">>>UsbDev::SetAlternate !\n");

	if (m_pInterface[InterfaceNo])
		pInterfaceInfo = m_pInterface[InterfaceNo];

	if(pInterfaceInfo)
	{//pInterfaceInfo != NULL
#ifdef __VIDEO_CLASS__
		// For Video Class Device
		DBGU_TRACE("Change information for ISO Interface\n");
		/*
		if (InterfaceNo == 1)
			pInterfaceInfo->NumberOfPipes = 1;

		if ((InterfaceNo == 1)&&(AlternateNo > 0))
			pInterfaceInfo->Length = sizeof(USBD_INTERFACE_INFORMATION);
		*/
		// james try M2TS.
		if (InterfaceNo == 1 || InterfaceNo == 2)
		{
			//if(TwoPipeEnable)
			if(BeST5R286)
			{
				pInterfaceInfo->NumberOfPipes = 2;

				if (AlternateNo > 0)
				{
					//2010/10/28 06:45下午 test
					pInterfaceInfo->Length = GET_USBD_INTERFACE_SIZE(2);//sizeof(USBD_INTERFACE_INFORMATION);
					
					//2010/11/18 03:17下午
					if(TwoPipeEnable)
					{
						m_StopIsoThread[0] = FALSE;
						m_StopIsoThread[1] = FALSE;
					}
					else
						m_StopIsoThread[0] = FALSE;
				}				
			}
			else
			{
					pInterfaceInfo->NumberOfPipes = 1;
					if (AlternateNo > 0)
						pInterfaceInfo->Length = sizeof(USBD_INTERFACE_INFORMATION);
					m_StopIsoThread[0] = FALSE;			
			}
		}
#endif
		pUrb = (PURB) ExAllocatePoolWithTag(NonPagedPool, GET_SELECT_INTERFACE_REQUEST_SIZE(pInterfaceInfo->NumberOfPipes), USBDEV_POOLTAG);

		if(pUrb) 
		{//pUrb != NULL
			pInterfaceInfo->AlternateSetting = AlternateNo;

			for(i=0;i<pInterfaceInfo->NumberOfPipes;i++)
			{
				if (m_fUSBHighSpeed)
					pInterfaceInfo->Pipes[i].MaximumTransferSize = MAX_TRANSFER_SIZE_2;
				else
					pInterfaceInfo->Pipes[i].MaximumTransferSize = MAX_TRANSFER_SIZE;

				pInterfaceInfo->Pipes[i].PipeFlags = 0;
			}

			RtlCopyMemory(&pUrb->UrbSelectInterface.Interface, pInterfaceInfo, pInterfaceInfo->Length);
			pUrb->UrbHeader.Length   = GET_SELECT_INTERFACE_REQUEST_SIZE(pInterfaceInfo->NumberOfPipes);
			pUrb->UrbHeader.Function = URB_FUNCTION_SELECT_INTERFACE;
			pUrb->UrbSelectInterface.ConfigurationHandle = m_hConfigureation;
			ntStatus = SendAwaitUrb(pUrb);

			if(!NT_SUCCESS(ntStatus))
			{//ntStatus != STATUS_SUCCESS
				DBGU_TRACE("ERR: Fail to set alternate setting !!\n");
				ntStatus = STATUS_UNSUCCESSFUL;
			}//ntStatus != STATUS_SUCCESS
			else
			{//ntStatus == STATUS_SUCCESS
				if(pInterfaceInfo->Length > pUrb->UrbSelectInterface.Interface.Length) 
					pInterfaceInfo->Length = pUrb->UrbSelectInterface.Interface.Length;

				RtlCopyMemory(pInterfaceInfo, &pUrb->UrbSelectInterface.Interface, pUrb->UrbSelectInterface.Interface.Length);
				//Display interface information
#if DBG
				DBGU_TRACE(" Interface Information\n");
				DBGU_TRACE(" -----------------------------------\n");
				DBGU_TRACE(" Length: %x\n",pUrb->UrbSelectInterface.Interface.Length);
				DBGU_TRACE(" InterfaceNumber: %x\n",pUrb->UrbSelectInterface.Interface.InterfaceNumber);
				DBGU_TRACE(" AlternateSetting: %x\n", pUrb->UrbSelectInterface.Interface.AlternateSetting);
				DBGU_TRACE(" NumberOfPipes: %x\n",pUrb->UrbSelectInterface.Interface.NumberOfPipes);
				DBGU_TRACE(" Class: %x\n",pUrb->UrbSelectInterface.Interface.Class);
				DBGU_TRACE(" SubClass: %x\n",	pUrb->UrbSelectInterface.Interface.SubClass);
				DBGU_TRACE(" Protocol: %x\n",pUrb->UrbSelectInterface.Interface.Protocol);
				DBGU_TRACE(" InterfaceHandle: %x\n",pUrb->UrbSelectInterface.Interface.InterfaceHandle);
				DBGU_TRACE(" -----------------------------------\n");

				for(i=0;i<pInterfaceInfo->NumberOfPipes;i++) 
				{// for loop i
					DBGU_TRACE(" Pipes (%x) Information\n",i);
					DBGU_TRACE(" -----------------------------------\n");	
					DBGU_TRACE(" EndpointAddress: %x\n",pUrb->UrbSelectInterface.Interface.Pipes[i].EndpointAddress);     
					DBGU_TRACE(" PipeType: %x\n",pUrb->UrbSelectInterface.Interface.Pipes[i].PipeType);
					DBGU_TRACE(" PipeHandle: %x\n",pUrb->UrbSelectInterface.Interface.Pipes[i].PipeHandle);
					DBGU_TRACE(" MaximumPacketSize: %x\n",pUrb->UrbSelectInterface.Interface.Pipes[i].MaximumPacketSize);
				}// for loop i

				DBGU_TRACE(" -----------------------------------\n");	
#endif
			}//ntStatus == STATUS_SUCCESS
		}//pUrb != NULL
		else
		{//pUrb == NULL
			ntStatus = STATUS_INSUFFICIENT_RESOURCES;
		}//pUrb == NULL
	}//pInterfaceInfo != NULL
	else
	{//pInterfaceInfo == NULL
		DBGU_TRACE("pInterfaceInfo == NULL !\n");
		ntStatus = STATUS_UNSUCCESSFUL;
	}//pInterfaceInfo == NULL

	if(pUrb)
		ExFreePoolWithTag(pUrb,USBDEV_POOLTAG);
	
	return ntStatus;
}
Пример #8
0
VOID
OvsFreeAlignedMemory(VOID *ptr)
{
    ASSERT(ptr);
    ExFreePoolWithTag(ptr, OVS_MEMORY_TAG);
}
Пример #9
0
NTSTATUS NTAPI
IopQueryBusDescription(
   PIO_QUERY Query,
   UNICODE_STRING RootKey,
   HANDLE RootKeyHandle,
   PULONG Bus,
   BOOLEAN KeyIsRoot)
{
   NTSTATUS Status;
   ULONG BusLoop;
   UNICODE_STRING SubRootRegName;
   UNICODE_STRING BusString;
   UNICODE_STRING SubBusString;
   ULONG LenBasicInformation = 0;
   ULONG LenFullInformation;
   ULONG LenKeyFullInformation;
   ULONG LenKey;
   HANDLE SubRootKeyHandle;
   PKEY_FULL_INFORMATION FullInformation;
   PKEY_BASIC_INFORMATION BasicInformation = NULL;
   OBJECT_ATTRIBUTES ObjectAttributes;
   PKEY_VALUE_FULL_INFORMATION BusInformation[3] = {NULL, NULL, NULL};

   /* How much buffer space */
   Status = ZwQueryKey(RootKeyHandle, KeyFullInformation, NULL, 0, &LenFullInformation);

   if (!NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL && Status != STATUS_BUFFER_OVERFLOW)
      return Status;

   /* Allocate it */
   FullInformation = ExAllocatePoolWithTag(PagedPool, LenFullInformation, TAG_IO_RESOURCE);

   if (!FullInformation)
     return STATUS_NO_MEMORY;

   /* Get the Information */
   Status = ZwQueryKey(RootKeyHandle, KeyFullInformation, FullInformation, LenFullInformation, &LenFullInformation);

   /* Everything was fine */
   if (NT_SUCCESS(Status))
   {
      /* Buffer needed for all the keys under this one */
      LenBasicInformation = FullInformation->MaxNameLen + sizeof(KEY_BASIC_INFORMATION);

      /* Allocate it */
      BasicInformation = ExAllocatePoolWithTag(PagedPool, LenBasicInformation, TAG_IO_RESOURCE);
   }

   /* Deallocate the old Buffer */
   ExFreePoolWithTag(FullInformation, TAG_IO_RESOURCE);

   /* Try to find a Bus */
   for (BusLoop = 0; NT_SUCCESS(Status); BusLoop++)
   {
      /* Bus parameter was passed and number was matched */
      if ((Query->BusNumber) && (*(Query->BusNumber)) == *Bus) break;

      /* Enumerate the Key */
      Status = ZwEnumerateKey(
         RootKeyHandle,
         BusLoop,
         KeyBasicInformation,
         BasicInformation,
         LenBasicInformation,
         &LenKey);

      /* Everything enumerated */
      if (!NT_SUCCESS(Status)) break;

      /* What Bus are we going to go down? (only check if this is a Root Key) */
      if (KeyIsRoot)
      {
         if (wcsncmp(BasicInformation->Name, L"MultifunctionAdapter", BasicInformation->NameLength / 2) &&
             wcsncmp(BasicInformation->Name, L"EisaAdapter", BasicInformation->NameLength / 2) &&
             wcsncmp(BasicInformation->Name, L"TcAdapter", BasicInformation->NameLength / 2))
         {
            /* Nothing found, check next */
            continue;
         }
      }

      /* Enumerate the Bus. */
      BusString.Buffer = BasicInformation->Name;
      BusString.Length = (USHORT)BasicInformation->NameLength;
      BusString.MaximumLength = (USHORT)BasicInformation->NameLength;

      /* Open a handle to the Root Registry Key */
      InitializeObjectAttributes(
         &ObjectAttributes,
         &BusString,
         OBJ_CASE_INSENSITIVE,
         RootKeyHandle,
         NULL);

      Status = ZwOpenKey(&SubRootKeyHandle, KEY_READ, &ObjectAttributes);

      /* Go on if we can't */
      if (!NT_SUCCESS(Status)) continue;

      /* Key opened. Create the path */
      SubRootRegName = RootKey;
      RtlAppendUnicodeToString(&SubRootRegName, L"\\");
      RtlAppendUnicodeStringToString(&SubRootRegName, &BusString);

      if (!KeyIsRoot)
      {
         /* Parsing a SubBus-key */
         int SubBusLoop;
         PWSTR Strings[3] = {
            L"Identifier",
            L"Configuration Data",
            L"Component Information"};

         for (SubBusLoop = 0; SubBusLoop < 3; SubBusLoop++)
         {
            /* Identifier String First */
            RtlInitUnicodeString(&SubBusString, Strings[SubBusLoop]);

            /* How much buffer space */
            ZwQueryValueKey(SubRootKeyHandle, &SubBusString, KeyValueFullInformation, NULL, 0, &LenKeyFullInformation);

            /* Allocate it */
            BusInformation[SubBusLoop] = ExAllocatePoolWithTag(PagedPool, LenKeyFullInformation, TAG_IO_RESOURCE);

            /* Get the Information */
            Status = ZwQueryValueKey(SubRootKeyHandle, &SubBusString, KeyValueFullInformation, BusInformation[SubBusLoop], LenKeyFullInformation, &LenKeyFullInformation);
         }

         if (NT_SUCCESS(Status))
         {
            /* Do we have something */
            if (BusInformation[1] != NULL &&
                BusInformation[1]->DataLength != 0 &&
                /* Does it match what we want? */
                (((PCM_FULL_RESOURCE_DESCRIPTOR)((ULONG_PTR)BusInformation[1] + BusInformation[1]->DataOffset))->InterfaceType == *(Query->BusType)))
            {
               /* Found a bus */
               (*Bus)++;

               /* Is it the bus we wanted */
               if (Query->BusNumber == NULL || *(Query->BusNumber) == *Bus)
               {
                  /* If we don't want Controller Information, we're done... call the callback */
                  if (Query->ControllerType == NULL)
                  {
                     Status = Query->CalloutRoutine(
                        Query->Context,
                        &SubRootRegName,
                        *(Query->BusType),
                        *Bus,
                        BusInformation,
                        0,
                        0,
                        NULL,
                        0,
                        0,
                        NULL);
                  } else {
                     /* We want Controller Info...get it */
                     Status = IopQueryDeviceDescription(Query, SubRootRegName, RootKeyHandle, *Bus, (PKEY_VALUE_FULL_INFORMATION*)BusInformation);
                  }
               }
            }
         }

         /* Free the allocated memory */
         for (SubBusLoop = 0; SubBusLoop < 3; SubBusLoop++)
         {
            if (BusInformation[SubBusLoop])
            {
               ExFreePoolWithTag(BusInformation[SubBusLoop], TAG_IO_RESOURCE);
               BusInformation[SubBusLoop] = NULL;
            }
         }

         /* Exit the Loop if we found the bus */
         if (Query->BusNumber != NULL && *(Query->BusNumber) == *Bus)
         {
            ZwClose(SubRootKeyHandle);
            SubRootKeyHandle = NULL;
            continue;
         }
      }

      /* Enumerate the buses below us recursively if we haven't found the bus yet */
      Status = IopQueryBusDescription(Query, SubRootRegName, SubRootKeyHandle, Bus, !KeyIsRoot);

      /* Everything enumerated */
      if (Status == STATUS_NO_MORE_ENTRIES) Status = STATUS_SUCCESS;

      ZwClose(SubRootKeyHandle);
      SubRootKeyHandle = NULL;
   }

   /* Free the last remaining Allocated Memory */
   if (BasicInformation)
      ExFreePoolWithTag(BasicInformation, TAG_IO_RESOURCE);

   return Status;
}
Пример #10
0
NTSTATUS QueryAndAllocRegistryData(HANDLE hKey, LPCWSTR Value, ULONG Type, PUNICODE_STRING Data, PUNICODE_STRING Default)
{
	PKEY_VALUE_PARTIAL_INFORMATION info = NULL;
	UNICODE_STRING valueName;
	ULONG length, dataLength;
	NTSTATUS status;
	PVOID dataBuffer;

	if (Default)
	{
		dataLength = Default->Length;
		dataBuffer = ExAllocatePoolWithTag(NonPagedPool, dataLength, CONFIG_ALLOC_TAG);
		if (!dataBuffer)
			return STATUS_NO_MEMORY;

		RtlCopyMemory(dataBuffer, Default->Buffer, dataLength);
	}
	else
	{
		dataLength = 0;
		dataBuffer = NULL;
	}

	RtlInitUnicodeString(&valueName, Value);

	status = ZwQueryValueKey(hKey, &valueName, KeyValuePartialInformation, NULL, 0, &length);
	if (status != STATUS_BUFFER_OVERFLOW && status != STATUS_BUFFER_TOO_SMALL)
		goto end_proc;

	if (length < sizeof(KEY_VALUE_PARTIAL_INFORMATION))
		goto end_proc;

	info = (PKEY_VALUE_PARTIAL_INFORMATION)ExAllocatePoolWithTag(NonPagedPool, length, CONFIG_ALLOC_TAG);
	if (!info)
		goto end_proc;

	status = ZwQueryValueKey(hKey, &valueName, KeyValuePartialInformation, info, length, &length);
	if (!NT_SUCCESS(status))
		goto end_proc;

	if (info->Type != Type)
		goto end_proc;

	if (info->DataLength == 0 || info->DataLength > 0xFFFF)
		goto end_proc;

	if (dataBuffer)
		ExFreePoolWithTag(dataBuffer, CONFIG_ALLOC_TAG);

	dataLength = info->DataLength;
	dataBuffer = ExAllocatePoolWithTag(NonPagedPool, dataLength, CONFIG_ALLOC_TAG);
	if (!dataBuffer)
		return STATUS_NO_MEMORY;

	RtlCopyMemory(dataBuffer, info->Data, dataLength);

end_proc:

	if (info)
		ExFreePoolWithTag(info, CONFIG_ALLOC_TAG);

	Data->Buffer = (PWCH)dataBuffer;
	Data->Length = (USHORT)dataLength;
	Data->MaximumLength = (USHORT)dataLength;

	return STATUS_SUCCESS;
}
Пример #11
0
VOID ReleaseRegistryData(PUNICODE_STRING Data)
{
	if (Data->Length)
		ExFreePoolWithTag(Data->Buffer, CONFIG_ALLOC_TAG);
}
Пример #12
0
NTSTATUS kkll_m_minifilters_list(PKIWI_BUFFER outBuffer)
{
    NTSTATUS status = STATUS_SUCCESS;
    ULONG NumberFiltersReturned, NumberInstancesReturned, sizeOfBuffer;
    PFLT_FILTER *FilterList = NULL;
    PFLT_INSTANCE *InstanceList = NULL;
    PFLT_VOLUME Volume = NULL;
    PFILTER_FULL_INFORMATION myFilterFullInformation = NULL;
    PVOID pCallBack, preCallBack, postCallBack;
    ULONG i, j, k;

    status = FltEnumerateFilters(NULL, 0, &NumberFiltersReturned);
    if((status == STATUS_BUFFER_TOO_SMALL) && NumberFiltersReturned)
    {
        sizeOfBuffer = sizeof(PFLT_FILTER) * NumberFiltersReturned;
        if(FilterList = (PFLT_FILTER *) ExAllocatePoolWithTag(NonPagedPool, sizeOfBuffer, POOL_TAG))
        {
            status = FltEnumerateFilters(FilterList, sizeOfBuffer, &NumberFiltersReturned);
            for(i = 0; NT_SUCCESS(status) && (i < NumberFiltersReturned); i++)
            {
                status = FltGetFilterInformation(FilterList[i], FilterFullInformation, NULL, 0, &sizeOfBuffer);
                if((status == STATUS_BUFFER_TOO_SMALL) && sizeOfBuffer)
                {
                    if(myFilterFullInformation = (PFILTER_FULL_INFORMATION) ExAllocatePoolWithTag(NonPagedPool, sizeOfBuffer, POOL_TAG))
                    {
                        status = FltGetFilterInformation(FilterList[i], FilterFullInformation, myFilterFullInformation, sizeOfBuffer, &sizeOfBuffer);
                        if(NT_SUCCESS(status))
                        {
                            status = kprintf(outBuffer, L"[%.2u] %.*s\n", i, myFilterFullInformation->FilterNameLength/sizeof(WCHAR), myFilterFullInformation->FilterNameBuffer);
                            if(NT_SUCCESS(status))
                            {
                                status = FltEnumerateInstances(NULL, FilterList[i], NULL, 0, &NumberInstancesReturned);
                                if((status == STATUS_BUFFER_TOO_SMALL) && NumberInstancesReturned)
                                {
                                    if(InstanceList = (PFLT_INSTANCE *) ExAllocatePoolWithTag(NonPagedPool, sizeof(PFLT_INSTANCE) * NumberInstancesReturned, POOL_TAG))
                                    {
                                        status = FltEnumerateInstances(NULL, FilterList[i], InstanceList, NumberInstancesReturned, &NumberInstancesReturned);
                                        for(j = 0; NT_SUCCESS(status) && (j < NumberInstancesReturned); j++)
                                        {
                                            if(NT_SUCCESS(FltGetVolumeFromInstance(InstanceList[j], &Volume)))
                                            {
                                                status = kprintf(outBuffer, L"  [%.2u] %wZ\n", j, (PUNICODE_STRING) (((ULONG_PTR) Volume) + MF_OffSetTable[KiwiOsIndex][CallbackVolumeNameOffset]));
                                                FltObjectDereference (Volume);
                                            }
                                            else
                                            {
                                                status = kprintf(outBuffer, L"  [%.2u] /\n", j);;
                                            }
                                            for(k = 0x16; NT_SUCCESS(status) && (k < 0x32); k++)
                                            {
                                                if(pCallBack = (PVOID) *(PULONG_PTR) (( ((ULONG_PTR) InstanceList[j] )+ MF_OffSetTable[KiwiOsIndex][CallbackOffset]) + sizeof(PVOID)*k))
                                                {
                                                    preCallBack = (PVOID) *(PULONG_PTR) (((ULONG_PTR) pCallBack) + MF_OffSetTable[KiwiOsIndex][CallbackPreOffset]);
                                                    postCallBack = (PVOID) *(PULONG_PTR) (((ULONG_PTR) pCallBack) + MF_OffSetTable[KiwiOsIndex][CallbackPostOffset]);
                                                    if(preCallBack || postCallBack)
                                                    {
                                                        status = kprintf(outBuffer, L"    [0x%2x] %s\n", k, irpToName[k - 0x16]);
                                                        if(NT_SUCCESS(status) && preCallBack)
                                                        {
                                                            status = kprintf(outBuffer, L"      PreCallback  : ");
                                                            if(NT_SUCCESS(status))
                                                                status = kkll_m_modules_fromAddr(outBuffer, preCallBack);
                                                        }
                                                        if(NT_SUCCESS(status) && postCallBack)
                                                        {
                                                            status = kprintf(outBuffer, L"      PostCallback : ");
                                                            if(NT_SUCCESS(status))
                                                                status = kkll_m_modules_fromAddr(outBuffer, postCallBack);
                                                        }
                                                    }
                                                }
                                            }
                                            FltObjectDereference (InstanceList[j]);
                                        }
                                        ExFreePoolWithTag(InstanceList, POOL_TAG);
                                    }
                                }
                            }
                        }
                        ExFreePoolWithTag(myFilterFullInformation, POOL_TAG);
                    }
                }
                FltObjectDereference (FilterList[i]);
            }
            ExFreePoolWithTag(FilterList, POOL_TAG);
        }
    }
    return status;
}
Пример #13
0
NTSTATUS KphHashFile(
    __in PUNICODE_STRING FileName,
    __out PVOID *Hash,
    __out PULONG HashSize
    )
{
    NTSTATUS status;
    BCRYPT_ALG_HANDLE hashAlgHandle = NULL;
    ULONG querySize;
    ULONG hashObjectSize;
    ULONG hashSize;
    PVOID hashObject = NULL;
    PVOID hash = NULL;
    BCRYPT_HASH_HANDLE hashHandle = NULL;
    OBJECT_ATTRIBUTES objectAttributes;
    IO_STATUS_BLOCK iosb;
    HANDLE fileHandle = NULL;
    FILE_STANDARD_INFORMATION standardInfo;
    ULONG remainingBytes;
    ULONG bytesToRead;
    PVOID buffer = NULL;

    PAGED_CODE();

    // Open the hash algorithm and allocate memory for the hash object.

    if (!NT_SUCCESS(status = BCryptOpenAlgorithmProvider(&hashAlgHandle, KPH_HASH_ALGORITHM, NULL, 0)))
        goto CleanupExit;
    if (!NT_SUCCESS(status = BCryptGetProperty(hashAlgHandle, BCRYPT_OBJECT_LENGTH,
        (PUCHAR)&hashObjectSize, sizeof(ULONG), &querySize, 0)))
    {
        goto CleanupExit;
    }
    if (!NT_SUCCESS(status = BCryptGetProperty(hashAlgHandle, BCRYPT_HASH_LENGTH, (PUCHAR)&hashSize,
        sizeof(ULONG), &querySize, 0)))
    {
        goto CleanupExit;
    }

    if (!(hashObject = ExAllocatePoolWithTag(PagedPool, hashObjectSize, 'vhpK')))
    {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto CleanupExit;
    }
    if (!(hash = ExAllocatePoolWithTag(PagedPool, hashSize, 'vhpK')))
    {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto CleanupExit;
    }

    if (!NT_SUCCESS(status = BCryptCreateHash(hashAlgHandle, &hashHandle, hashObject, hashObjectSize,
        NULL, 0, 0)))
    {
        goto CleanupExit;
    }

    // Open the file and compute the hash.

    InitializeObjectAttributes(&objectAttributes, FileName, OBJ_KERNEL_HANDLE, NULL, NULL);

    if (!NT_SUCCESS(status = ZwCreateFile(&fileHandle, FILE_GENERIC_READ, &objectAttributes,
        &iosb, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_OPEN,
        FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0)))
    {
        goto CleanupExit;
    }

    if (!NT_SUCCESS(status = ZwQueryInformationFile(fileHandle, &iosb, &standardInfo,
        sizeof(FILE_STANDARD_INFORMATION), FileStandardInformation)))
    {
        goto CleanupExit;
    }

    if (standardInfo.EndOfFile.QuadPart <= 0)
    {
        status = STATUS_UNSUCCESSFUL;
        goto CleanupExit;
    }
    if (standardInfo.EndOfFile.QuadPart > FILE_MAX_SIZE)
    {
        status = STATUS_FILE_TOO_LARGE;
        goto CleanupExit;
    }

    if (!(buffer = ExAllocatePoolWithTag(PagedPool, FILE_BUFFER_SIZE, 'vhpK')))
    {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto CleanupExit;
    }

    remainingBytes = (ULONG)standardInfo.EndOfFile.QuadPart;

    while (remainingBytes != 0)
    {
        bytesToRead = FILE_BUFFER_SIZE;
        if (bytesToRead > remainingBytes)
            bytesToRead = remainingBytes;

        if (!NT_SUCCESS(status = ZwReadFile(fileHandle, NULL, NULL, NULL, &iosb, buffer, bytesToRead,
            NULL, NULL)))
        {
            goto CleanupExit;
        }
        if ((ULONG)iosb.Information != bytesToRead)
        {
            status = STATUS_INTERNAL_ERROR;
            goto CleanupExit;
        }

        if (!NT_SUCCESS(status = BCryptHashData(hashHandle, buffer, bytesToRead, 0)))
            goto CleanupExit;

        remainingBytes -= bytesToRead;
    }

    if (!NT_SUCCESS(status = BCryptFinishHash(hashHandle, hash, hashSize, 0)))
        goto CleanupExit;

    if (NT_SUCCESS(status))
    {
        *Hash = hash;
        *HashSize = hashSize;

        hash = NULL; // Don't free this in the cleanup section
    }

CleanupExit:
    if (buffer)
        ExFreePoolWithTag(buffer, 'vhpK');
    if (fileHandle)
        ZwClose(fileHandle);
    if (hashHandle)
        BCryptDestroyHash(hashHandle);
    if (hash)
        ExFreePoolWithTag(hash, 'vhpK');
    if (hashObject)
        ExFreePoolWithTag(hashObject, 'vhpK');
    if (hashAlgHandle)
        BCryptCloseAlgorithmProvider(hashAlgHandle, 0);

    return status;
}
Пример #14
0
NTSTATUS
CreateSdpRecord(
    _In_ PBTHDDI_SDP_NODE_INTERFACE SdpNodeInterface,
    _In_ PBTHDDI_SDP_PARSE_INTERFACE SdpParseInterface,
    _In_ const GUID * ClassId,
    _In_ LPWSTR Name,
    _In_ USHORT Psm,
    _Out_ PUCHAR * Stream,
    _Out_ ULONG * Size
    )
/*++

Description:

    Create server SDP record

Arguments:

    SdpNodeInterface - Node interface that we obtained from bth stack
    SdpParseInterface - Parse interface that we obtained from bth stack
    ClassId - Service Class ID to publish
    Name - Service name to publish
    Psm - Server PSM
    Stream - receives the sdp record stream
    Size - receives size of sdp record stream

Return Value:

    NTSTATUS Status code.

--*/
{
    NTSTATUS status;
    PSDP_TREE_ROOT_NODE tree = NULL;
    PSDP_NODE seqClsIdList, seqProto, seqLang; 
    PSDP_NODE nodeName = NULL, nodeDesc = NULL, nodeProto; 
    UNICODE_STRING unicodeStrName;
    ANSI_STRING ansiStrName;
    PUCHAR stream = NULL;
    ULONG size;
    ULONG_PTR errorByte = 0;

    RtlInitUnicodeString(&unicodeStrName, Name);
    RtlInitAnsiString(&ansiStrName, NULL);

    status = RtlUnicodeStringToAnsiString(&ansiStrName, &unicodeStrName, TRUE);
    if (!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_SDP, 
            "Creating ANSI string for service name failed, Status code %!STATUS!\n", status);

        ansiStrName.Length = 0;
        goto exit;
    }
        
    tree = SdpNodeInterface->SdpCreateNodeTree(
        POOLTAG_BTHECHOSAMPLE
        );

    if (NULL == tree)
    {
        status = STATUS_INSUFFICIENT_RESOURCES;

        TraceEvents(TRACE_LEVEL_ERROR, DBG_SDP, 
            "SdpCreateNodeTree failed, returning Status code %!STATUS!\n", status);
        
        goto exit;
    }

    //
    // Add ClassIdList attribute
    //

    status = AddSeqAttribute(SdpNodeInterface, tree, SDP_ATTRIB_CLASS_ID_LIST, &seqClsIdList);
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    status = AppendNodeUuid128(SdpNodeInterface, seqClsIdList, ClassId);
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    //
    // Add protocols
    //

    //
    // L2CAP
    //
    status = AddSeqAttribute(SdpNodeInterface, tree, SDP_ATTRIB_PROTOCOL_DESCRIPTOR_LIST, &seqProto);
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    status = AppendSeqNode(SdpNodeInterface, seqProto, &nodeProto);
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }
    
    status = AppendNodeUuid16(SdpNodeInterface, nodeProto, L2CAP_PROTOCOL_UUID16);
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    status = AppendNodeUint16(SdpNodeInterface, nodeProto, Psm);
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    //
    // SDP
    //

    status = AppendSeqNode(SdpNodeInterface, seqProto, &nodeProto);
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    status = AppendNodeUuid16(SdpNodeInterface, nodeProto, SDP_PROTOCOL_UUID16);            
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    //
    // Add lang attributes
    //
    status = AddSeqAttribute(SdpNodeInterface, tree, SDP_ATTRIB_LANG_BASE_ATTRIB_ID_LIST, &seqLang);
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    status = AppendNodeUint16(SdpNodeInterface, seqLang, 0x656e); //TODO: find constants for these           
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }

    status = AppendNodeUint16(SdpNodeInterface, seqLang, 0x006A);            
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }
    
    status = AppendNodeUint16(SdpNodeInterface, seqLang, 0x0100);            
    if (!NT_SUCCESS(status))
    {
        goto exit;
    }
    
    //
    // Add service name
    //

    nodeName = SdpNodeInterface->SdpCreateNodeString(
        ansiStrName.Buffer, 
        ansiStrName.Length, 
        POOLTAG_BTHECHOSAMPLE
        );
    if(NULL == nodeName)
    {
        status = STATUS_INSUFFICIENT_RESOURCES;

        TraceEvents(TRACE_LEVEL_ERROR, DBG_SDP, 
            "Creating node for service name failed, Status code %!STATUS!\n", status);

        goto exit;
    }
    
    status = SdpNodeInterface->SdpAddAttributeToTree(
        tree, 
        LANG_DEFAULT_ID+STRING_NAME_OFFSET, 
        nodeName, 
        POOLTAG_BTHECHOSAMPLE
        );
    if(!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_SDP, 
            "SdpAddAttributeToTree for service name failed, Status code %!STATUS!\n", status);

        goto exit;
    }

    nodeName = NULL; //transferred owenership to tree
    
    nodeDesc = SdpNodeInterface->SdpCreateNodeString(
        ansiStrName.Buffer, 
        ansiStrName.Length, 
        POOLTAG_BTHECHOSAMPLE
        );
    if(NULL == nodeDesc)
    {
        status = STATUS_INSUFFICIENT_RESOURCES;

        TraceEvents(TRACE_LEVEL_ERROR, DBG_SDP, 
            "Creating node for service desc failed, Status code %!STATUS!\n", status);

        goto exit;
    }
    
    status = SdpNodeInterface->SdpAddAttributeToTree(
        tree, 
        LANG_DEFAULT_ID+STRING_DESCRIPTION_OFFSET, 
        nodeDesc, 
        POOLTAG_BTHECHOSAMPLE
        );
    if(!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_SDP, 
            "SdpAddAttributeToTree for service desc failed, Status code %!STATUS!\n", status);
        
        goto exit;
    }

    nodeDesc = NULL;

    //
    // Create stream from tree
    //

    status = SdpParseInterface->SdpConvertTreeToStream(tree, &stream, &size, POOLTAG_BTHECHOSAMPLE);
    if(!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_SDP, 
            "Failed to get stream from tree for SDP record, Status code %!STATUS!\n", status);
        
        goto exit;
    }

    status = SdpParseInterface->SdpValidateStream(
        stream,
        size,
        &errorByte
        );

    if(!NT_SUCCESS(status))
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_SDP, 
            "Validate stream failed for SDP record, first failure at address %p\n", (PVOID)errorByte);
        
        goto exit;
    }

    *Stream = stream;
    *Size = size;
    
exit:
    if (NULL != tree)
    {
        SdpNodeInterface->SdpFreeTree(tree);
    }

    if (NULL != nodeName)
    {
        //
        // If we failed to add attribute to tree use ExFreePool to free it
        //
        ExFreePool(nodeName);
    }
    
    if (NULL != nodeDesc)
    {
        //
        // If we failed to add attribute to tree use ExFreePool to free it
        //
        ExFreePool(nodeDesc);
    }
    
    RtlFreeAnsiString(&ansiStrName);

    if (!NT_SUCCESS(status))
    {
        if (stream != NULL)
        {
            ExFreePoolWithTag(stream, POOLTAG_BTHECHOSAMPLE);
        }
    }
    
    return status;
}
Пример #15
0
PSECONDARY
Secondary_Create (
	IN  PIRP_CONTEXT			IrpContext,
	IN	PVOLUME_DEVICE_OBJECT	VolDo		 
	)
{
	NTSTATUS			status;
	PSECONDARY			secondary;

	OBJECT_ATTRIBUTES	objectAttributes;
	LARGE_INTEGER		timeOut;
	ULONG				tryQuery;
	BOOLEAN				isLocalAddress;
	

	UNREFERENCED_PARAMETER( IrpContext );

	secondary = ExAllocatePoolWithTag( NonPagedPool, sizeof(SECONDARY), NDASNTFS_ALLOC_TAG );
	
	if (secondary == NULL) {

		ASSERT( NDASNTFS_INSUFFICIENT_RESOURCES );
		return NULL;
	}
	
	RtlZeroMemory( secondary, sizeof(SECONDARY) );

#define MAX_TRY_QUERY 2

	for (tryQuery = 0; tryQuery < MAX_TRY_QUERY; tryQuery++) {

		status = ((PVOLUME_DEVICE_OBJECT) NdasNtfsFileSystemDeviceObject)->
			NdfsCallback.QueryPrimaryAddress( &VolDo->NetdiskPartitionInformation, &secondary->PrimaryAddress, &isLocalAddress );

		DebugTrace2( 0, Dbg2, ("Secondary_Create: QueryPrimaryAddress %08x\n", status) );

		if (NT_SUCCESS(status)) {

			DebugTrace2( 0, Dbg2, ("Secondary_Create: QueryPrimaryAddress: Found PrimaryAddress :%02x:%02x:%02x:%02x:%02x:%02x/%d\n",
				secondary->PrimaryAddress.Node[0], secondary->PrimaryAddress.Node[1],
				secondary->PrimaryAddress.Node[2], secondary->PrimaryAddress.Node[3],
				secondary->PrimaryAddress.Node[4], secondary->PrimaryAddress.Node[5],
				NTOHS(secondary->PrimaryAddress.Port)) );
			break;
		}
	}

	if (status != STATUS_SUCCESS || isLocalAddress) {

		ExFreePoolWithTag( secondary, NDASNTFS_ALLOC_TAG );
		return NULL;
	}

	secondary->Flags = SECONDARY_FLAG_INITIALIZING;

#if 0
	ExInitializeResourceLite( &secondary->RecoveryResource );
	ExInitializeResourceLite( &secondary->Resource );
	ExInitializeResourceLite( &secondary->SessionResource );
	ExInitializeResourceLite( &secondary->CreateResource );
#endif

	ExInitializeFastMutex( &secondary->FastMutex );

	secondary->ReferenceCount = 1;

	VolDo_Reference( VolDo );
	secondary->VolDo = VolDo;

	secondary->ThreadHandle = NULL;

	InitializeListHead( &secondary->RecoveryCcbQueue );
    ExInitializeFastMutex( &secondary->RecoveryCcbQMutex );

	InitializeListHead( &secondary->DeletedFcbQueue );

	KeQuerySystemTime( &secondary->TryCloseTime );

	secondary->TryCloseWorkItem = IoAllocateWorkItem( (PDEVICE_OBJECT)VolDo );

	KeInitializeEvent( &secondary->ReadyEvent, NotificationEvent, FALSE );
    
	InitializeListHead( &secondary->RequestQueue );
	KeInitializeSpinLock( &secondary->RequestQSpinLock );
	KeInitializeEvent( &secondary->RequestEvent, NotificationEvent, FALSE );

#if 0
	////////////////////////////////////////
	InitializeListHead( &secondary->FcbQueue );
	ExInitializeFastMutex( &secondary->FcbQMutex );
	/////////////////////////////////////////
#endif

	KeInitializeEvent( &secondary->RecoveryReadyEvent, NotificationEvent, FALSE );

	InitializeObjectAttributes( &objectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL );

	secondary->SessionId = 0;
	
	status = PsCreateSystemThread( &secondary->ThreadHandle,
								   THREAD_ALL_ACCESS,
								   &objectAttributes,
								   NULL,
								   NULL,
								   SecondaryThreadProc,
								   secondary );

	if (!NT_SUCCESS(status)) {

		ASSERT( NDASNTFS_UNEXPECTED );
		Secondary_Close( secondary );
		
		return NULL;
	}

	status = ObReferenceObjectByHandle( secondary->ThreadHandle,
										FILE_READ_DATA,
										NULL,
										KernelMode,
										&secondary->ThreadObject,
										NULL );

	if (!NT_SUCCESS(status)) {

		ASSERT( NDASNTFS_INSUFFICIENT_RESOURCES );
		Secondary_Close( secondary );
		
		return NULL;
	}

	secondary->SessionId ++;

	timeOut.QuadPart = -NDASNTFS_TIME_OUT;		
	status = KeWaitForSingleObject( &secondary->ReadyEvent,
									Executive,
									KernelMode,
									FALSE,
									&timeOut );

	if (status != STATUS_SUCCESS) {
	
		NDAS_ASSERT( FALSE );
		Secondary_Close( secondary );
		
		return NULL;
	}

	KeClearEvent( &secondary->ReadyEvent );

	ExAcquireFastMutex( &secondary->FastMutex );

	if (!FlagOn(secondary->Thread.Flags, SECONDARY_THREAD_FLAG_START) ||
		FlagOn(secondary->Thread.Flags, SECONDARY_THREAD_FLAG_STOPED)) {

		if (secondary->Thread.SessionStatus != STATUS_DISK_CORRUPT_ERROR &&
			secondary->Thread.SessionStatus != STATUS_UNRECOGNIZED_VOLUME) {
	
			ExReleaseFastMutex( &secondary->FastMutex );

			Secondary_Close( secondary );
			return NULL;
		}
	} 

	ASSERT( secondary->Thread.SessionContext.SessionSlotCount != 0 );

	ClearFlag( secondary->Flags, SECONDARY_FLAG_INITIALIZING );
	SetFlag( secondary->Flags, SECONDARY_FLAG_START );

	ExReleaseFastMutex( &secondary->FastMutex );

	DebugTrace2( 0, Dbg2,
				("Secondary_Create: The client thread are ready secondary = %p\n", secondary) );

	return secondary;
}
Пример #16
0
NTSTATUS NTAPI
IopQueryDeviceDescription(
   PIO_QUERY Query,
   UNICODE_STRING RootKey,
   HANDLE RootKeyHandle,
   ULONG Bus,
   PKEY_VALUE_FULL_INFORMATION *BusInformation)
{
   NTSTATUS Status = STATUS_SUCCESS;

   /* Controller Stuff */
   UNICODE_STRING ControllerString;
   UNICODE_STRING ControllerRootRegName = RootKey;
   UNICODE_STRING ControllerRegName;
   HANDLE ControllerKeyHandle;
   PKEY_FULL_INFORMATION ControllerFullInformation = NULL;
   PKEY_VALUE_FULL_INFORMATION ControllerInformation[3] = {NULL, NULL, NULL};
   ULONG ControllerNumber;
   ULONG ControllerLoop;
   ULONG MaximumControllerNumber;

   /* Peripheral Stuff */
   UNICODE_STRING PeripheralString;
   HANDLE PeripheralKeyHandle;
   PKEY_FULL_INFORMATION PeripheralFullInformation;
   PKEY_VALUE_FULL_INFORMATION PeripheralInformation[3] = {NULL, NULL, NULL};
   ULONG PeripheralNumber;
   ULONG PeripheralLoop;
   ULONG MaximumPeripheralNumber;

   /* Global Registry Stuff */
   OBJECT_ATTRIBUTES ObjectAttributes;
   ULONG LenFullInformation;
   ULONG LenKeyFullInformation;
   UNICODE_STRING TempString;
   WCHAR TempBuffer[14];
   PWSTR Strings[3] = {
      L"Identifier",
      L"Configuration Data",
      L"Component Information"
   };

   /* Temporary String */
   TempString.MaximumLength = sizeof(TempBuffer);
   TempString.Length = 0;
   TempString.Buffer = TempBuffer;

   /* Add Controller Name to String */
   RtlAppendUnicodeToString(&ControllerRootRegName, L"\\");
   RtlAppendUnicodeToString(&ControllerRootRegName, ArcTypes[*Query->ControllerType]);

   /* Set the Controller Number if specified */
   if (Query->ControllerNumber && *(Query->ControllerNumber))
   {
      ControllerNumber = *Query->ControllerNumber;
      MaximumControllerNumber = ControllerNumber + 1;
   } else {
      /* Find out how many Controller Numbers there are */
      InitializeObjectAttributes(
         &ObjectAttributes,
         &ControllerRootRegName,
         OBJ_CASE_INSENSITIVE,
         NULL,
         NULL);

      Status = ZwOpenKey(&ControllerKeyHandle, KEY_READ, &ObjectAttributes);
      if (NT_SUCCESS(Status))
      {
         /* How much buffer space */
         ZwQueryKey(ControllerKeyHandle, KeyFullInformation, NULL, 0, &LenFullInformation);

         /* Allocate it */
         ControllerFullInformation = ExAllocatePoolWithTag(PagedPool, LenFullInformation, TAG_IO_RESOURCE);

         /* Get the Information */
         Status = ZwQueryKey(ControllerKeyHandle, KeyFullInformation, ControllerFullInformation, LenFullInformation, &LenFullInformation);
         ZwClose(ControllerKeyHandle);
         ControllerKeyHandle = NULL;
      }

      /* No controller was found, go back to function. */
      if (!NT_SUCCESS(Status))
      {
         if (ControllerFullInformation != NULL)
            ExFreePoolWithTag(ControllerFullInformation, TAG_IO_RESOURCE);
         return Status;
      }

      /* Find out Controller Numbers */
      ControllerNumber = 0;
      MaximumControllerNumber = ControllerFullInformation->SubKeys;

      /* Free Memory */
      ExFreePoolWithTag(ControllerFullInformation, TAG_IO_RESOURCE);
      ControllerFullInformation = NULL;
   }

   /* Save String */
   ControllerRegName = ControllerRootRegName;

   /* Loop through controllers */
   for (; ControllerNumber < MaximumControllerNumber; ControllerNumber++)
   {
      /* Load String */
      ControllerRootRegName = ControllerRegName;

      /* Controller Number to Registry String */
      Status = RtlIntegerToUnicodeString(ControllerNumber, 10, &TempString);

      /* Create String */
      Status |= RtlAppendUnicodeToString(&ControllerRootRegName, L"\\");
      Status |= RtlAppendUnicodeStringToString(&ControllerRootRegName, &TempString);

      /* Something messed up */
      if (!NT_SUCCESS(Status)) break;

      /* Open the Registry Key */
      InitializeObjectAttributes(
         &ObjectAttributes,
         &ControllerRootRegName,
         OBJ_CASE_INSENSITIVE,
         NULL,
         NULL);

      Status = ZwOpenKey(&ControllerKeyHandle, KEY_READ, &ObjectAttributes);

      /* Read the Configuration Data... */
      if (NT_SUCCESS(Status))
      {
         for (ControllerLoop = 0; ControllerLoop < 3; ControllerLoop++)
         {
            /* Identifier String First */
            RtlInitUnicodeString(&ControllerString, Strings[ControllerLoop]);

            /* How much buffer space */
            Status = ZwQueryValueKey(ControllerKeyHandle, &ControllerString, KeyValueFullInformation, NULL, 0, &LenKeyFullInformation);

            if (!NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL && Status != STATUS_BUFFER_OVERFLOW)
               continue;

            /* Allocate it */
            ControllerInformation[ControllerLoop] = ExAllocatePoolWithTag(PagedPool, LenKeyFullInformation, TAG_IO_RESOURCE);

            /* Get the Information */
            Status = ZwQueryValueKey(ControllerKeyHandle, &ControllerString, KeyValueFullInformation, ControllerInformation[ControllerLoop], LenKeyFullInformation, &LenKeyFullInformation);
         }

         /* Clean Up */
         ZwClose(ControllerKeyHandle);
         ControllerKeyHandle = NULL;
      }

      /* Something messed up */
      if (!NT_SUCCESS(Status))
         goto EndLoop;

      /* We now have Bus *AND* Controller Information.. is it enough? */
      if (!Query->PeripheralType || !(*Query->PeripheralType))
      {
         Status = Query->CalloutRoutine(
            Query->Context,
            &ControllerRootRegName,
            *Query->BusType,
            Bus,
            BusInformation,
            *Query->ControllerType,
            ControllerNumber,
            ControllerInformation,
            0,
            0,
            NULL);
         goto EndLoop;
      }

      /* Not enough...caller also wants peripheral name */
      Status = RtlAppendUnicodeToString(&ControllerRootRegName, L"\\");
      Status |= RtlAppendUnicodeToString(&ControllerRootRegName, ArcTypes[*Query->PeripheralType]);

      /* Something messed up */
      if (!NT_SUCCESS(Status)) goto EndLoop;

      /* Set the Peripheral Number if specified */
      if (Query->PeripheralNumber && *Query->PeripheralNumber)
      {
         PeripheralNumber = *Query->PeripheralNumber;
         MaximumPeripheralNumber = PeripheralNumber + 1;
      } else {
         /* Find out how many Peripheral Numbers there are */
         InitializeObjectAttributes(
            &ObjectAttributes,
            &ControllerRootRegName,
            OBJ_CASE_INSENSITIVE,
            NULL,
            NULL);

         Status = ZwOpenKey(&PeripheralKeyHandle, KEY_READ, &ObjectAttributes);

         if (NT_SUCCESS(Status))
         {
            /* How much buffer space */
            ZwQueryKey(PeripheralKeyHandle, KeyFullInformation, NULL, 0, &LenFullInformation);

            /* Allocate it */
            PeripheralFullInformation = ExAllocatePoolWithTag(PagedPool, LenFullInformation, TAG_IO_RESOURCE);

            /* Get the Information */
            Status = ZwQueryKey(PeripheralKeyHandle, KeyFullInformation, PeripheralFullInformation, LenFullInformation, &LenFullInformation);
            ZwClose(PeripheralKeyHandle);
            PeripheralKeyHandle = NULL;
         }

         /* No controller was found, go back to function but clean up first */
         if (!NT_SUCCESS(Status))
         {
            Status = STATUS_SUCCESS;
            goto EndLoop;
         }

         /* Find out Peripheral Number */
         PeripheralNumber = 0;
         MaximumPeripheralNumber = PeripheralFullInformation->SubKeys;

         /* Free Memory */
         ExFreePoolWithTag(PeripheralFullInformation, TAG_IO_RESOURCE);
         PeripheralFullInformation = NULL;
      }

      /* Save Name */
      ControllerRegName = ControllerRootRegName;

      /* Loop through Peripherals */
      for (; PeripheralNumber < MaximumPeripheralNumber; PeripheralNumber++)
      {
         /* Restore Name */
         ControllerRootRegName = ControllerRegName;

         /* Peripheral Number to Registry String */
         Status = RtlIntegerToUnicodeString(PeripheralNumber, 10, &TempString);

         /* Create String */
         Status |= RtlAppendUnicodeToString(&ControllerRootRegName, L"\\");
         Status |= RtlAppendUnicodeStringToString(&ControllerRootRegName, &TempString);

         /* Something messed up */
         if (!NT_SUCCESS(Status)) break;

         /* Open the Registry Key */
         InitializeObjectAttributes(
            &ObjectAttributes,
            &ControllerRootRegName,
            OBJ_CASE_INSENSITIVE,
            NULL,
            NULL);

         Status = ZwOpenKey(&PeripheralKeyHandle, KEY_READ, &ObjectAttributes);

         if (NT_SUCCESS(Status))
         {
            for (PeripheralLoop = 0; PeripheralLoop < 3; PeripheralLoop++)
            {
               /* Identifier String First */
               RtlInitUnicodeString(&PeripheralString, Strings[PeripheralLoop]);

               /* How much buffer space */
               Status = ZwQueryValueKey(PeripheralKeyHandle, &PeripheralString, KeyValueFullInformation, NULL, 0, &LenKeyFullInformation);

               if (!NT_SUCCESS(Status) && Status != STATUS_BUFFER_TOO_SMALL && Status != STATUS_BUFFER_OVERFLOW)
               {
                 PeripheralInformation[PeripheralLoop] = NULL;
                 continue;
               }

               /* Allocate it */
               PeripheralInformation[PeripheralLoop] = ExAllocatePoolWithTag(PagedPool, LenKeyFullInformation, TAG_IO_RESOURCE);

               /* Get the Information */
               Status = ZwQueryValueKey(PeripheralKeyHandle, &PeripheralString, KeyValueFullInformation, PeripheralInformation[PeripheralLoop], LenKeyFullInformation, &LenKeyFullInformation);
            }

            /* Clean Up */
            ZwClose(PeripheralKeyHandle);
            PeripheralKeyHandle = NULL;

            /* We now have everything the caller could possibly want */
            if (NT_SUCCESS(Status))
            {
               Status = Query->CalloutRoutine(
                  Query->Context,
                  &ControllerRootRegName,
                  *Query->BusType,
                  Bus,
                  BusInformation,
                  *Query->ControllerType,
                  ControllerNumber,
                  ControllerInformation,
                  *Query->PeripheralType,
                  PeripheralNumber,
                  PeripheralInformation);
            }

            /* Free the allocated memory */
            for (PeripheralLoop = 0; PeripheralLoop < 3; PeripheralLoop++)
            {
               if (PeripheralInformation[PeripheralLoop])
               {
                  ExFreePoolWithTag(PeripheralInformation[PeripheralLoop], TAG_IO_RESOURCE);
                  PeripheralInformation[PeripheralLoop] = NULL;
               }
            }

            /* Something Messed up */
            if (!NT_SUCCESS(Status)) break;
         }
      }

EndLoop:
      /* Free the allocated memory */
      for (ControllerLoop = 0; ControllerLoop < 3; ControllerLoop++)
      {
         if (ControllerInformation[ControllerLoop])
         {
            ExFreePoolWithTag(ControllerInformation[ControllerLoop], TAG_IO_RESOURCE);
            ControllerInformation[ControllerLoop] = NULL;
         }
      }

      /* Something Messed up */
      if (!NT_SUCCESS(Status)) break;
   }

   return Status;
}
Пример #17
0
//2006/3/7 support Choice Full Speed Bandwidth
NTSTATUS UsbDev::SelectUsbBandwidth(PINT pSelectedBandwidth, BOOL fHasAudio)
{
 	NTSTATUS ntStatus=STATUS_SUCCESS;
    PIRP irp;
    KEVENT event;
    IO_STATUS_BLOCK ioStatus;
    PIO_STACK_LOCATION nextStack;
	PUSB_BUS_NOTIFICATION pBandwidthInfo;
	LARGE_INTEGER timeout = {(ULONG)(USB_COMMAND_TIMEOUT * 1000 * -10), -1};
	UINT AudioBandwidth=0;
	UINT AvailableBandwidth;

	DBGU_TRACE ( "UsbDev::SelectUsbBandwidth\n");

	if (fHasAudio)
		AudioBandwidth = 64;
	
	// ISO0, ISO1, ISO2, ISO3, ISO4, ISO5, ISO6, ISO7, ISO8
	UINT Bandwith_Require[] = { 0, 128, 256, 384, 512, 680, 800, 900, 1023};

	//2006/3/14 check pSelectedBandwidth
	if (pSelectedBandwidth == NULL) return STATUS_UNSUCCESSFUL;

	//2006/03/22 free bandwidth before query it
	ntStatus = SetAlternate(0,0);
	
	if (!NT_SUCCESS(ntStatus))
		return ntStatus;

//    if((pBandwidthInfo = (PUSB_BUS_NOTIFICATION)ExAllocatePoolWithTag(NonPagedPool, sizeof(USB_BUS_NOTIFICATION), USBDEV_POOLTAG))==NULL)
//		return STATUS_UNSUCCESSFUL;

    pBandwidthInfo = (PUSB_BUS_NOTIFICATION)ExAllocatePoolWithTag(NonPagedPool, sizeof(USB_BUS_NOTIFICATION), USBDEV_POOLTAG);
	if(pBandwidthInfo==NULL)
	{	
		DBGU_TRACE ( "pBandwidthInfo == NULL\n");
		return STATUS_UNSUCCESSFUL;
	}

	memset(pBandwidthInfo, 0, sizeof(USB_BUS_NOTIFICATION));
	pBandwidthInfo->NotificationType = AcquireBusInfo;

    //
    // issue a synchronous request
    //

    KeInitializeEvent(&event, SynchronizationEvent, FALSE);

    irp = IoBuildDeviceIoControlRequest(
            IOCTL_INTERNAL_USB_GET_BUS_INFO,
            m_pLdo,
            NULL,
            0,
            NULL,
            0,
            TRUE, 
            &event,
            &ioStatus);

    if (irp == NULL ) {
		if (pBandwidthInfo)
			ExFreePoolWithTag(pBandwidthInfo,USBDEV_POOLTAG);
        return STATUS_UNSUCCESSFUL;
    }

    //
    // Call the class driver to perform the operation.  If the returned status
    // is PENDING, wait for the request to complete.
    //

    nextStack= IoGetNextIrpStackLocation(irp);

	 if (nextStack == NULL ) {
		if (pBandwidthInfo)
			ExFreePoolWithTag(pBandwidthInfo,USBDEV_POOLTAG);
        return STATUS_UNSUCCESSFUL;
    }

    //
    // pass the URB to the USB driver stack
    //
    nextStack->Parameters.Others.Argument1 = pBandwidthInfo;

    ntStatus= IoCallDriver(m_pLdo,irp);

    DBGU_TRACE ("return from IoCallDriver USBD %x\n", ntStatus);

    if (ntStatus == STATUS_PENDING) {

        DBGU_TRACE ( "Wait for single object\n");

        ntStatus = KeWaitForSingleObject(&event,
                                       Executive,
                                       KernelMode,
                                       FALSE,
                                       &timeout);

        if (ntStatus == STATUS_TIMEOUT) {                        //
            //
            // USBD did not complete this request in 30 milliseconds, assume
            // that the USBD is hung and return an
            // error.                        
            //
			if (pBandwidthInfo)
				ExFreePoolWithTag(pBandwidthInfo,USBDEV_POOLTAG);
            return(STATUS_UNSUCCESSFUL);                    
        }

        DBGU_TRACE ("Wait for single object, returned %x\n", ntStatus);
        
    } else {
        ioStatus.Status = ntStatus;
    }

    //
    // USBD maps the error code for us
    //
    ntStatus = ioStatus.Status;

	if(ntStatus == STATUS_SUCCESS)
	{
		DBGU_TRACE ("System Usb Total Bandwidth is %d, ConsumedBandwidth is %d\n",pBandwidthInfo->TotalBandwidth, pBandwidthInfo->ConsumedBandwidth);
		AvailableBandwidth = (pBandwidthInfo->TotalBandwidth - pBandwidthInfo->ConsumedBandwidth)/10 - AudioBandwidth;
		DBGU_TRACE ("System Usb Available ISO Bandwidth is %d bytes\n",AvailableBandwidth);
		
		for(int i=8; i > 0 ; i--)
		{
			if (AvailableBandwidth > Bandwith_Require[i])
			{
				*pSelectedBandwidth = i;
				break;
			}
		}
	}
	
	if (pBandwidthInfo)
		ExFreePoolWithTag(pBandwidthInfo,USBDEV_POOLTAG);

    return ntStatus;
}
Пример #18
0
/*
 * @implemented
 */
NTSTATUS
NTAPI
Ke386CallBios(IN ULONG Int,
              OUT PCONTEXT Context)
{
    PUCHAR Trampoline = (PUCHAR)TRAMPOLINE_BASE;
    PTEB VdmTeb = (PTEB)TRAMPOLINE_TEB;
    PVDM_TIB VdmTib = (PVDM_TIB)TRAMPOLINE_TIB;
    ULONG ContextSize = FIELD_OFFSET(CONTEXT, ExtendedRegisters);
    PKTHREAD Thread = KeGetCurrentThread();
    PKTSS Tss = KeGetPcr()->TSS;
    PKPROCESS Process = Thread->ApcState.Process;
    PVDM_PROCESS_OBJECTS VdmProcessObjects;
    USHORT OldOffset, OldBase;

    /* Start with a clean TEB */
    RtlZeroMemory(VdmTeb, sizeof(TEB));

    /* Write the interrupt and bop */
    *Trampoline++ = 0xCD;
    *Trampoline++ = (UCHAR)Int;
    *(PULONG)Trampoline = TRAMPOLINE_BOP;

    /* Setup the VDM TEB and TIB */
    VdmTeb->Vdm = (PVOID)TRAMPOLINE_TIB;
    RtlZeroMemory(VdmTib, sizeof(VDM_TIB));
    VdmTib->Size = sizeof(VDM_TIB);

    /* Set a blank VDM state */
    *VdmState = 0;

    /* Copy the context */
    RtlCopyMemory(&VdmTib->VdmContext, Context, ContextSize);
    VdmTib->VdmContext.SegCs = (ULONG_PTR)Trampoline >> 4;
    VdmTib->VdmContext.SegSs = (ULONG_PTR)Trampoline >> 4;
    VdmTib->VdmContext.Eip = 0;
    VdmTib->VdmContext.Esp = 2 * PAGE_SIZE - sizeof(ULONG_PTR);
    VdmTib->VdmContext.EFlags |= EFLAGS_V86_MASK | EFLAGS_INTERRUPT_MASK;
    VdmTib->VdmContext.ContextFlags = CONTEXT_FULL;

    /* This can't be a real VDM process */
    ASSERT(PsGetCurrentProcess()->VdmObjects == NULL);

    /* Allocate VDM structure */
    VdmProcessObjects = ExAllocatePoolWithTag(NonPagedPool,
                                              sizeof(VDM_PROCESS_OBJECTS),
                                              '  eK');
    if (!VdmProcessObjects) return STATUS_NO_MEMORY;

    /* Set it up */
    RtlZeroMemory(VdmProcessObjects, sizeof(VDM_PROCESS_OBJECTS));
    VdmProcessObjects->VdmTib = VdmTib;
    PsGetCurrentProcess()->VdmObjects = VdmProcessObjects;

    /* Set the system affinity for the current thread */
    KeSetSystemAffinityThread(1);

    /* Make sure there's space for two IOPMs, then copy & clear the current */
    ASSERT(((PKIPCR)KeGetPcr())->GDT[KGDT_TSS / 8].LimitLow >=
            (0x2000 + IOPM_OFFSET - 1));
    RtlCopyMemory(Ki386IopmSaveArea, &Tss->IoMaps[0].IoMap, PAGE_SIZE * 2);
    RtlZeroMemory(&Tss->IoMaps[0].IoMap, PAGE_SIZE * 2);

    /* Save the old offset and base, and set the new ones */
    OldOffset = Process->IopmOffset;
    OldBase = Tss->IoMapBase;
    Process->IopmOffset = (USHORT)IOPM_OFFSET;
    Tss->IoMapBase = (USHORT)IOPM_OFFSET;

    /* Switch stacks and work the magic */
    Ki386SetupAndExitToV86Mode(VdmTeb);

    /* Restore IOPM */
    RtlCopyMemory(&Tss->IoMaps[0].IoMap, Ki386IopmSaveArea, PAGE_SIZE * 2);
    Process->IopmOffset = OldOffset;
    Tss->IoMapBase = OldBase;

    /* Restore affinity */
    KeRevertToUserAffinityThread();

    /* Restore context */
    RtlCopyMemory(Context, &VdmTib->VdmContext, ContextSize);
    Context->ContextFlags = CONTEXT_FULL;

    /* Free VDM objects */
    ExFreePoolWithTag(PsGetCurrentProcess()->VdmObjects, '  eK');
    PsGetCurrentProcess()->VdmObjects = NULL;

    /* Return status */
    return STATUS_SUCCESS;
}
Пример #19
0
// Get Usb Configuration Descriptor
NTSTATUS UsbDev::GetConfigurationDescriptor()
{
	NTSTATUS						ntStatus = STATUS_SUCCESS;
    PURB							pUrb;
    ULONG							siz;
	UCHAR							index;
	PUSB_CONFIGURATION_DESCRIPTOR	pTemp_pConfigDesc = NULL;

	DBGU_TRACE(">>>UsbDev::GetConfigurationDescriptor !\n");
	pUrb = (PURB) ExAllocatePoolWithTag(NonPagedPool, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST), USBDEV_POOLTAG);

	if(pUrb)
	{//pUrb != NULL	
		RtlZeroMemory(pUrb, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST));

		for(index=0;index<m_DevDesc.bNumConfigurations;index++)
		{//travel all configurations
			siz = 64;
get_config_descriptor_retry:
			if(pTemp_pConfigDesc) ExFreePoolWithTag(pTemp_pConfigDesc,USBDEV_POOLTAG);

			if ((pTemp_pConfigDesc = (PUSB_CONFIGURATION_DESCRIPTOR) ExAllocatePoolWithTag(NonPagedPool, siz, USBDEV_POOLTAG)))
			{//pTemp_pConfigDesc != NULL
				RtlZeroMemory(pTemp_pConfigDesc,siz);
				UsbBuildGetDescriptorRequest(
					pUrb,
					(USHORT) sizeof (struct _URB_CONTROL_DESCRIPTOR_REQUEST),
					USB_CONFIGURATION_DESCRIPTOR_TYPE,
					index,
					0,
					pTemp_pConfigDesc,
					NULL,
					siz,
					NULL);
				ntStatus = SendAwaitUrb(pUrb);

				if(!NT_SUCCESS(ntStatus))
				{//ntStatus != STATUS_SUCCESS
					DBGU_TRACE("ERR: Fail to get configuration descriptor !!\n");
					ExFreePoolWithTag(pTemp_pConfigDesc,USBDEV_POOLTAG);
					ntStatus = STATUS_INSUFFICIENT_RESOURCES;
					break;
				}//ntStatus != STATUS_SUCCESS

				if ((pUrb->UrbControlDescriptorRequest.TransferBufferLength>0) && \
					(pTemp_pConfigDesc->wTotalLength>siz)) 
				{
					siz = pTemp_pConfigDesc->wTotalLength;
					goto get_config_descriptor_retry;
				}

				m_pConfigDesc[index] = pTemp_pConfigDesc;
				pTemp_pConfigDesc = NULL;
				// Print configuration descriptor
				DBGU_TRACE("  Configuration Descriptor: %x\n",index);
				DBGU_TRACE("  -------------------------\n");
				DBGU_TRACE("  bLength %x\n",m_pConfigDesc[index]->bLength);
				DBGU_TRACE("  bDescriptorType %x\n",m_pConfigDesc[index]->bDescriptorType);
				DBGU_TRACE("  wTotalLength %x\n",m_pConfigDesc[index]->wTotalLength);
				DBGU_TRACE("  bNumInterfaces %x\n",m_pConfigDesc[index]->bNumInterfaces);
				DBGU_TRACE("  bConfigurationValue %x\n",m_pConfigDesc[index]->bConfigurationValue);
				DBGU_TRACE("  iConfiguration %x\n",m_pConfigDesc[index]->iConfiguration);
				DBGU_TRACE("  MaxPower %x\n",m_pConfigDesc[index]->MaxPower);
				DBGU_TRACE("  -------------------------\n");
			}//pTemp_pConfigDesc != NULL
			else
			{//pTemp_pConfigDesc == NULL
				DBGU_TRACE("ERR: Fail to allocate memory for m_pConfigDesc !!\n");
				ntStatus = STATUS_INSUFFICIENT_RESOURCES;
				break;
			}//pTemp_pConfigDesc == NULL
		}//travel all configurations
	}//pUrb != NULL	
	else 
	{//pUrb == NULL	
		DBGU_TRACE("ERR: Fail to allocate memory for pUrb !!\n");
		ntStatus = STATUS_INSUFFICIENT_RESOURCES;
	}//pUrb == NULL

	if(pUrb) ExFreePoolWithTag(pUrb,USBDEV_POOLTAG);

    return ntStatus;
}
Пример #20
0
static NTSTATUS
ReadRegistryEntries(
	IN PUNICODE_STRING RegistryPath,
	IN PCLASS_DRIVER_EXTENSION DriverExtension)
{
	UNICODE_STRING ParametersRegistryKey;
	RTL_QUERY_REGISTRY_TABLE Parameters[4];
	NTSTATUS Status;

	ULONG DefaultConnectMultiplePorts = 1;
	ULONG DefaultDataQueueSize = 0x64;
	PCWSTR DefaultDeviceBaseName = L"PointerClass";

	ParametersRegistryKey.Length = 0;
	ParametersRegistryKey.MaximumLength = RegistryPath->Length + sizeof(L"\\Parameters") + sizeof(UNICODE_NULL);
	ParametersRegistryKey.Buffer = ExAllocatePoolWithTag(PagedPool, ParametersRegistryKey.MaximumLength, CLASS_TAG);
	if (!ParametersRegistryKey.Buffer)
	{
		WARN_(CLASS_NAME, "ExAllocatePoolWithTag() failed\n");
		return STATUS_NO_MEMORY;
	}
	RtlCopyUnicodeString(&ParametersRegistryKey, RegistryPath);
	RtlAppendUnicodeToString(&ParametersRegistryKey, L"\\Parameters");
	ParametersRegistryKey.Buffer[ParametersRegistryKey.Length / sizeof(WCHAR)] = UNICODE_NULL;

	RtlZeroMemory(Parameters, sizeof(Parameters));

	Parameters[0].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[0].Name = L"ConnectMultiplePorts";
	Parameters[0].EntryContext = &DriverExtension->ConnectMultiplePorts;
	Parameters[0].DefaultType = REG_DWORD;
	Parameters[0].DefaultData = &DefaultConnectMultiplePorts;
	Parameters[0].DefaultLength = sizeof(ULONG);

	Parameters[1].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[1].Name = L"MouseDataQueueSize";
	Parameters[1].EntryContext = &DriverExtension->DataQueueSize;
	Parameters[1].DefaultType = REG_DWORD;
	Parameters[1].DefaultData = &DefaultDataQueueSize;
	Parameters[1].DefaultLength = sizeof(ULONG);

	Parameters[2].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_REGISTRY_OPTIONAL;
	Parameters[2].Name = L"PointerDeviceBaseName";
	Parameters[2].EntryContext = &DriverExtension->DeviceBaseName;
	Parameters[2].DefaultType = REG_SZ;
	Parameters[2].DefaultData = (PVOID)DefaultDeviceBaseName;
	Parameters[2].DefaultLength = 0;

	Status = RtlQueryRegistryValues(
		RTL_REGISTRY_ABSOLUTE,
		ParametersRegistryKey.Buffer,
		Parameters,
		NULL,
		NULL);

	if (NT_SUCCESS(Status))
	{
		/* Check values */
		if (DriverExtension->ConnectMultiplePorts != 0
			&& DriverExtension->ConnectMultiplePorts != 1)
		{
			DriverExtension->ConnectMultiplePorts = DefaultConnectMultiplePorts;
		}
		if (DriverExtension->DataQueueSize == 0)
		{
			DriverExtension->DataQueueSize = DefaultDataQueueSize;
		}
	}
	else if (Status == STATUS_OBJECT_NAME_NOT_FOUND)
	{
		/* Registry path doesn't exist. Set defaults */
		DriverExtension->ConnectMultiplePorts = DefaultConnectMultiplePorts;
		DriverExtension->DataQueueSize = DefaultDataQueueSize;
		if (RtlCreateUnicodeString(&DriverExtension->DeviceBaseName, DefaultDeviceBaseName))
			Status = STATUS_SUCCESS;
		else
			Status = STATUS_NO_MEMORY;
	}

	ExFreePoolWithTag(ParametersRegistryKey.Buffer, CLASS_TAG);
	return Status;
}
Пример #21
0
// Set the configuration of the usb device.
NTSTATUS UsbDev::SetConfiguration()
{
	NTSTATUS ntStatus = STATUS_SUCCESS;
    PUSBD_INTERFACE_LIST_ENTRY	pTempInterfaceList = NULL, pTempInterfaceList_First = NULL;
	PUSB_CONFIGURATION_DESCRIPTOR pTemp_pConfigDesc = m_pConfigDesc[m_UsbConfigurationNo];
	int i,j,NoOfInterface;
	PUSB_INTERFACE_DESCRIPTOR pTempInterfaceDesc = NULL;
	PURB pUrb = NULL;
	//2010/8/17 03:49下午
	KIRQL oldIrql;
	PUSBD_INTERFACE_INFORMATION interface_temp;
	
	//2010/8/16 06:17下午
	NoOfInterface = pTemp_pConfigDesc->bNumInterfaces;
	DBGU_TRACE(">>>UsbDev::SetConfiguration ! NoOfInterface = %d\n",NoOfInterface);
	pTempInterfaceList_First = pTempInterfaceList = (PUSBD_INTERFACE_LIST_ENTRY) ExAllocatePoolWithTag( NonPagedPool,	sizeof(USBD_INTERFACE_LIST_ENTRY) * (NoOfInterface + 1), USBDEV_POOLTAG);
	
	//2010/8/23 11:51上午
	m_NumberOfInterfaces = NoOfInterface;
	
	if(pTempInterfaceList)
	{// pTempInterfaceList != NULL
		RtlZeroMemory(pTempInterfaceList, sizeof(USBD_INTERFACE_LIST_ENTRY) * (NoOfInterface + 1));

		for(i=0;i<NoOfInterface;i++) 
		{// for loop i
			pTempInterfaceDesc = (PUSB_INTERFACE_DESCRIPTOR) USBD_ParseConfigurationDescriptorEx( 
														m_pConfigDesc[0],		// Pointer to configuration descriptor
														m_pConfigDesc[0],		// Start position
														i,					// Interface number
														-1,//0,					// Alternate setting
														-1,
														-1,
														-1);

			if(!pTempInterfaceDesc)
				break;

			pTempInterfaceList->InterfaceDescriptor = pTempInterfaceDesc;
			pTempInterfaceList++;
		}// for loop i

	    pTempInterfaceList->InterfaceDescriptor = NULL;	// Mark the end of the list
		//pTempInterfaceList = pTempInterfaceList_First; // Pointer to the first entry of the interface list.
		pUrb = USBD_CreateConfigurationRequestEx(pTemp_pConfigDesc, pTempInterfaceList_First);

		if(pUrb) 
		{// pUrb != NULL
			for(i=0;i<NoOfInterface;i++) 
			{// for loop i
				// Set to interface i, alternater 0
				pTempInterfaceList_First[i].Interface->InterfaceNumber	= i;
				pTempInterfaceList_First[i].Interface->AlternateSetting	= 0;	
				DBGU_TRACE("No of endpoints : %d\n", pTempInterfaceList_First[i].InterfaceDescriptor->bNumEndpoints);
				
				for(j=0;j<pTempInterfaceList_First[i].InterfaceDescriptor->bNumEndpoints;j++) 
					pTempInterfaceList_First[i].Interface->Pipes[j].MaximumTransferSize = USBD_DEFAULT_MAXIMUM_TRANSFER_SIZE;
			}// for loop i
			
			//2010/8/24 05:51下午
			interface_temp = &pUrb->UrbSelectConfiguration.Interface;
			
			ntStatus = SendAwaitUrb(pUrb);
			
			if(!NT_SUCCESS(ntStatus)) 
			{// ntStatus != STATUS_SUCCESS
				ntStatus = STATUS_IO_DEVICE_ERROR;
				DBGU_TRACE("Fail to configure usb device !\n");
			}// ntStatus != STATUS_SUCCESS
			else
			{// ntStatus == STATUS_SUCCESS
				m_hConfigureation = pUrb->UrbSelectConfiguration.ConfigurationHandle;
				//Release memory
				//if(m_pInterfaceListEntry)
				{ // m_pInterfaceListEntry != NULL
					for(i=0;i<m_NumberOfInterfaces;i++)
						if(m_pInterface[i])
						{
							ExFreePoolWithTag(m_pInterface[i],USBDEV_POOLTAG);
							m_pInterface[i] = NULL;
							DBGU_TRACE("ExFreePoolWithTag m_pInterface[%d]\n",i);
						}
				//	ExFreePoolWithTag(m_pInterfaceListEntry,USBDEV_POOLTAG);
				//	m_pInterfaceListEntry = NULL;
				} // m_pInterfaceListEntry != NULL
				//2010/8/23 11:51上午
				//m_NumberOfInterfaces = NoOfInterface;
				//Copy interface list
				//m_pInterfaceListEntry = (PUSBD_INTERFACE_LIST_ENTRY) ExAllocatePoolWithTag(NonPagedPool,(m_NumberOfInterfaces * sizeof(USBD_INTERFACE_LIST_ENTRY)), USBDEV_POOLTAG);

				//if(m_pInterfaceListEntry)
				{// m_pInterfaceListEntry != NULL
					
					for(i=0;i<m_NumberOfInterfaces;i++) 
					{//for loop i
						//m_pInterfaceListEntry[i].InterfaceDescriptor = pTempInterfaceList_First[i].InterfaceDescriptor;
#ifdef __VIDEO_CLASS__
						// For Video Class Device
						if (pTempInterfaceList_First[i].Interface->InterfaceNumber==1) // UVC has 2 interfaces
						{
							//2011/5/12 02:22下午
							if(BeST5R286)
								pTempInterfaceList_First[i].Interface->NumberOfPipes = 2;
							else
								pTempInterfaceList_First[i].Interface->NumberOfPipes = 1;
							
							pTempInterfaceList_First[i].Interface->Length = sizeof(USBD_INTERFACE_INFORMATION);
						}

						// james try M2TS.
						if (pTempInterfaceList_First[i].Interface->InterfaceNumber==2)
						{
							pTempInterfaceList_First[i].Interface->NumberOfPipes = 1;
							pTempInterfaceList_First[i].Interface->Length = sizeof(USBD_INTERFACE_INFORMATION);
						}
#endif
						//2010/8/24 05:53下午
//						m_pInterface[i] = (PUSBD_INTERFACE_INFORMATION) ExAllocatePoolWithTag(NonPagedPool, pTempInterfaceList_First[i].Interface->Length, USBDEV_POOLTAG);
						if(BeST5R286)
							m_pInterface[i] = (PUSBD_INTERFACE_INFORMATION) ExAllocatePoolWithTag(NonPagedPool, GET_USBD_INTERFACE_SIZE(2), USBDEV_POOLTAG);
						else
							m_pInterface[i] = (PUSBD_INTERFACE_INFORMATION) ExAllocatePoolWithTag(NonPagedPool, interface_temp->Length, USBDEV_POOLTAG);
						
						//2010/8/17 05:42下午
						//KeAcquireSpinLock(&SetConfigSpinLock, &oldIrql);

						//2010/8/13 05:20下午
						if (m_pInterface[i] && pTempInterfaceList_First[i].Interface && pTempInterfaceList_First[i].Interface->Length >0)
						//if (m_pInterfaceListEntry[i].Interface)
						{
							//2010/8/25 10:52上午
							//DBGU_TRACE("RtlCopyMemory Interface[%d] len = %d\n",i,pTempInterfaceList_First[i].Interface->Length);
							//RtlCopyMemory(m_pInterface[i], pTempInterfaceList_First[i].Interface, pTempInterfaceList_First[i].Interface->Length);
							DBGU_TRACE("MJ RtlCopyMemory Interface[%d] len = %d\n",i,interface_temp->Length);
							RtlCopyMemory(m_pInterface[i], interface_temp, interface_temp->Length);
							m_pInterface[i]->InterfaceNumber	= i;
							m_pInterface[i]->AlternateSetting	= 0;	
							
							if(i==0)
								m_pInterface[i]->Pipes[0].MaximumTransferSize = USBD_DEFAULT_MAXIMUM_TRANSFER_SIZE;
							else
							{
								if(BeST5R286)
									m_pInterface[i]->NumberOfPipes = 2;
								else	
									m_pInterface[i]->NumberOfPipes = 1;
							}

						}
						else
						{
							DBGU_TRACE("RtlCopyMemory Interface[%d] STATUS_INSUFFICIENT_RESOURCES\n",i);
							ntStatus = STATUS_INSUFFICIENT_RESOURCES;
						}	
						//2010/8/17 03:42下午
						//KeReleaseSpinLock(&SetConfigSpinLock, oldIrql);
					}//for loop i
					

				}// m_pInterfaceListEntry != NULL
				/*else
				{// m_pInterfaceListEntry == NULL
					ntStatus = STATUS_INSUFFICIENT_RESOURCES;
				}*/// m_pInterfaceListEntry == NULL
			}// ntStatus == STATUS_SUCCESS
		}// pUrb != NULL
		else
		{// pUrb == NULL
			ntStatus = STATUS_INSUFFICIENT_RESOURCES;
		}// pUrb == NULL
	}// pTempInterfaceList != NULL
	else
	{// pTempInterfaceList == NULL
		ntStatus = STATUS_INSUFFICIENT_RESOURCES;
	}// pTempInterfaceList == NULL

	if(pUrb) 
		ExFreePool(pUrb);

	if(pTempInterfaceList_First)
	{
		ExFreePoolWithTag(pTempInterfaceList_First,USBDEV_POOLTAG);
		//2010/8/16 07:00下午
		pTempInterfaceList_First = NULL;
	}

	return ntStatus;
}
Пример #22
0
NTSTATUS
InsertNBs(
	_Inout_ KKDRV_QUEUE_DATA *queueData,
	_In_ NET_BUFFER_LIST *head
	)
{
	NTSTATUS status = STATUS_SUCCESS;
	KLOCK_QUEUE_HANDLE lockHandle;

	NET_BUFFER_LIST *nbl = head;
	NET_BUFFER *nb;

	while (nbl)
	{
		nb = NET_BUFFER_LIST_FIRST_NB(nbl);

		while (nb)
		{
			PVOID data;
			ULONG dataLength = NET_BUFFER_DATA_LENGTH(nb);
			PKKDRV_PACKET packet = (PKKDRV_PACKET)ExAllocatePoolWithTag(
				NonPagedPool,
				KKDRV_PACKET_SIZE + dataLength,
				KKDRV_TAG
				);
			if (packet == NULL)
			{
				return STATUS_INSUFFICIENT_RESOURCES;
			};

			packet->dataLength = dataLength;
			data = NdisGetDataBuffer(nb, dataLength, NULL, 1, 0);
			if (data == NULL)
			{
				NdisGetDataBuffer(nb, dataLength, &packet->data, 1, 0);
			}
			else
			{
				RtlCopyMemory(&(packet->data), data, dataLength);
			}

			KeAcquireInStackQueuedSpinLockAtDpcLevel(
				&queueData->queueLock,
				&lockHandle
				);

			InsertTailList(&queueData->queue, &packet->entry);
			queueData->queueLength++;

			if (queueData->queueLength > queueData->queueLengthMax)
			{
				PLIST_ENTRY entry = RemoveHeadList(&queueData->queue);
				ExFreePoolWithTag(entry, KKDRV_TAG);
				queueData->queueLength--;
			}

			KeReleaseInStackQueuedSpinLockFromDpcLevel(
				&lockHandle
				);

			nb = nb->Next;
		}

		nbl = nbl->Next;
	}

	return status;
}
Пример #23
0
NTSTATUS inspectPacket(PENDED_PACKET* windbgsharkPacket)
{
	PBYTE dataWithOverhead = NULL;
	ULONG dataWithOverheadLength = 0;

	if(windbgsharkPacket->flowContext == NULL)
	{
		// This means an error with callouts
		return STATUS_UNSUCCESSFUL;
	}
	
	if(windbgsharkPacket->close)
	{
		CleanupFlowContext(windbgsharkPacket->flowContext);
		windbgsharkPacket->permitted = FALSE;

		return STATUS_SUCCESS;
	}

	if(windbgsharkPacket->flags & FWPS_STREAM_FLAG_SEND)
	{
		windbgsharkPacket->sequenceNumber = windbgsharkPacket->flowContext->localCounter;
		windbgsharkPacket->acknowledgementNumber = windbgsharkPacket->flowContext->remoteCounter;
	}
	else if(windbgsharkPacket->flags & FWPS_STREAM_FLAG_RECEIVE)
	{
		windbgsharkPacket->sequenceNumber = windbgsharkPacket->flowContext->remoteCounter;
		windbgsharkPacket->acknowledgementNumber = windbgsharkPacket->flowContext->localCounter;
	}

	// If the payload is empty, no need for parsing
	if(windbgsharkPacket->dataLength == 0 || windbgsharkPacket->data == NULL)
	{
		return STATUS_UNSUCCESSFUL;
	}

	// Pool realloc to add an overhead to the size
	// (user from host OS may want to add new data)
	dataWithOverheadLength = windbgsharkPacket->dataLength + PACKET_SIZE_OVERHEAD;
	
	dataWithOverhead = ExAllocatePoolWithTag(
		NonPagedPool,
		dataWithOverheadLength,
		TAG_PENDEDPACKETDATA);

	if(dataWithOverhead != NULL)
	{
		RtlZeroMemory(dataWithOverhead, dataWithOverheadLength);

		RtlCopyMemory(
			dataWithOverhead,
			windbgsharkPacket->data, 
			windbgsharkPacket->dataLength);

		ExFreePoolWithTag(windbgsharkPacket->data, TAG_PENDEDPACKETDATA);

		windbgsharkPacket->data = dataWithOverhead;

		windbgsharkPacket->allocatedBytes = dataWithOverheadLength;
	}

	onpacketinspect_stub(windbgsharkPacket);

	onpacketinject_stub(windbgsharkPacket);

	return STATUS_SUCCESS;
}
Пример #24
0
Файл: rw.c Проект: RPG-7/reactos
/*
 * FUNCTION: Reads data from a file
 */
static
NTSTATUS
NtfsReadFile(PDEVICE_EXTENSION DeviceExt,
             PFILE_OBJECT FileObject,
             PUCHAR Buffer,
             ULONG Length,
             ULONG ReadOffset,
             ULONG IrpFlags,
             PULONG LengthRead)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PNTFS_FCB Fcb;
    PFILE_RECORD_HEADER FileRecord;
    PNTFS_ATTR_CONTEXT DataContext;
    ULONG RealLength;
    ULONG RealReadOffset;
    ULONG RealLengthRead;
    ULONG ToRead;
    BOOLEAN AllocatedBuffer = FALSE;
    PCHAR ReadBuffer = (PCHAR)Buffer;

    DPRINT1("NtfsReadFile(%p, %p, %p, %u, %u, %x, %p)\n", DeviceExt, FileObject, Buffer, Length, ReadOffset, IrpFlags, LengthRead);

    *LengthRead = 0;

    if (Length == 0)
    {
        DPRINT1("Null read!\n");
        return STATUS_SUCCESS;
    }

    Fcb = (PNTFS_FCB)FileObject->FsContext;

    if (ReadOffset >= Fcb->Entry.AllocatedSize)
    {
        DPRINT1("Reading beyond file end!\n");
        return STATUS_END_OF_FILE;
    }

    ToRead = Length;
    if (ReadOffset + Length > Fcb->Entry.AllocatedSize)
        ToRead = Fcb->Entry.AllocatedSize - ReadOffset;

    RealReadOffset = ReadOffset;
    RealLength = ToRead;

    if ((ReadOffset % DeviceExt->NtfsInfo.BytesPerSector) != 0 || (ToRead % DeviceExt->NtfsInfo.BytesPerSector) != 0)
    {
        RealReadOffset = ROUND_DOWN(ReadOffset, DeviceExt->NtfsInfo.BytesPerSector);
        RealLength = ROUND_UP(ToRead, DeviceExt->NtfsInfo.BytesPerSector);

        ReadBuffer = ExAllocatePoolWithTag(NonPagedPool, RealLength + DeviceExt->NtfsInfo.BytesPerSector, TAG_NTFS);
        if (ReadBuffer == NULL)
        {
            DPRINT1("Not enough memory!\n");
            return STATUS_INSUFFICIENT_RESOURCES;
        }
        AllocatedBuffer = TRUE;
    }

    FileRecord = ExAllocatePoolWithTag(NonPagedPool, DeviceExt->NtfsInfo.BytesPerFileRecord, TAG_NTFS);
    if (FileRecord == NULL)
    {
        DPRINT1("Not enough memory!\n");
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    Status = ReadFileRecord(DeviceExt, Fcb->MFTIndex, FileRecord);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Can't find record!\n");
        ExFreePoolWithTag(FileRecord, TAG_NTFS);
        return Status;
    }

    Status = FindAttribute(DeviceExt, FileRecord, AttributeData, L"", 0, &DataContext);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("No data associated with file!\n");
        ExFreePoolWithTag(FileRecord, TAG_NTFS);
        return Status;
    }

    DPRINT1("Effective read: %lu at %lu\n", RealLength, RealReadOffset);
    RealLengthRead = ReadAttribute(DeviceExt, DataContext, RealReadOffset, (PCHAR)ReadBuffer, RealLength);
    if (RealLengthRead != RealLength)
    {
        DPRINT1("Read failure!\n");
        ReleaseAttributeContext(DataContext);
        ExFreePoolWithTag(FileRecord, TAG_NTFS);
        if (AllocatedBuffer)
        {
            ExFreePoolWithTag(ReadBuffer, TAG_NTFS);
        }
        return Status;
    }

    ReleaseAttributeContext(DataContext);
    ExFreePoolWithTag(FileRecord, TAG_NTFS);

    *LengthRead = ToRead;

    DPRINT1("%lu got read\n", *LengthRead);

    if (AllocatedBuffer)
    {
        RtlCopyMemory(Buffer, ReadBuffer + (ReadOffset - RealReadOffset), ToRead);
    }

    if (ToRead != Length)
    {
        RtlZeroMemory(Buffer + ToRead, Length - ToRead);
    }

    if (AllocatedBuffer)
    {
        ExFreePoolWithTag(ReadBuffer, TAG_NTFS);
    }

    return STATUS_SUCCESS;
}
Пример #25
0
/**
 * Query Cache Pool (If the _WRITE_ Request is Matched)
 * If it's fully matched, update cache and return TRUE,
 * else return FALSE
 */
BOOLEAN QueryAndWriteToCachePool (
	PCACHE_POOL CachePool, PUCHAR Buf, LONGLONG Offset, ULONG Length
#ifdef READ_VERIFY
	,PDEVICE_OBJECT LowerDeviceObject
	,ULONG DiskNumber
	,ULONG PartitionNumber
#endif
)
{
	PUCHAR origBuf;
	ULONG i, front_offset, front_skip, end_cut, origLen;
	BOOLEAN Ret = FALSE;
	BOOLEAN front_broken, end_broken;
	PCACHE_BLOCK *ppInternalBlocks = NULL;

	origBuf = Buf;
	origLen = Length;

	detect_broken(Offset, Length, front_broken, end_broken, front_offset, front_skip, end_cut);
	Offset /= BLOCK_SIZE;
	Length /= BLOCK_SIZE;

	ppInternalBlocks = (PCACHE_BLOCK*) ExAllocatePoolWithTag (
		NonPagedPool,
		(SIZE_T)((Length+2) * sizeof(PCACHE_BLOCK)),
		CACHE_POOL_TAG
	);
	if (ppInternalBlocks == NULL)
		goto l_error;

	// Query Pool to Check If Fully Matched
	if (front_broken == TRUE && _QueryPoolByIndex(CachePool, Offset-1, ppInternalBlocks+0) == FALSE)
		goto l_error;
	for (i = 0; i < Length; i++)
		if (_QueryPoolByIndex(CachePool, Offset+i, ppInternalBlocks+i+1) == FALSE)
			goto l_error;
	if (end_broken == TRUE && _QueryPoolByIndex(CachePool, Offset+Length, ppInternalBlocks+Length+1) == FALSE)
		goto l_error;

	if (front_broken == TRUE)
	{
		DO_READ_VERIFY(CachePool, &CachePool->Storage, ppInternalBlocks[0]);
		_write_data(ppInternalBlocks[0], front_offset, Buf, front_skip);
		Buf += front_skip;
	}

	for (i = 0; i < Length; i++)
	{
		DO_READ_VERIFY(CachePool, &CachePool->Storage, ppInternalBlocks[i+1]);
		_write_data(ppInternalBlocks[i+1], 0, Buf, BLOCK_SIZE);
		Buf += BLOCK_SIZE;
	}

	if (end_broken == TRUE)
	{
		DO_READ_VERIFY(CachePool, &CachePool->Storage, ppInternalBlocks[Length+1]);
		_write_data(ppInternalBlocks[Length+1], 0, Buf, end_cut);
		Buf += end_cut;
	}

	ASSERT(Buf - origBuf == origLen);
	Ret = TRUE;
l_error:
	if (ppInternalBlocks != NULL)
		ExFreePoolWithTag(ppInternalBlocks, CACHE_POOL_TAG);
	return Ret;
}
Пример #26
0
static VOID vboxUsbToolMemFree(PVOID pvMem)
{
    ExFreePoolWithTag(pvMem, VBOXUSBTOOL_MEMTAG);
}
Пример #27
0
VOID
NTAPI
LpcpDestroyPortQueue(IN PLPCP_PORT_OBJECT Port,
                     IN BOOLEAN Destroy)
{
    PLIST_ENTRY ListHead, NextEntry;
    PETHREAD Thread;
    PLPCP_MESSAGE Message;
    PLPCP_PORT_OBJECT ConnectionPort = NULL;
    PLPCP_CONNECTION_MESSAGE ConnectMessage;
    PLPCP_NONPAGED_PORT_QUEUE MessageQueue;

    PAGED_CODE();
    LPCTRACE(LPC_CLOSE_DEBUG, "Port: %p. Flags: %lx\n", Port, Port->Flags);

    /* Hold the lock */
    KeAcquireGuardedMutex(&LpcpLock);

    /* Check if we have a connected port */
    if (((Port->Flags & LPCP_PORT_TYPE_MASK) != LPCP_UNCONNECTED_PORT) &&
        (Port->ConnectedPort))
    {
        /* Disconnect it */
        Port->ConnectedPort->ConnectedPort = NULL;
        ConnectionPort = Port->ConnectedPort->ConnectionPort;
        if (ConnectionPort)
        {
            /* Clear connection port */
            Port->ConnectedPort->ConnectionPort = NULL;
        }
    }

    /* Check if this is a connection port */
    if ((Port->Flags & LPCP_PORT_TYPE_MASK) == LPCP_CONNECTION_PORT)
    {
        /* Delete the name */
        Port->Flags |= LPCP_NAME_DELETED;
    }

    /* Walk all the threads waiting and signal them */
    ListHead = &Port->LpcReplyChainHead;
    NextEntry = ListHead->Flink;
    while ((NextEntry) && (NextEntry != ListHead))
    {
        /* Get the Thread */
        Thread = CONTAINING_RECORD(NextEntry, ETHREAD, LpcReplyChain);

        /* Make sure we're not in exit */
        if (Thread->LpcExitThreadCalled) break;

        /* Move to the next entry */
        NextEntry = NextEntry->Flink;

        /* Remove and reinitialize the List */
        RemoveEntryList(&Thread->LpcReplyChain);
        InitializeListHead(&Thread->LpcReplyChain);

        /* Check if someone is waiting */
        if (!KeReadStateSemaphore(&Thread->LpcReplySemaphore))
        {
            /* Get the message */
            Message = LpcpGetMessageFromThread(Thread);
            if (Message)
            {
                /* Check if it's a connection request */
                if (Message->Request.u2.s2.Type == LPC_CONNECTION_REQUEST)
                {
                    /* Get the connection message */
                    ConnectMessage = (PLPCP_CONNECTION_MESSAGE)(Message + 1);

                    /* Check if it had a section */
                    if (ConnectMessage->SectionToMap)
                    {
                        /* Dereference it */
                        ObDereferenceObject(ConnectMessage->SectionToMap);
                    }
                }

                /* Clear the reply message */
                Thread->LpcReplyMessage = NULL;

                /* And remove the message from the port zone */
                LpcpFreeToPortZone(Message, LPCP_LOCK_HELD);
                NextEntry = Port->LpcReplyChainHead.Flink;
            }

            /* Release the semaphore and reset message id count */
            Thread->LpcReplyMessageId = 0;
            KeReleaseSemaphore(&Thread->LpcReplySemaphore, 0, 1, FALSE);
        }
    }

    /* Reinitialize the list head */
    InitializeListHead(&Port->LpcReplyChainHead);

    /* Loop queued messages */
    while ((Port->MsgQueue.ReceiveHead.Flink) &&
           !(IsListEmpty(&Port->MsgQueue.ReceiveHead)))
    {
        /* Get the message */
        Message = CONTAINING_RECORD(Port->MsgQueue.ReceiveHead.Flink,
                                    LPCP_MESSAGE,
                                    Entry);

        /* Free and reinitialize it's list head */
        RemoveEntryList(&Message->Entry);
        InitializeListHead(&Message->Entry);

        /* Remove it from the port zone */
        LpcpFreeToPortZone(Message, LPCP_LOCK_HELD);
    }

    /* Release the lock */
    KeReleaseGuardedMutex(&LpcpLock);

    /* Dereference the connection port */
    if (ConnectionPort) ObDereferenceObject(ConnectionPort);

    /* Check if we have to free the port entirely */
    if (Destroy)
    {
        /* Check if the semaphore exists */
        if (Port->MsgQueue.Semaphore)
        {
            /* Use the semaphore to find the port queue and free it */
            MessageQueue = CONTAINING_RECORD(Port->MsgQueue.Semaphore,
                                             LPCP_NONPAGED_PORT_QUEUE,
                                             Semaphore);
            ExFreePoolWithTag(MessageQueue, 'troP');
        }
    }
}
Пример #28
0
/*
 * @implemented
 */
PVOID
NTAPI
MmAllocateNonCachedMemory(IN SIZE_T NumberOfBytes)
{
    PFN_COUNT PageCount, MdlPageCount;
    PFN_NUMBER PageFrameIndex;
    PHYSICAL_ADDRESS LowAddress, HighAddress, SkipBytes;
    MI_PFN_CACHE_ATTRIBUTE CacheAttribute;
    PMDL Mdl;
    PVOID BaseAddress;
    PPFN_NUMBER MdlPages;
    PMMPTE PointerPte;
    MMPTE TempPte;

    //
    // Get the page count
    //
    ASSERT(NumberOfBytes != 0);
    PageCount = (PFN_COUNT)BYTES_TO_PAGES(NumberOfBytes);

    //
    // Use the MDL allocator for simplicity, so setup the parameters
    //
    LowAddress.QuadPart = 0;
    HighAddress.QuadPart = -1;
    SkipBytes.QuadPart = 0;
    CacheAttribute = MiPlatformCacheAttributes[0][MmNonCached];

    //
    // Now call the MDL allocator
    //
    Mdl = MiAllocatePagesForMdl(LowAddress,
                                HighAddress,
                                SkipBytes,
                                NumberOfBytes,
                                CacheAttribute,
                                0);
    if (!Mdl) return NULL;

    //
    // Get the MDL VA and check how many pages we got (could be partial)
    //
    BaseAddress = (PVOID)((ULONG_PTR)Mdl->StartVa + Mdl->ByteOffset);
    MdlPageCount = ADDRESS_AND_SIZE_TO_SPAN_PAGES(BaseAddress, Mdl->ByteCount);
    if (PageCount != MdlPageCount)
    {
        //
        // Unlike MDLs, partial isn't okay for a noncached allocation, so fail
        //
        ASSERT(PageCount > MdlPageCount);
        MmFreePagesFromMdl(Mdl);
        ExFreePoolWithTag(Mdl, TAG_MDL);
        return NULL;
    }

    //
    // Allocate system PTEs for the base address
    // We use an extra page to store the actual MDL pointer for the free later
    //
    PointerPte = MiReserveSystemPtes(PageCount + 1, SystemPteSpace);
    if (!PointerPte)
    {
        //
        // Out of memory...
        //
        MmFreePagesFromMdl(Mdl);
        ExFreePoolWithTag(Mdl, TAG_MDL);
        return NULL;
    }

    //
    // Store the MDL pointer
    //
    *(PMDL*)PointerPte++ = Mdl;

    //
    // Okay, now see what range we got
    //
    BaseAddress = MiPteToAddress(PointerPte);

    //
    // This is our array of pages
    //
    MdlPages = (PPFN_NUMBER)(Mdl + 1);

    //
    // Setup the template PTE
    //
    TempPte = ValidKernelPte;

    //
    // Now check what kind of caching we should use
    //
    switch (CacheAttribute)
    {
        case MiNonCached:

            //
            // Disable caching
            //
            MI_PAGE_DISABLE_CACHE(&TempPte);
            MI_PAGE_WRITE_THROUGH(&TempPte);
            break;

        case MiWriteCombined:

            //
            // Enable write combining
            //
            MI_PAGE_DISABLE_CACHE(&TempPte);
            MI_PAGE_WRITE_COMBINED(&TempPte);
            break;

        default:
            //
            // Nothing to do
            //
            break;
    }

    //
    // Now loop the MDL pages
    //
    do
    {
        //
        // Get the PFN
        //
        PageFrameIndex = *MdlPages++;

        //
        // Set the PFN in the page and write it
        //
        TempPte.u.Hard.PageFrameNumber = PageFrameIndex;
        MI_WRITE_VALID_PTE(PointerPte++, TempPte);
    } while (--PageCount);

    //
    // Return the base address
    //
    return BaseAddress;

}
Пример #29
0
ULONGLONG
NtfsGetFreeClusters(PDEVICE_EXTENSION DeviceExt)
{
    NTSTATUS Status;
    PFILE_RECORD_HEADER BitmapRecord;
    PNTFS_ATTR_CONTEXT DataContext;
    ULONGLONG BitmapDataSize;
    PCHAR BitmapData;
    ULONGLONG FreeClusters = 0;
    ULONG Read = 0;
    RTL_BITMAP Bitmap;

    DPRINT1("NtfsGetFreeClusters(%p)\n", DeviceExt);

    BitmapRecord = ExAllocatePoolWithTag(NonPagedPool,
                                         DeviceExt->NtfsInfo.BytesPerFileRecord,
                                         TAG_NTFS);
    if (BitmapRecord == NULL)
    {
        return 0;
    }

    Status = ReadFileRecord(DeviceExt, NTFS_FILE_BITMAP, BitmapRecord);
    if (!NT_SUCCESS(Status))
    {
        ExFreePoolWithTag(BitmapRecord, TAG_NTFS);
        return 0;
    }

    Status = FindAttribute(DeviceExt, BitmapRecord, AttributeData, L"", 0, &DataContext);
    if (!NT_SUCCESS(Status))
    {
        ExFreePoolWithTag(BitmapRecord, TAG_NTFS);
        return 0;
    }

    BitmapDataSize = AttributeDataLength(&DataContext->Record);
    ASSERT((BitmapDataSize * 8) >= DeviceExt->NtfsInfo.ClusterCount);
    BitmapData = ExAllocatePoolWithTag(NonPagedPool, ROUND_UP(BitmapDataSize, DeviceExt->NtfsInfo.BytesPerSector), TAG_NTFS);
    if (BitmapData == NULL)
    {
        ReleaseAttributeContext(DataContext);
        ExFreePoolWithTag(BitmapRecord, TAG_NTFS);
        return 0;
    }

    /* FIXME: Totally underoptimized! */
    for (; Read < BitmapDataSize; Read += DeviceExt->NtfsInfo.BytesPerSector)
    {
        ReadAttribute(DeviceExt, DataContext, Read, (PCHAR)((ULONG_PTR)BitmapData + Read), DeviceExt->NtfsInfo.BytesPerSector);
    }
    ReleaseAttributeContext(DataContext);

    DPRINT1("Total clusters: %I64x\n", DeviceExt->NtfsInfo.ClusterCount);
    DPRINT1("Total clusters in bitmap: %I64x\n", BitmapDataSize * 8);
    DPRINT1("Diff in size: %I64d B\n", ((BitmapDataSize * 8) - DeviceExt->NtfsInfo.ClusterCount) * DeviceExt->NtfsInfo.SectorsPerCluster * DeviceExt->NtfsInfo.BytesPerSector);

    RtlInitializeBitMap(&Bitmap, (PULONG)BitmapData, DeviceExt->NtfsInfo.ClusterCount);
    FreeClusters = RtlNumberOfClearBits(&Bitmap);

    ExFreePoolWithTag(BitmapData, TAG_NTFS);
    ExFreePoolWithTag(BitmapRecord, TAG_NTFS);

    return FreeClusters;
}
Пример #30
0
static NTSTATUS VirtQueueAddBuffer(IN PDEVICE_CONTEXT Context,
                                   IN WDFREQUEST Request,
                                   IN size_t Length)
{
    PREAD_BUFFER_ENTRY entry;
    size_t length;
    struct virtqueue *vq = Context->VirtQueue;
    struct VirtIOBufferDescriptor sg;
    int ret;

    TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %!FUNC!");

    entry = (PREAD_BUFFER_ENTRY)ExAllocatePoolWithTag(NonPagedPool,
        sizeof(READ_BUFFER_ENTRY), VIRT_RNG_MEMORY_TAG);

    if (entry == NULL)
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_READ,
            "Failed to allocate a read entry.");
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    length = min(Length, PAGE_SIZE);
    entry->Buffer = ExAllocatePoolWithTag(NonPagedPool, length,
        VIRT_RNG_MEMORY_TAG);

    if (entry->Buffer == NULL)
    {
        TraceEvents(TRACE_LEVEL_ERROR, DBG_READ,
            "Failed to allocate a read buffer.");
        ExFreePoolWithTag(entry, VIRT_RNG_MEMORY_TAG);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    entry->Request = Request;

    sg.physAddr = MmGetPhysicalAddress(entry->Buffer);
    sg.length = (unsigned)length;

    WdfSpinLockAcquire(Context->VirtQueueLock);

    TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ,
        "Push %p Request: %p Buffer: %p",
        entry, entry->Request, entry->Buffer);

    PushEntryList(&Context->ReadBuffersList, &entry->ListEntry);

    ret = virtqueue_add_buf(vq, &sg, 0, 1, entry, NULL, 0);
    if (ret < 0)
    {
        PSINGLE_LIST_ENTRY removed;

        TraceEvents(TRACE_LEVEL_ERROR, DBG_READ,
            "Failed to add buffer to virt queue.");

        TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ,
            "Pop %p Request: %p Buffer: %p",
            entry, entry->Request, entry->Buffer);

        removed = PopEntryList(&Context->ReadBuffersList);
        NT_ASSERT(entry == CONTAINING_RECORD(
            removed, READ_BUFFER_ENTRY, ListEntry));

        ExFreePoolWithTag(entry->Buffer, VIRT_RNG_MEMORY_TAG);
        ExFreePoolWithTag(entry, VIRT_RNG_MEMORY_TAG);

        WdfSpinLockRelease(Context->VirtQueueLock);

        return STATUS_UNSUCCESSFUL;
    }

    WdfSpinLockRelease(Context->VirtQueueLock);

    virtqueue_kick(vq);

    TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %!FUNC!");

    return STATUS_SUCCESS;
}