Ejemplo n.º 1
0
static int MS_MountDevice(int DeviceType)
{
	kal_uint8 *sector = (kal_uint8*)MSDC_Sector;
	FS_MasterBootRecord *MBR;
	FS_BootRecord *PBR;
	int status;	
	kal_bool IsMBRExist;
   kal_uint8 type = 0;
   kal_uint8 c = gMS.Capacity;
   	
   // get index for MS_MBR => (type) is the index
   while((c >>= 1) != 2)
   	type++;	   
	
	IsMBRExist = KAL_FALSE;
	// read MBR at sector 0
	status = ReadSectors(NULL,0,1,(void*)sector);	  		
	MBR = (FS_MasterBootRecord*)sector;
	PBR = (FS_BootRecord*)sector;
	if( MBR->Signature == 0xAA55 &&
		MBR->PTable[0].BootIndicator == 0x80)
	{
		IsMBRExist = KAL_TRUE;
	}
	if(!IsMBRExist)
	{	
		// create MBR
		kal_mem_set((void*)MBR,0,sizeof(MBR));
		kal_mem_cpy((void*)&(MBR->PTable[0]),MS_MBR[type],MS_MBR_SIZE);
		MBR->Signature = 0xAA55;
		status = WriteSectors(NULL,0,1,(void*)sector);
		if(status < NO_ERROR)
			return FS_MSDC_MOUNT_ERROR;
		// create PBR
		FS_CreateBootSector((void*)sector, (FS_PartitionRecord*)MS_MBR[type], (BYTE)MSDC_MEDIA_DESCRIPTOR, 
			(UINT)gMS.PagesPerBlk, (gMS.Capacity < 128)?FS_FMT_FAT_12:FS_FMT_FAT_16);
		PBR->NearJump[0] = 0xE9;
		PBR->NearJump[1] = 0x00;
		PBR->NearJump[2] = 0x00;
		kal_mem_set((void*)PBR->BP.OEMName,0x20,8);
		PBR->BP.SectorsPerCluster = gMS.PagesPerBlk;
		PBR->BP.DirEntries = 0x200;
		PBR->BP.E._16.BPB.PhysicalDiskNumber = 0;
		PBR->BP.E._16.BPB.CurrentHead = 0;
		PBR->BP.E._16.BPB.SerialNumber = 0;
		kal_mem_set((void*)PBR->BP.E._16.BPB.Label,0x20,11);	
		status = WriteSectors(NULL, PBR->BP.NumberOfHiddenSectors,1,(void*)sector);
		if(status < NO_ERROR)
			return FS_MSDC_MOUNT_ERROR;
		
	}
	
	return FS_NO_ERROR;
}
Ejemplo n.º 2
0
Archivo: backup.c Proyecto: FDOS/chkdsk
BOOL BackupBoot(RDWRHandle handle)
{
   int fatlabelsize = GetFatLabelSize(handle);
   SECTOR BackupSector;
   struct BootSectorStruct* boot;
   BOOL retVal = TRUE;
  
   if (fatlabelsize == FAT32)
   {
      BackupSector = GetFAT32BackupBootSector(handle);
      if (!BackupSector)
      {
         RETURN_FTEERR(FALSE);
      }       
              
      boot = AllocateBootSector();
      if (!boot) RETURN_FTEERR(FALSE);
   
      if (!ReadBootSector(handle, boot) ||
	  (WriteSectors(handle, 1, BackupSector, (void*) boot, WR_UNKNOWN)
                                                                     == -1))
      {
	  RETURN_FTEERR(FALSE);
      }    
      
      FreeBootSector(boot);
   }     

   RETURN_FTEERR(retVal);   
}
Ejemplo n.º 3
0
RETVAL PlaceDescriptorInFat(RDWRHandle handle)
{
    struct  BootSectorStruct boot;
    SECTOR  fatstart;
    char    buffer[BYTESPERSECTOR], *p;

    if (!ReadBootSector(handle, &boot))
       return ERROR;

    fatstart = GetFatStart(handle);
    if (!fatstart) return ERROR;

    if (ReadSectors(handle, 1, fatstart, buffer) == -1)
       return ERROR;

    if (buffer[0] != boot.descriptor)
    {
        ReportFileSysError("Wrong descriptor value in FAT",
                           0,
                           &p,
                           0,
                           FALSE);

       buffer[0] = boot.descriptor;

       if (WriteSectors(handle, 1, fatstart, buffer, WR_FAT) == -1)
          return ERROR;

       if (!BackupFat(handle))
	  return ERROR;
    }

    return SUCCESS;
}
Ejemplo n.º 4
0
SD_SelfFormat()
{

    FS_PartitionRecord Par, Par1;
    //static kal_uint8 p[512];

    kal_mem_set((void*)&Par, 0, sizeof Par);
    Par.Sectors = gSD->mCSD.capacity/512;

    FS_CreateMasterBootRecord(MSDC_Sector, &Par);

    WriteSectors(gMSDC_Handle, 0, 1, MSDC_Sector);

    Par = ((FS_MasterBootRecord *)MSDC_Sector)->PTable[0];
    FS_CreateBootSector((void*)MSDC_Sector, &Par, 0xF8, 0, FS_FMT_SINGLE_FAT );
    WriteSectors(gMSDC_Handle, Par.RelativeSector, 1, MSDC_Sector);
    /*  End of SelfFormat */

}
Ejemplo n.º 5
0
BOOL WriteDiskFromFile( HANDLE hDevice,HANDLE hFile,ULONGLONG ullStartSector, ULONGLONG ullSectors )
{
	ULONGLONG ullRealStartSector = ullStartSector;
	ULONGLONG ullReadSectors = 0;
	ULONGLONG ullRemainSectors = ullSectors;
	DWORD dwSectors = 0;
	BOOL  bOK = TRUE;
	ULONGLONG ullOffset = 0;

	PBYTE lpBuf = new BYTE[BUF_LENGTH];
	memset(lpBuf,0,BUF_LENGTH);

	while (ullReadSectors < ullSectors)
	{
		if (ullRemainSectors < PER_SECTORS)
		{
			dwSectors = (DWORD)ullRemainSectors;
		}
		else
		{
			dwSectors = PER_SECTORS;
		}
		DWORD dwLastError = 0;
		memset(lpBuf,0,BUF_LENGTH);

		DWORD dwSize = dwSectors * BYTES_PER_SECTOR;
		BOOL bRec = ReadFileAsyn(hFile,ullOffset,dwSize,lpBuf,&g_OverlapedFile,&dwLastError);

		if (!bRec)
		{
			bOK = FALSE;
			std::cout << red << "Read File Error---" << dwLastError << white << std::endl;
			break;
		}

		bRec = WriteSectors(hDevice,ullRealStartSector,dwSectors,BYTES_PER_SECTOR,lpBuf,&g_OverlapedDisk,&dwLastError);

		if (!bRec)
		{
			bOK = FALSE;
			std::cout << red << "Write Sectors Error---" << dwLastError << white << std::endl;
			break;
		}

		ullRealStartSector += dwSectors;
		ullReadSectors += dwSectors;
		ullRemainSectors -= dwSectors;
		ullOffset += dwSize;
	}

	delete[] lpBuf;

	return bOK;
}
Ejemplo n.º 6
0
//! under construction [Samuel, 2010/10/01]
DRV_STATUS_CODE DRV_SD_WriteSectors(
	mcdev_enum id,
	unsigned int sector,
	unsigned int sectors,
	void * buffer,
	unsigned int flags
	)
{
	SDC_CMD_STATUS status = NO_ERROR;
	emmc_addr addr;

//#if !defined(__UBL__) && !defined(__FUE__)
//	ASSERT(0); // so far this function can only be used in bootloader
//#endif

	get_MSDC_lock(&gSD->mSDdrv_lock);

	status = DRV_SD_AddrLookupTbl(sector, &addr);
	if (NO_ERROR != status)
	{
		free_MSDC_lock(&gSD->mSDdrv_lock);
		return DRV_WRITE_FAILURE;
	}

	if (KAL_TRUE != SD_eMMC_ECSD_setCurrentPart(addr.partition))
	{
		free_MSDC_lock(&gSD->mSDdrv_lock);
		return DRV_WRITE_FAILURE;
	}

	status = WriteSectors(GetMsdcHandle(id), addr.offset, sectors, buffer);
	if (NO_ERROR != status)
	{
		free_MSDC_lock(&gSD->mSDdrv_lock);
		return DRV_WRITE_FAILURE;
	}

	//! TODO: check why it fails
	if (KAL_TRUE != SD_eMMC_ECSD_setCurrentPart(eMMC_user_Area))
	{
		free_MSDC_lock(&gSD->mSDdrv_lock);
		return DRV_WRITE_FAILURE;
	}

	free_MSDC_lock(&gSD->mSDdrv_lock);
	return DRV_SUCCESS;
}
Ejemplo n.º 7
0
BiosResult WriteEncryptedSectors (uint16 sourceSegment, uint16 sourceOffset, byte drive, uint64 sector, uint16 sectorCount)
{
	BiosResult result;
	AcquireSectorBuffer();
	uint64 dataUnitNo;
	uint64 writeOffset;

	dataUnitNo = sector;
	writeOffset.HighPart = 0;
	writeOffset.LowPart = 0;

	if (BootCryptoInfo->hiddenVolume)
	{
		if (ReadWritePartiallyCoversEncryptedArea (sector, sectorCount))
			return BiosResultInvalidFunction;

		// Remap the request to the hidden volume
		writeOffset = HiddenVolumeStartSector;
		writeOffset -= EncryptedVirtualPartition.StartSector;
		dataUnitNo -= EncryptedVirtualPartition.StartSector;
		dataUnitNo += HiddenVolumeStartUnitNo;
	}

	while (sectorCount-- > 0)
	{
		CopyMemory (sourceSegment, sourceOffset, SectorBuffer, TC_LB_SIZE);

		if (drive == EncryptedVirtualPartition.Drive && sector >= EncryptedVirtualPartition.StartSector && sector <= EncryptedVirtualPartition.EndSector)
		{
			EncryptDataUnits (SectorBuffer, &dataUnitNo, 1, BootCryptoInfo);
		}

		result = WriteSectors (SectorBuffer, drive, sector + writeOffset, 1);

		if (result != BiosResultSuccess)
			break;

		++sector;
		++dataUnitNo;
		sourceOffset += TC_LB_SIZE;
	}

	ReleaseSectorBuffer();
	return result;
}
Ejemplo n.º 8
0
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//	Installs BK to load the specified driver.
//
BOOL	BkInstallVbr(
			PCHSS	PayloadAddress 
			)
{
	BOOL	Ret = FALSE;
	PCHAR	Vbs	= NULL, Loader = NULL, Packed = NULL;
	PVBR	Vbr = NULL;
	ULONG	i, CodeSize, bSize = BIOS_DEFAULT_SECTOR_SIZE;
	PPARTITION_TABLE	PTable;
	ULONG	StartSector = 0, SectorSize = 0, PackedSize = 0;
	WCHAR	TargetDrive[cstrlenW(wszPartition) + 1] = {0};

	wsprintfW(TargetDrive, wszPartition, 0);
	
	do	// not a loop
	{
		if (!(Vbs = Alloc(BIOS_DEFAULT_SECTOR_SIZE)))
			// Not enough memory
			break;

		// Reading MBR sector
		if (!ReadSectors(TargetDrive, Vbs, bSize, 0, 1))
			// Reading failed 
			break;

		// Check out we read a right one
		if (*(PUSHORT)(Vbs + BIOS_DEFAULT_SECTOR_SIZE - sizeof(USHORT)) != BIOS_MBR_MAGIC)
			// Wrong or corrupt sector loaded
			break;

		// Here we read the Driver Boot sector and searching for the Volume boot sector within it

		PTable = (PPARTITION_TABLE)(Vbs + BIOS_PARTITION_TABLE_OFFSET);
		i = 0;
		
		while(
			(i < BIOS_MAX_PARTITION_COUNT) && 
			(!(PTable->Entry[i].ActiveFlag & BIOS_PARTITION_ACTIVE_FLAG) || 
			(PTable->Entry[i].Descriptor != BIOS_PARTITION_TYPE_INSTALLABLE)))
			i += 1;

		if (i == BIOS_MAX_PARTITION_COUNT)
			// No bootable NTFS partition found
			break;
		
		bSize = BIOS_DEFAULT_SECTOR_SIZE;

#ifdef	_PHYSICAL_DRIVE
		StartSector = PTable->Entry[i].LBAStartSector;
#else
		wsprintfW(TargetDrive, wszPartition, (i + 1));
		StartSector = 0;
#endif

		if (!ReadSectors(TargetDrive, Vbs, bSize, StartSector, 1))
			// Reading failed
			break;


		Vbr = (PVBR)Vbs;
		if (memcmp(&Vbr->VolumeOemId, NTFS_OEM_ID, sizeof(NTFS_OEM_ID)))
			// Not a NTFS partition
			break;

		SectorSize = Vbr->Bpb.SectorSize;
		ASSERT(SectorSize == BIOS_DEFAULT_SECTOR_SIZE);

		bSize = (NTFS_LOADER_SIZE * SectorSize);
		if (!(Loader = Alloc(bSize)))
			// Not enough memory
			break;

		if (!ReadSectors(TargetDrive, Loader, bSize, (StartSector + 1), (NTFS_LOADER_SIZE - 1)))
			// Reading failed
			break;

		if (!(i = GetCodeOffset(Loader)))
			// Wrong or corrupt OS loader
			break;

		CodeSize = (NTFS_LOADER_SIZE - 1) * SectorSize - i;

		PackedSize = ApPack((Loader + i), CodeSize, &Packed);
		if (!PackedSize)
			// Packing failed
			break;

		if (!BkCreateLoader(Loader + i, CodeSize, Packed, PackedSize, PayloadAddress))
			// Failed to create loader
			break;

		if (WriteSectors(TargetDrive, Loader, bSize, (StartSector + 1), (NTFS_LOADER_SIZE - 1)))
			Ret = TRUE;
		
	} while(FALSE);

	if (Vbs)
		Free(Vbs);

	if (Loader)
		Free(Loader);

	if (Packed)
		Free(Packed);

	return(Ret);
}
Ejemplo n.º 9
0
static BOOL	BkInstallPayloadFromBuffer(
			 					PCHAR	Payload,		
								ULONG	PayloadSize,
								PCHSS	PayloadAddress
								)
{
	BOOL	Ret = FALSE;
	PCHAR	Vbs	= NULL, Loader = NULL, Packed = NULL;
	PVBR	Vbr = NULL;
	ULONG	i, bSize = BIOS_DEFAULT_SECTOR_SIZE;
	PPARTITION_TABLE	PTable;
	ULONG	StartSector = 0, EndSector = 0, SectorSize = 0, PackedSize = 0;
	PWCHAR	TargetDrive = wszPhysicalDrive0;

	PCHAR	PayloadSectors = NULL;
	ULONG	PayloadSecSize;
	ULONG	RndSeed = GetTickCount();

	DISK_GEOMETRY	Dg = {0};


	do	// not a loop
	{
		if (!Payload || !PayloadAddress || !PayloadSize)
			break;

		if (!GetDriveGeometry(TargetDrive, &Dg))
			break;

		if (!(Vbs = Alloc(BIOS_DEFAULT_SECTOR_SIZE)))
			// Not enough memory
			break;

		// Reading MBR sector
		if (!ReadSectors(TargetDrive, Vbs, bSize, 0, 1))
			// Reading failed 
			break;

		// Check out we read a right one
		if (*(PUSHORT)(Vbs + BIOS_DEFAULT_SECTOR_SIZE - sizeof(USHORT)) != BIOS_MBR_MAGIC)
			// Wrong or corrupt sector loaded
			break;

		// Here we read the Driver Boot sector and searching for the Volume boot sector within it
		PTable = (PPARTITION_TABLE)(Vbs + BIOS_PARTITION_TABLE_OFFSET);
		
		// Calculating drive unpartitioned space
		for (i=0; i<BIOS_MAX_PARTITION_COUNT; i++)
		{
			if (PTable->Entry[i].ActiveFlag & BIOS_PARTITION_ACTIVE_FLAG)
			{
				if (StartSector == 0 || StartSector > PTable->Entry[i].LBAStartSector)
					StartSector = PTable->Entry[i].LBAStartSector;

				if (EndSector < (PTable->Entry[i].LBAStartSector + PTable->Entry[i].PartitionSize))
					EndSector = (PTable->Entry[i].LBAStartSector + PTable->Entry[i].PartitionSize);
			}
		}	// for (i=0; i<BIOS_MAX_PARTITION_COUNT; i++)

		PayloadSecSize =  (PayloadSize + (Dg.BytesPerSector -1))/Dg.BytesPerSector;

		if (((StartSector - 1)) > PayloadSecSize)
			StartSector = 1 + RtlRandom(&RndSeed)%((StartSector - 1) - PayloadSecSize);
		else
		{
			ULONG	DriveLastSector = Dg.Cylinders.LowPart * Dg.TracksPerCylinder * Dg.SectorsPerTrack;
			StartSector = DriveLastSector - PayloadSecSize - 2;
		}

		if (!(PayloadSectors = Alloc(PayloadSecSize * Dg.BytesPerSector)))
			// Not enough memory
			break;

		memcpy(PayloadSectors, Payload, PayloadSize);


		if (StartSector)
		{
			// Calculating Start sector CHSS address
			PayloadAddress->StartSector.QuadPart = (ULONGLONG)StartSector;
			PayloadAddress->NumberSectors = (USHORT)PayloadSecSize;
			// Writing payload to the disk
			Ret = WriteSectors(TargetDrive, PayloadSectors, (PayloadSecSize * Dg.BytesPerSector), StartSector, PayloadSecSize);
		}
	

	} while(FALSE);

	if (Vbs)
		Free(Vbs);

	if (PayloadSectors) 
		Free(PayloadSectors);

	return(Ret);
}
Ejemplo n.º 10
0
int MMCWriteSectors(BYTE   bDevice,      void *pData,
                    DWORD dwStartSector, WORD  wSectorCount)
{
    int    nError;
    WORD   wWriteCount;
    DRIVE *pDrive = 0;
    BYTE  *pByte;

    nError = MMC_OK;

    MMCLock();

    if (bDevice >= MMC_MAX_SUPPORTED_DEVICE)
    {
        nError = MMC_DRIVE_NOT_FOUND;
    }
    else
    {
        pDrive = &sDrive[bDevice];

        if ((dwStartSector + wSectorCount) > pDrive->dTotalSectors)
        {
            nError = MMC_PARAM_ERROR;
        }
        if ((pDrive->wFlags & MMC_READY) == 0)
        {
            nError = MMC_DRIVE_NOT_FOUND;
        }
        if (pDrive->wFlags & MMC_READ_ONLY)
        {
            nError = MMC_NOT_SUPPORTED;
        }
    }

    if (nError == MMC_OK)
    {
        pByte = (BYTE *) pData;
        while (wSectorCount > 0)
        {

            if (wSectorCount < 256)
            {
                wWriteCount = wSectorCount;
            }
            else
            {
                wWriteCount = 256;
            }

            nError = WriteSectors(pDrive, pByte, dwStartSector, wWriteCount);
            if (nError != MMC_OK)
            {
                break;
            }

            dwStartSector += wWriteCount;
            wSectorCount  -= wWriteCount;
            pByte         += (wWriteCount * MMC_SECTOR_SIZE);
        }
    }

    MMCFree();

    return(nError);
} /* MMCWriteSectors */
Ejemplo n.º 11
0
void USB_Mode(void) 
{
	gb_cmd_timeout=0;
	set_clock_mode(CLOCK_MODE_USB); 
    PowerOn_Init_USB();
	Fill_EndpointDataTable_Into_ExRamBase();
	USBInitialize(); 
	Init_Flash_Reg();
	Init_Flash_Variable();
	gc_WriteProof = 0x00;
	InitFlash();
	
	USB_REG[0x27]    = 0x00; 	// 080304 jay change for new fpga
	GLOBAL_REG[0x17] = 0x01;	// UDC O/P	
    IE = 0x83;	   

	gdw_USB_CountDown = USB_DETECT_TIMEOUT;
	EA=1;	
	while(!gc_USBRST_ISR_Detected)                        // Bulk_In_Out  將跳出while 迴圈  //20090630 chiayen modify
	{
		USB_PlugDetect();
    	if((--gdw_USB_CountDown==0))  //080925chiayen add
		{
			gb_cmd_timeout=1;
    	  	break;
    	}
		if(!gbt_USB_Detected)
		{
			break;
		}
	}
	
	EA=0;
	if(gb_cmd_timeout==1)  //080925chiayen modify
	{
		USB_DisConnect();
		set_clock_mode(CLOCK_MODE_MP3); 
		InitFlash();
		return;
	}
	if(!gb_cmd_timeout)
	{
		LCM_clear();
		LCM_Disp_PC();
		LCM_Disp_PCConnect();
		LCM_Disp_MyMP3Logo();
	}
	   
	for(;;)
	{
		USB_PlugDetect();
		if(!gbt_USB_Detected)
		{//usb connected 
			USB_DisConnect();
			set_clock_mode(CLOCK_MODE_MP3);
			InitFlash();
			break;
		}
		else
		{
			if (gc_USBStage == CBWStage) 
			{			
				if(gbt_USB_Connect_Flag)
				{
				    //tdw_CMD_In_Count =0x02FFFFF;
				}
				else
				{
				    gdw_USB_CountDown =0x01FFFF;  //081208  detect charge first
				}
				EA=1;							
				while (!gbt_USB_CMD_IN)                        // Bulk_In_Out  將跳出while 迴圈
				{
					USB_PlugDetect();
					if(!gbt_USB_Detected)
					{
						break;
					}
					if(gbt_USB_Connect_Flag)
					{
					    if(gbt_USER_Remove_Flag)
						{
					        gb_cmd_timeout=1;
						    break;
						}
					} 
					else
					{
				    	if((--gdw_USB_CountDown==0)&&(!gb_USB_ISR_Detected)) 
						{
							gb_cmd_timeout=1;
				    	  	break;							
				    	}
					}
				}
				EA=0;                                       // 表示有 SCSI CMD 進入 關閉中斷避免常常進入			
				if((!gbt_USB_Detected)||(gb_cmd_timeout==1))  //080925chiayen modify
				{
					USB_DisConnect();
					set_clock_mode(CLOCK_MODE_MP3); 
					InitFlash();
					break;
				}
				gbt_USB_CMD_IN = 0;
				SD_Card_Detect();		
				gbt_USB_Connect_Flag =1; // 081208 jay add			
				Save_CBW_Packet();
				Decode_CBW_Command();                             // 解CBW和記錄相關手續		    
			}

			if(gw_USBDisplayTime==0)
			{
				USB_Mode_Disp();
			}

			if (gc_USBStage == BulkInReadSectorsStage) 
			{
				USB_REG[0xD2]      &= 0xDD;				//Disable Bulk-Out中斷
				ReadSectors();			    
				USB_REG[0xE9]       = 0x11;
				if (gc_ErrorCode == SET_ABRT) 
				{
					gc_RequestSenseCode = 0x06;        //ECC Error				
					gdw_dCBW_DataXferLength.LW = ((LWORD)TotalXferPageNum.WD) << 9;
					gc_bCSWStatus = 0x01;
				}
				else if (gc_ErrorCode == ID_NOT_FND) 
				{
					gc_RequestSenseCode = 0x07;        				//over range
					gdw_dCBW_DataXferLength.LW = ((LWORD)TotalXferPageNum.WD) << 9;
					gc_bCSWStatus = 0x01;
				}
				else 
				{
					gdw_dCBW_DataXferLength.LW = 0;
				}
				gc_USBStage = CSWStage;                                   // 進入Comand Status Wrapper
			}
			if (gc_USBStage == BulkOutWriteSectorsStage) 
			{
				USB_REG[0xD2]      &= 0xDD;				//Disable Bulk-Out中斷
				USB_REG[0x11]       = 0x01;   //HW auto ACK 
				WriteSectors();
				USB_REG[0x11]       = 0x00;
				USB_REG[0xE9]       = 0x22;

				if (gc_ErrorCode == SET_ABRT) 
				{
					gc_bCSWStatus = 0x01;
					gc_RequestSenseCode = 0x08;       					// write error 
				}
				else if (gc_ErrorCode == ID_NOT_FND) 
				{
					gc_RequestSenseCode = 0x07;      					//over range
					gc_bCSWStatus = 0x01;
				}
				else 
				{
					gc_bCSWStatus = 0x00;
					gc_RequestSenseCode = 0xFF;                        // normal
				}
				gdw_dCBW_DataXferLength.LW = 0;
				gc_USBStage = CSWStage;
			}
			if (gc_USBStage == BulkInResponseStage) 
			{                          // '4' BulkInProcess
				USB_REG[0xD2]      &= 0xDD;				//Disable Bulk-Out中斷
				if (gbt_XferNormalResponseData_or_ModeSense) 
				{                      // '1':Normal
			   		if (COMD_IN[0] == 0x23) 
					{
						gdw_dCBW_DataXferLength.WD[1] = 0x00;
						USB_REG[0x16]  = 0x00;
						USB_REG[0x15]  = 0x0C;
						USB_REG[0xA1] |= 0x01;
						while (USB_REG[0xA1] & 0x01)
						{
							USB_PlugDetect();  // 081014 Jay add for usb plug out
							if(!gbt_USB_Detected) break;
						}
						USB_REG[0xE9]  = 0x01;
			   		}
			   		else 
					{
						while (gdw_dCBW_DataXferLength.WD[1]) 
						{
							if (gdw_dCBW_DataXferLength.WD[1] > 64) 
							{
								gdw_dCBW_DataXferLength.WD[1] = gdw_dCBW_DataXferLength.WD[1] - 64;
					       		USB_REG[0x16] = 0x00;
								USB_REG[0x15] = 0x40;
							}
							else 
							{
					       		USB_REG[0x16] = gdw_dCBW_DataXferLength.BY[2] & 0x0F;
								USB_REG[0x15] = gdw_dCBW_DataXferLength.BY[3];
					       		gdw_dCBW_DataXferLength.WD[1] = 0x00;
					       	}
							USB_REG[0xA1] |= 0x01;
							while (USB_REG[0xA1] & 0x01)
							{  //081014 Jay add for usb plug out
								USB_PlugDetect();
								if(!gbt_USB_Detected) break;
							}
							USB_REG[0xE9]  = 0x01;
						}
		   			}
				}
				else 
				{
					if (COMD_IN[0] == 0x1A) 
					{
						gdw_dCBW_DataXferLength.WD[1] = 0x00;
						USB_REG[0x15]  = 0x04;
						USB_REG[0x16]  = 0x00;
						USB_REG[0xA1] |= 0x01;
						while (USB_REG[0xA1] & 0x01)
						{  //081014 Jay add for usb plug out
								USB_PlugDetect();
								if(!gbt_USB_Detected) break;
						}
						USB_REG[0xE9]  = 0x01;
					}
					else 
					{
						gdw_dCBW_DataXferLength.WD[1] = 0x00;
						USB_REG[0x15]  = 0x08;
						USB_REG[0x16]  = 0x00;
						USB_REG[0xA1] |= 0x01;
						while (USB_REG[0xA1] & 0x01)
						{  //081014 Jay add for usb plug out
								USB_PlugDetect();
								if(!gbt_USB_Detected) break;
						}
						USB_REG[0xE9]  = 0x01;
					}
					gbt_XferNormalResponseData_or_ModeSense = NormalResponseData;// 將預設設為一般型
				}
				gc_USBStage = CSWStage;
			}
			if (gc_USBStage == BulkStallStage) 
			{
				StallBulkRW();
				gc_USBStage = CSWStage;
			}
			if (gc_USBStage == BulkInReadBufferStage) 
			{
				USB_REG[0xD2]      &= 0xDD;				//Disable Bulk-Out中斷
				NoCard_ReadSectors();		    
				USB_REG[0xE9]       = 0x11;
				gdw_dCBW_DataXferLength.LW = 0;			
				gc_USBStage = CSWStage;                                   // 進入Comand Status Wrapper			                          
			}
			if (gc_USBStage == BulkOutWriteBufferStage) 
			{
				USB_REG[0xD2]      &= 0xDD;				//Disable Bulk-Out中斷
				USB_REG[0x11]       = 0x01;   //HW auto ACK 
				NoCard_WriteSectors();			
				USB_REG[0x11]       = 0x00;
				USB_REG[0xE9]       = 0x22;
				gdw_dCBW_DataXferLength.LW = 0;
				gc_USBStage = CSWStage;
			}				
			if (gc_USBStage == CSWStage) 
			{
				gc_USBStage = CBWStage;                                   // 重新準備收下一筆command
				USB_BUF_Bank0[ 0] = 'U';					// 以下由SetCSWData expand
				USB_BUF_Bank0[ 1] = 'S';
				USB_BUF_Bank0[ 2] = 'B';
				USB_BUF_Bank0[ 3] = 'S';
				USB_BUF_Bank0[ 4] = dCBW_Tag[0];
				USB_BUF_Bank0[ 5] = dCBW_Tag[1];
				USB_BUF_Bank0[ 6] = dCBW_Tag[2];
				USB_BUF_Bank0[ 7] = dCBW_Tag[3];
				USB_BUF_Bank0[ 8] = gdw_dCBW_DataXferLength.BY[3];                  // LSB 記錄剩下未被傳輸的資料
				USB_BUF_Bank0[ 9] = gdw_dCBW_DataXferLength.BY[2];                  //     記錄剩下未被傳輸的資料
				USB_BUF_Bank0[10] = gdw_dCBW_DataXferLength.BY[1];                  //     記錄剩下未被傳輸的資料
				USB_BUF_Bank0[11] = gdw_dCBW_DataXferLength.BY[0];                  // MSB 記錄剩下未被傳輸的資料
				USB_BUF_Bank0[12] = gc_bCSWStatus;                                 // Command Status 見BulkOnly P.15說明各種碼的情形
				USB_REG[0x2B]  = 0x00; 
				USB_REG[0x16]  = 0x00;
				USB_REG[0x15]  = 0x0D;
				USB_REG[0xA1] |= 0x01;
				while (USB_REG[0xA1] & 0x01)
				{  //081014 Jay add for usb plug out
					USB_PlugDetect();
					if(!gbt_USB_Detected) break;
				}
			}
			USB_REG[0xE9]  = 0x01;			
			USB_REG[0xD2]  |= 0x02;	//Enable Bulk-Out中斷
			USB_REG[0xA1]  |= 0x02;		//下一筆31Byte Bulk-Out
		}
	}
}
Ejemplo n.º 12
0
int highlevelformat(void * DriveData, UINT BaseSectorNumber)
{
    int              FATType;
    int        SystemSectors,
               RootDirSectors,
               FATSectors,
               Written;
    int             FatCount,
                    StartOfFAT,
                    InfoSector;
    int		i, y;
    FS_BootRecord       *PBR;
    kal_uint8 MediaDescriptor;
    int Result   = RTF_NO_ERROR;

    /* HLF - 1 - Read the PBR sector */
    ///* FIXME */ DrvDirect.ReadSector(SectorBuffer     /* Buffer */ ,
    //                                 BaseSectorNumber /* Sector Number */);
    ReadSectors(DriveData, BaseSectorNumber, 1, MSDC_Sector);

    PBR = (FS_BootRecord*)&MSDC_Sector;

    /* HLF - 2 - Setup PBR sector content and attributes */
    {
        if (PBR->BP.SectorsOnDisk != 0)
            PBR->BP.TotalSectors = PBR->BP.SectorsOnDisk;

        if (PBR->Signature != 0xAA55 ||
                //PBR->BP.TotalSectors > Par.Partition.Sectors ||
                PBR->BP.TotalSectors > (gSD->mCSD.capacity/512) ||
                PBR->BP.BytesPerSector != 512 ||
                PBR->BP.SectorsPerCluster == 0 ||
                PBR->BP.ReservedSectors == 0 ||
                PBR->BP.NumberOfFATs == 0)
        {
            return FS_INVALID_FILE_SYSTEM;
        }

        FATSectors     = (PBR->BP.SectorsPerFAT) ? PBR->BP.SectorsPerFAT : PBR->BP.E._32.SectorsPerFAT;
        RootDirSectors = (PBR->BP.DirEntries * 32 + (PBR->BP.BytesPerSector - 1)) / PBR->BP.BytesPerSector;

        Written        = PBR->BP.TotalSectors
                         - PBR->BP.ReservedSectors
                         - PBR->BP.NumberOfFATs * FATSectors
                         - RootDirSectors;
        Written = Written / PBR->BP.SectorsPerCluster;

        if (Written <= 0xFF4L)            FATType = 12;
        else if (Written <= 0xFFF4l)      FATType = 16;
        else if (Written <= 0xFFFFFF4l)   FATType = 32;
        else             return FS_INVALID_FILE_SYSTEM;
        Written = 0;

        if (FATType == 32)
        {
            RootDirSectors = PBR->BP.SectorsPerCluster;

            if (PBR->BP.E._32.RootDirCluster != 2)
            {
                PBR->BP.E._32.RootDirCluster = 2;
                /*
                Result = RTFSeek(Drive, 0, RTF_FILE_BEGIN);
                if (Result < RTF_NO_ERROR) return Result;

                Result = RTFWrite(Drive, (void*)PBR, SECTOR_SIZE, NULL);
                if (Result < RTF_NO_ERROR) return Result;
                */
                //above seek and write seems mean write to specific sector
                WriteSectors(DriveData, BaseSectorNumber , 1, (void *)PBR);

                /*
                   Result = RTFSeek(Drive, PBR->BP.E._32.BackupBootSector * SECTOR_SIZE, RTF_FILE_BEGIN);
                   if (Result < RTF_NO_ERROR) return Result;

                   Result = RTFWrite(Drive, (void*)PBR, SECTOR_SIZE, NULL);
                   if (Result < RTF_NO_ERROR) return Result;
                   */
                WriteSectors(DriveData, BaseSectorNumber + PBR->BP.E._32.BackupBootSector , 1, (void *)PBR);
            }
        }

        SystemSectors  = PBR->BP.ReservedSectors
                         + PBR->BP.NumberOfFATs * FATSectors
                         + RootDirSectors;

        FatCount       = PBR->BP.NumberOfFATs;
        StartOfFAT     = PBR->BP.ReservedSectors;
        InfoSector     = PBR->BP.E._32.FSInfoSector;
    }

    /*we get MediaDescriptor for step 6 usage, since we will clear MSDC_Sector*/
    MediaDescriptor = PBR->BP.MediaDescriptor;
    /*we need MSDC_Sector to be 512-byte-0 now*/
    kal_mem_set(MSDC_Sector, 0, 512);

    /* HLF - 3 - Formating cont, FAT32 reserved sector write down */
    {

        if ((FATType == 32) && (InfoSector > 0) && (InfoSector < StartOfFAT))
        {
            /* FIXME */
            //DrvDirect.ZeroSector( BaseSectorNumber + InfoSector /* Start Sector Number */ ,
            //                      1                             /* Zero Sector Count   */ );
            WriteSectors(DriveData, BaseSectorNumber + InfoSector, 1, MSDC_Sector);
        }
    }

    SD_startFastFormat();
    /* HLF - 4 - Formating cont, start, FAT Table write down , remember FAT begin sector */
    {
        /* FIXME */
        //DrvDirect.ZeroSector( BaseSectorNumber + StartOfFAT /* Start Sector Number */ ,
        //                      FATSectors * FatCount         /* Zero Sector Count   */ );
#ifdef DRV_LSD
        WriteSectors(DriveData, BaseSectorNumber + StartOfFAT, FATSectors * FatCount , MSDC_Sector);
#else
        for(i = 0; i < FATSectors * FatCount; i++) {
            WriteSectors(DriveData, BaseSectorNumber + StartOfFAT + i, 1 , MSDC_Sector);
        }
#endif
    }
    /* HLF - 5 - Formating cont, Root directory write down */
    {
        int x;
        x = StartOfFAT + FATSectors * FatCount;
        /* FIXME */
        //DrvDirect.ZeroSector( BaseSectorNumber + x          /* Start Sector Number */ ,
        //                      RootDirSectors                /* Zero Sector Count   */ );
#ifdef DRV_LSD
        WriteSectors(DriveData, BaseSectorNumber + x, RootDirSectors , MSDC_Sector);
#else
        for(i = 0; i < RootDirSectors; i++) {
            WriteSectors(DriveData, BaseSectorNumber + x + i, 1 , MSDC_Sector);
        }
#endif
    }
    SD_closeFastFormat();
    /* HLF - 6 - Formating final, 1st FAT sector must be rewritten */
    {





        switch (FATType)
        {
        case 32:
        {
            //kal_uint32 * FPtr = (void*) ScratchSector;
            MSDC_Sector[2] = 0x0FFFFFFF; // this is for the root dir
            MSDC_Sector[1] = 0x0FFFFFFF;
            break;
        }
        case 16:
        {
            kal_uint16 * FPtr = (void*) MSDC_Sector;
            FPtr[1] = 0xFFFF;
            break;
        }
        case 12:
        {
            kal_uint8 *FPtr = (void *)MSDC_Sector;
            /* FIXME */ FPtr[2] = 0xFF;
            /* FIXME */ FPtr[1] = 0xFF;
            /* FIXME */ FPtr[0] = MediaDescriptor;
            break;
        }
        }
        for (i = 0, y = StartOfFAT;
                i < FatCount;
                i++  , y+= FATSectors)
        {
            ///* FIXME */ DrvDirect.WriteSector(SectorBuffer     /* Buffer */ ,
            //                              BaseSectorNumber + y /* Sector Number */);
            WriteSectors(DriveData, BaseSectorNumber + y, 1 , MSDC_Sector);
        }
    }
    /* HLF - 7 - The END */
    return FS_NO_ERROR;
}