NorFlashDxe.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. /** @file NorFlashDxe.c
  2. Copyright (c) 2011 - 2014, ARM Ltd. All rights reserved.<BR>
  3. SPDX-License-Identifier: BSD-2-Clause-Patent
  4. **/
  5. #include <Library/UefiLib.h>
  6. #include <Library/BaseMemoryLib.h>
  7. #include <Library/MemoryAllocationLib.h>
  8. #include <Library/UefiBootServicesTableLib.h>
  9. #include <Library/PcdLib.h>
  10. #include "NorFlashDxe.h"
  11. STATIC EFI_EVENT mNorFlashVirtualAddrChangeEvent;
  12. //
  13. // Global variable declarations
  14. //
  15. NOR_FLASH_INSTANCE **mNorFlashInstances;
  16. UINT32 mNorFlashDeviceCount;
  17. NOR_FLASH_INSTANCE mNorFlashInstanceTemplate = {
  18. NOR_FLASH_SIGNATURE, // Signature
  19. NULL, // Handle ... NEED TO BE FILLED
  20. 0, // DeviceBaseAddress ... NEED TO BE FILLED
  21. 0, // RegionBaseAddress ... NEED TO BE FILLED
  22. 0, // Size ... NEED TO BE FILLED
  23. 0, // StartLba
  24. {
  25. EFI_BLOCK_IO_PROTOCOL_REVISION2, // Revision
  26. NULL, // Media ... NEED TO BE FILLED
  27. NorFlashBlockIoReset, // Reset;
  28. NorFlashBlockIoReadBlocks, // ReadBlocks
  29. NorFlashBlockIoWriteBlocks, // WriteBlocks
  30. NorFlashBlockIoFlushBlocks // FlushBlocks
  31. }, // BlockIoProtocol
  32. {
  33. 0, // MediaId ... NEED TO BE FILLED
  34. FALSE, // RemovableMedia
  35. TRUE, // MediaPresent
  36. FALSE, // LogicalPartition
  37. FALSE, // ReadOnly
  38. FALSE, // WriteCaching;
  39. 0, // BlockSize ... NEED TO BE FILLED
  40. 4, // IoAlign
  41. 0, // LastBlock ... NEED TO BE FILLED
  42. 0, // LowestAlignedLba
  43. 1, // LogicalBlocksPerPhysicalBlock
  44. }, //Media;
  45. {
  46. EFI_DISK_IO_PROTOCOL_REVISION, // Revision
  47. NorFlashDiskIoReadDisk, // ReadDisk
  48. NorFlashDiskIoWriteDisk // WriteDisk
  49. },
  50. {
  51. FvbGetAttributes, // GetAttributes
  52. FvbSetAttributes, // SetAttributes
  53. FvbGetPhysicalAddress, // GetPhysicalAddress
  54. FvbGetBlockSize, // GetBlockSize
  55. FvbRead, // Read
  56. FvbWrite, // Write
  57. FvbEraseBlocks, // EraseBlocks
  58. NULL, //ParentHandle
  59. }, // FvbProtoccol;
  60. NULL, // ShadowBuffer
  61. {
  62. {
  63. {
  64. HARDWARE_DEVICE_PATH,
  65. HW_VENDOR_DP,
  66. {
  67. (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End)),
  68. (UINT8)(OFFSET_OF (NOR_FLASH_DEVICE_PATH, End) >> 8)
  69. }
  70. },
  71. { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } }, // GUID ... NEED TO BE FILLED
  72. },
  73. 0, // Index
  74. {
  75. END_DEVICE_PATH_TYPE,
  76. END_ENTIRE_DEVICE_PATH_SUBTYPE,
  77. { sizeof (EFI_DEVICE_PATH_PROTOCOL), 0 }
  78. }
  79. } // DevicePath
  80. };
  81. EFI_STATUS
  82. NorFlashCreateInstance (
  83. IN UINTN NorFlashDeviceBase,
  84. IN UINTN NorFlashRegionBase,
  85. IN UINTN NorFlashSize,
  86. IN UINT32 Index,
  87. IN UINT32 BlockSize,
  88. IN BOOLEAN SupportFvb,
  89. OUT NOR_FLASH_INSTANCE** NorFlashInstance
  90. )
  91. {
  92. EFI_STATUS Status;
  93. NOR_FLASH_INSTANCE* Instance;
  94. ASSERT(NorFlashInstance != NULL);
  95. Instance = AllocateRuntimeCopyPool (sizeof(NOR_FLASH_INSTANCE),&mNorFlashInstanceTemplate);
  96. if (Instance == NULL) {
  97. return EFI_OUT_OF_RESOURCES;
  98. }
  99. Instance->DeviceBaseAddress = NorFlashDeviceBase;
  100. Instance->RegionBaseAddress = NorFlashRegionBase;
  101. Instance->Size = NorFlashSize;
  102. Instance->BlockIoProtocol.Media = &Instance->Media;
  103. Instance->Media.MediaId = Index;
  104. Instance->Media.BlockSize = BlockSize;
  105. Instance->Media.LastBlock = (NorFlashSize / BlockSize)-1;
  106. CopyGuid (&Instance->DevicePath.Vendor.Guid, &gEfiCallerIdGuid);
  107. Instance->DevicePath.Index = (UINT8)Index;
  108. Instance->ShadowBuffer = AllocateRuntimePool (BlockSize);;
  109. if (Instance->ShadowBuffer == NULL) {
  110. return EFI_OUT_OF_RESOURCES;
  111. }
  112. if (SupportFvb) {
  113. NorFlashFvbInitialize (Instance);
  114. Status = gBS->InstallMultipleProtocolInterfaces (
  115. &Instance->Handle,
  116. &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
  117. &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol,
  118. &gEfiFirmwareVolumeBlockProtocolGuid, &Instance->FvbProtocol,
  119. NULL
  120. );
  121. if (EFI_ERROR(Status)) {
  122. FreePool (Instance);
  123. return Status;
  124. }
  125. } else {
  126. Status = gBS->InstallMultipleProtocolInterfaces (
  127. &Instance->Handle,
  128. &gEfiDevicePathProtocolGuid, &Instance->DevicePath,
  129. &gEfiBlockIoProtocolGuid, &Instance->BlockIoProtocol,
  130. &gEfiDiskIoProtocolGuid, &Instance->DiskIoProtocol,
  131. NULL
  132. );
  133. if (EFI_ERROR(Status)) {
  134. FreePool (Instance);
  135. return Status;
  136. }
  137. }
  138. *NorFlashInstance = Instance;
  139. return Status;
  140. }
  141. UINT32
  142. NorFlashReadStatusRegister (
  143. IN NOR_FLASH_INSTANCE *Instance,
  144. IN UINTN SR_Address
  145. )
  146. {
  147. // Prepare to read the status register
  148. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_STATUS_REGISTER);
  149. return MmioRead32 (Instance->DeviceBaseAddress);
  150. }
  151. STATIC
  152. BOOLEAN
  153. NorFlashBlockIsLocked (
  154. IN NOR_FLASH_INSTANCE *Instance,
  155. IN UINTN BlockAddress
  156. )
  157. {
  158. UINT32 LockStatus;
  159. // Send command for reading device id
  160. SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
  161. // Read block lock status
  162. LockStatus = MmioRead32 (CREATE_NOR_ADDRESS(BlockAddress, 2));
  163. // Decode block lock status
  164. LockStatus = FOLD_32BIT_INTO_16BIT(LockStatus);
  165. if ((LockStatus & 0x2) != 0) {
  166. DEBUG((EFI_D_ERROR, "NorFlashBlockIsLocked: WARNING: Block LOCKED DOWN\n"));
  167. }
  168. return ((LockStatus & 0x1) != 0);
  169. }
  170. STATIC
  171. EFI_STATUS
  172. NorFlashUnlockSingleBlock (
  173. IN NOR_FLASH_INSTANCE *Instance,
  174. IN UINTN BlockAddress
  175. )
  176. {
  177. UINT32 LockStatus;
  178. // Raise the Task Priority Level to TPL_NOTIFY to serialise all its operations
  179. // and to protect shared data structures.
  180. if (FeaturePcdGet (PcdNorFlashCheckBlockLocked) == TRUE) {
  181. do {
  182. // Request a lock setup
  183. SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
  184. // Request an unlock
  185. SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
  186. // Send command for reading device id
  187. SEND_NOR_COMMAND (BlockAddress, 2, P30_CMD_READ_DEVICE_ID);
  188. // Read block lock status
  189. LockStatus = MmioRead32 (CREATE_NOR_ADDRESS(BlockAddress, 2));
  190. // Decode block lock status
  191. LockStatus = FOLD_32BIT_INTO_16BIT(LockStatus);
  192. } while ((LockStatus & 0x1) == 1);
  193. } else {
  194. // Request a lock setup
  195. SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_LOCK_BLOCK_SETUP);
  196. // Request an unlock
  197. SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_UNLOCK_BLOCK);
  198. // Wait until the status register gives us the all clear
  199. do {
  200. LockStatus = NorFlashReadStatusRegister (Instance, BlockAddress);
  201. } while ((LockStatus & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
  202. }
  203. // Put device back into Read Array mode
  204. SEND_NOR_COMMAND (BlockAddress, 0, P30_CMD_READ_ARRAY);
  205. DEBUG((DEBUG_BLKIO, "UnlockSingleBlock: BlockAddress=0x%08x\n", BlockAddress));
  206. return EFI_SUCCESS;
  207. }
  208. STATIC
  209. EFI_STATUS
  210. NorFlashUnlockSingleBlockIfNecessary (
  211. IN NOR_FLASH_INSTANCE *Instance,
  212. IN UINTN BlockAddress
  213. )
  214. {
  215. EFI_STATUS Status;
  216. Status = EFI_SUCCESS;
  217. if (NorFlashBlockIsLocked (Instance, BlockAddress) == TRUE) {
  218. Status = NorFlashUnlockSingleBlock (Instance, BlockAddress);
  219. }
  220. return Status;
  221. }
  222. /**
  223. * The following function presumes that the block has already been unlocked.
  224. **/
  225. STATIC
  226. EFI_STATUS
  227. NorFlashEraseSingleBlock (
  228. IN NOR_FLASH_INSTANCE *Instance,
  229. IN UINTN BlockAddress
  230. )
  231. {
  232. EFI_STATUS Status;
  233. UINT32 StatusRegister;
  234. Status = EFI_SUCCESS;
  235. // Request a block erase and then confirm it
  236. SEND_NOR_COMMAND(BlockAddress, 0, P30_CMD_BLOCK_ERASE_SETUP);
  237. SEND_NOR_COMMAND(BlockAddress, 0, P30_CMD_BLOCK_ERASE_CONFIRM);
  238. // Wait until the status register gives us the all clear
  239. do {
  240. StatusRegister = NorFlashReadStatusRegister (Instance, BlockAddress);
  241. } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
  242. if (StatusRegister & P30_SR_BIT_VPP) {
  243. DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: VPP Range Error\n", BlockAddress));
  244. Status = EFI_DEVICE_ERROR;
  245. }
  246. if ((StatusRegister & (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) == (P30_SR_BIT_ERASE | P30_SR_BIT_PROGRAM)) {
  247. DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Command Sequence Error\n", BlockAddress));
  248. Status = EFI_DEVICE_ERROR;
  249. }
  250. if (StatusRegister & P30_SR_BIT_ERASE) {
  251. DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Block Erase Error StatusRegister:0x%X\n", BlockAddress, StatusRegister));
  252. Status = EFI_DEVICE_ERROR;
  253. }
  254. if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
  255. // The debug level message has been reduced because a device lock might happen. In this case we just retry it ...
  256. DEBUG((EFI_D_INFO,"EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error\n", BlockAddress));
  257. Status = EFI_WRITE_PROTECTED;
  258. }
  259. if (EFI_ERROR(Status)) {
  260. // Clear the Status Register
  261. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
  262. }
  263. // Put device back into Read Array mode
  264. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
  265. return Status;
  266. }
  267. /**
  268. * This function unlock and erase an entire NOR Flash block.
  269. **/
  270. EFI_STATUS
  271. NorFlashUnlockAndEraseSingleBlock (
  272. IN NOR_FLASH_INSTANCE *Instance,
  273. IN UINTN BlockAddress
  274. )
  275. {
  276. EFI_STATUS Status;
  277. UINTN Index;
  278. EFI_TPL OriginalTPL;
  279. if (!EfiAtRuntime ()) {
  280. // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
  281. OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
  282. } else {
  283. // This initialization is only to prevent the compiler to complain about the
  284. // use of uninitialized variables
  285. OriginalTPL = TPL_HIGH_LEVEL;
  286. }
  287. Index = 0;
  288. // The block erase might fail a first time (SW bug ?). Retry it ...
  289. do {
  290. // Unlock the block if we have to
  291. Status = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
  292. if (EFI_ERROR (Status)) {
  293. break;
  294. }
  295. Status = NorFlashEraseSingleBlock (Instance, BlockAddress);
  296. Index++;
  297. } while ((Index < NOR_FLASH_ERASE_RETRY) && (Status == EFI_WRITE_PROTECTED));
  298. if (Index == NOR_FLASH_ERASE_RETRY) {
  299. DEBUG((EFI_D_ERROR,"EraseSingleBlock(BlockAddress=0x%08x: Block Locked Error (try to erase %d times)\n", BlockAddress,Index));
  300. }
  301. if (!EfiAtRuntime ()) {
  302. // Interruptions can resume.
  303. gBS->RestoreTPL (OriginalTPL);
  304. }
  305. return Status;
  306. }
  307. STATIC
  308. EFI_STATUS
  309. NorFlashWriteSingleWord (
  310. IN NOR_FLASH_INSTANCE *Instance,
  311. IN UINTN WordAddress,
  312. IN UINT32 WriteData
  313. )
  314. {
  315. EFI_STATUS Status;
  316. UINT32 StatusRegister;
  317. Status = EFI_SUCCESS;
  318. // Request a write single word command
  319. SEND_NOR_COMMAND(WordAddress, 0, P30_CMD_WORD_PROGRAM_SETUP);
  320. // Store the word into NOR Flash;
  321. MmioWrite32 (WordAddress, WriteData);
  322. // Wait for the write to complete and then check for any errors; i.e. check the Status Register
  323. do {
  324. // Prepare to read the status register
  325. StatusRegister = NorFlashReadStatusRegister (Instance, WordAddress);
  326. // The chip is busy while the WRITE bit is not asserted
  327. } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
  328. // Perform a full status check:
  329. // Mask the relevant bits of Status Register.
  330. // Everything should be zero, if not, we have a problem
  331. if (StatusRegister & P30_SR_BIT_VPP) {
  332. DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): VPP Range Error\n",WordAddress));
  333. Status = EFI_DEVICE_ERROR;
  334. }
  335. if (StatusRegister & P30_SR_BIT_PROGRAM) {
  336. DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): Program Error\n",WordAddress));
  337. Status = EFI_DEVICE_ERROR;
  338. }
  339. if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
  340. DEBUG((EFI_D_ERROR,"NorFlashWriteSingleWord(WordAddress:0x%X): Device Protect Error\n",WordAddress));
  341. Status = EFI_DEVICE_ERROR;
  342. }
  343. if (!EFI_ERROR(Status)) {
  344. // Clear the Status Register
  345. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
  346. }
  347. // Put device back into Read Array mode
  348. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
  349. return Status;
  350. }
  351. /*
  352. * Writes data to the NOR Flash using the Buffered Programming method.
  353. *
  354. * The maximum size of the on-chip buffer is 32-words, because of hardware restrictions.
  355. * Therefore this function will only handle buffers up to 32 words or 128 bytes.
  356. * To deal with larger buffers, call this function again.
  357. *
  358. * This function presumes that both the TargetAddress and the TargetAddress+BufferSize
  359. * exist entirely within the NOR Flash. Therefore these conditions will not be checked here.
  360. *
  361. * In buffered programming, if the target address not at the beginning of a 32-bit word boundary,
  362. * then programming time is doubled and power consumption is increased.
  363. * Therefore, it is a requirement to align buffer writes to 32-bit word boundaries.
  364. * i.e. the last 4 bits of the target start address must be zero: 0x......00
  365. */
  366. EFI_STATUS
  367. NorFlashWriteBuffer (
  368. IN NOR_FLASH_INSTANCE *Instance,
  369. IN UINTN TargetAddress,
  370. IN UINTN BufferSizeInBytes,
  371. IN UINT32 *Buffer
  372. )
  373. {
  374. EFI_STATUS Status;
  375. UINTN BufferSizeInWords;
  376. UINTN Count;
  377. volatile UINT32 *Data;
  378. UINTN WaitForBuffer;
  379. BOOLEAN BufferAvailable;
  380. UINT32 StatusRegister;
  381. WaitForBuffer = MAX_BUFFERED_PROG_ITERATIONS;
  382. BufferAvailable = FALSE;
  383. // Check that the target address does not cross a 32-word boundary.
  384. if ((TargetAddress & BOUNDARY_OF_32_WORDS) != 0) {
  385. return EFI_INVALID_PARAMETER;
  386. }
  387. // Check there are some data to program
  388. if (BufferSizeInBytes == 0) {
  389. return EFI_BUFFER_TOO_SMALL;
  390. }
  391. // Check that the buffer size does not exceed the maximum hardware buffer size on chip.
  392. if (BufferSizeInBytes > P30_MAX_BUFFER_SIZE_IN_BYTES) {
  393. return EFI_BAD_BUFFER_SIZE;
  394. }
  395. // Check that the buffer size is a multiple of 32-bit words
  396. if ((BufferSizeInBytes % 4) != 0) {
  397. return EFI_BAD_BUFFER_SIZE;
  398. }
  399. // Pre-programming conditions checked, now start the algorithm.
  400. // Prepare the data destination address
  401. Data = (UINT32 *)TargetAddress;
  402. // Check the availability of the buffer
  403. do {
  404. // Issue the Buffered Program Setup command
  405. SEND_NOR_COMMAND(TargetAddress, 0, P30_CMD_BUFFERED_PROGRAM_SETUP);
  406. // Read back the status register bit#7 from the same address
  407. if (((*Data) & P30_SR_BIT_WRITE) == P30_SR_BIT_WRITE) {
  408. BufferAvailable = TRUE;
  409. }
  410. // Update the loop counter
  411. WaitForBuffer--;
  412. } while ((WaitForBuffer > 0) && (BufferAvailable == FALSE));
  413. // The buffer was not available for writing
  414. if (WaitForBuffer == 0) {
  415. Status = EFI_DEVICE_ERROR;
  416. goto EXIT;
  417. }
  418. // From now on we work in 32-bit words
  419. BufferSizeInWords = BufferSizeInBytes / (UINTN)4;
  420. // Write the word count, which is (buffer_size_in_words - 1),
  421. // because word count 0 means one word.
  422. SEND_NOR_COMMAND(TargetAddress, 0, (BufferSizeInWords - 1));
  423. // Write the data to the NOR Flash, advancing each address by 4 bytes
  424. for(Count=0; Count < BufferSizeInWords; Count++, Data++, Buffer++) {
  425. MmioWrite32 ((UINTN)Data, *Buffer);
  426. }
  427. // Issue the Buffered Program Confirm command, to start the programming operation
  428. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_BUFFERED_PROGRAM_CONFIRM);
  429. // Wait for the write to complete and then check for any errors; i.e. check the Status Register
  430. do {
  431. StatusRegister = NorFlashReadStatusRegister (Instance, TargetAddress);
  432. // The chip is busy while the WRITE bit is not asserted
  433. } while ((StatusRegister & P30_SR_BIT_WRITE) != P30_SR_BIT_WRITE);
  434. // Perform a full status check:
  435. // Mask the relevant bits of Status Register.
  436. // Everything should be zero, if not, we have a problem
  437. Status = EFI_SUCCESS;
  438. if (StatusRegister & P30_SR_BIT_VPP) {
  439. DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): VPP Range Error\n", TargetAddress));
  440. Status = EFI_DEVICE_ERROR;
  441. }
  442. if (StatusRegister & P30_SR_BIT_PROGRAM) {
  443. DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): Program Error\n", TargetAddress));
  444. Status = EFI_DEVICE_ERROR;
  445. }
  446. if (StatusRegister & P30_SR_BIT_BLOCK_LOCKED) {
  447. DEBUG((EFI_D_ERROR,"NorFlashWriteBuffer(TargetAddress:0x%X): Device Protect Error\n",TargetAddress));
  448. Status = EFI_DEVICE_ERROR;
  449. }
  450. if (!EFI_ERROR(Status)) {
  451. // Clear the Status Register
  452. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_CLEAR_STATUS_REGISTER);
  453. }
  454. EXIT:
  455. // Put device back into Read Array mode
  456. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
  457. return Status;
  458. }
  459. STATIC
  460. EFI_STATUS
  461. NorFlashWriteFullBlock (
  462. IN NOR_FLASH_INSTANCE *Instance,
  463. IN EFI_LBA Lba,
  464. IN UINT32 *DataBuffer,
  465. IN UINT32 BlockSizeInWords
  466. )
  467. {
  468. EFI_STATUS Status;
  469. UINTN WordAddress;
  470. UINT32 WordIndex;
  471. UINTN BufferIndex;
  472. UINTN BlockAddress;
  473. UINTN BuffersInBlock;
  474. UINTN RemainingWords;
  475. EFI_TPL OriginalTPL;
  476. UINTN Cnt;
  477. Status = EFI_SUCCESS;
  478. // Get the physical address of the block
  479. BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSizeInWords * 4);
  480. // Start writing from the first address at the start of the block
  481. WordAddress = BlockAddress;
  482. if (!EfiAtRuntime ()) {
  483. // Raise TPL to TPL_HIGH to stop anyone from interrupting us.
  484. OriginalTPL = gBS->RaiseTPL (TPL_HIGH_LEVEL);
  485. } else {
  486. // This initialization is only to prevent the compiler to complain about the
  487. // use of uninitialized variables
  488. OriginalTPL = TPL_HIGH_LEVEL;
  489. }
  490. Status = NorFlashUnlockAndEraseSingleBlock (Instance, BlockAddress);
  491. if (EFI_ERROR(Status)) {
  492. DEBUG((EFI_D_ERROR, "WriteSingleBlock: ERROR - Failed to Unlock and Erase the single block at 0x%X\n", BlockAddress));
  493. goto EXIT;
  494. }
  495. // To speed up the programming operation, NOR Flash is programmed using the Buffered Programming method.
  496. // Check that the address starts at a 32-word boundary, i.e. last 7 bits must be zero
  497. if ((WordAddress & BOUNDARY_OF_32_WORDS) == 0x00) {
  498. // First, break the entire block into buffer-sized chunks.
  499. BuffersInBlock = (UINTN)(BlockSizeInWords * 4) / P30_MAX_BUFFER_SIZE_IN_BYTES;
  500. // Then feed each buffer chunk to the NOR Flash
  501. // If a buffer does not contain any data, don't write it.
  502. for(BufferIndex=0;
  503. BufferIndex < BuffersInBlock;
  504. BufferIndex++, WordAddress += P30_MAX_BUFFER_SIZE_IN_BYTES, DataBuffer += P30_MAX_BUFFER_SIZE_IN_WORDS
  505. ) {
  506. // Check the buffer to see if it contains any data (not set all 1s).
  507. for (Cnt = 0; Cnt < P30_MAX_BUFFER_SIZE_IN_WORDS; Cnt++) {
  508. if (~DataBuffer[Cnt] != 0 ) {
  509. // Some data found, write the buffer.
  510. Status = NorFlashWriteBuffer (Instance, WordAddress, P30_MAX_BUFFER_SIZE_IN_BYTES,
  511. DataBuffer);
  512. if (EFI_ERROR(Status)) {
  513. goto EXIT;
  514. }
  515. break;
  516. }
  517. }
  518. }
  519. // Finally, finish off any remaining words that are less than the maximum size of the buffer
  520. RemainingWords = BlockSizeInWords % P30_MAX_BUFFER_SIZE_IN_WORDS;
  521. if(RemainingWords != 0) {
  522. Status = NorFlashWriteBuffer (Instance, WordAddress, (RemainingWords * 4), DataBuffer);
  523. if (EFI_ERROR(Status)) {
  524. goto EXIT;
  525. }
  526. }
  527. } else {
  528. // For now, use the single word programming algorithm
  529. // It is unlikely that the NOR Flash will exist in an address which falls within a 32 word boundary range,
  530. // i.e. which ends in the range 0x......01 - 0x......7F.
  531. for(WordIndex=0; WordIndex<BlockSizeInWords; WordIndex++, DataBuffer++, WordAddress = WordAddress + 4) {
  532. Status = NorFlashWriteSingleWord (Instance, WordAddress, *DataBuffer);
  533. if (EFI_ERROR(Status)) {
  534. goto EXIT;
  535. }
  536. }
  537. }
  538. EXIT:
  539. if (!EfiAtRuntime ()) {
  540. // Interruptions can resume.
  541. gBS->RestoreTPL (OriginalTPL);
  542. }
  543. if (EFI_ERROR(Status)) {
  544. DEBUG((EFI_D_ERROR, "NOR FLASH Programming [WriteSingleBlock] failed at address 0x%08x. Exit Status = \"%r\".\n", WordAddress, Status));
  545. }
  546. return Status;
  547. }
  548. EFI_STATUS
  549. NorFlashWriteBlocks (
  550. IN NOR_FLASH_INSTANCE *Instance,
  551. IN EFI_LBA Lba,
  552. IN UINTN BufferSizeInBytes,
  553. IN VOID *Buffer
  554. )
  555. {
  556. UINT32 *pWriteBuffer;
  557. EFI_STATUS Status = EFI_SUCCESS;
  558. EFI_LBA CurrentBlock;
  559. UINT32 BlockSizeInWords;
  560. UINT32 NumBlocks;
  561. UINT32 BlockCount;
  562. // The buffer must be valid
  563. if (Buffer == NULL) {
  564. return EFI_INVALID_PARAMETER;
  565. }
  566. if(Instance->Media.ReadOnly == TRUE) {
  567. return EFI_WRITE_PROTECTED;
  568. }
  569. // We must have some bytes to read
  570. DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: BufferSizeInBytes=0x%x\n", BufferSizeInBytes));
  571. if(BufferSizeInBytes == 0) {
  572. return EFI_BAD_BUFFER_SIZE;
  573. }
  574. // The size of the buffer must be a multiple of the block size
  575. DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: BlockSize in bytes =0x%x\n", Instance->Media.BlockSize));
  576. if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
  577. return EFI_BAD_BUFFER_SIZE;
  578. }
  579. // All blocks must be within the device
  580. NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize ;
  581. DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: NumBlocks=%d, LastBlock=%ld, Lba=%ld.\n", NumBlocks, Instance->Media.LastBlock, Lba));
  582. if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
  583. DEBUG((EFI_D_ERROR, "NorFlashWriteBlocks: ERROR - Write will exceed last block.\n"));
  584. return EFI_INVALID_PARAMETER;
  585. }
  586. BlockSizeInWords = Instance->Media.BlockSize / 4;
  587. // Because the target *Buffer is a pointer to VOID, we must put all the data into a pointer
  588. // to a proper data type, so use *ReadBuffer
  589. pWriteBuffer = (UINT32 *)Buffer;
  590. CurrentBlock = Lba;
  591. for (BlockCount=0; BlockCount < NumBlocks; BlockCount++, CurrentBlock++, pWriteBuffer = pWriteBuffer + BlockSizeInWords) {
  592. DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: Writing block #%d\n", (UINTN)CurrentBlock));
  593. Status = NorFlashWriteFullBlock (Instance, CurrentBlock, pWriteBuffer, BlockSizeInWords);
  594. if (EFI_ERROR(Status)) {
  595. break;
  596. }
  597. }
  598. DEBUG((DEBUG_BLKIO, "NorFlashWriteBlocks: Exit Status = \"%r\".\n", Status));
  599. return Status;
  600. }
  601. #define BOTH_ALIGNED(a, b, align) ((((UINTN)(a) | (UINTN)(b)) & ((align) - 1)) == 0)
  602. /**
  603. Copy Length bytes from Source to Destination, using aligned accesses only.
  604. Note that this implementation uses memcpy() semantics rather then memmove()
  605. semantics, i.e., SourceBuffer and DestinationBuffer should not overlap.
  606. @param DestinationBuffer The target of the copy request.
  607. @param SourceBuffer The place to copy from.
  608. @param Length The number of bytes to copy.
  609. @return Destination
  610. **/
  611. STATIC
  612. VOID *
  613. AlignedCopyMem (
  614. OUT VOID *DestinationBuffer,
  615. IN CONST VOID *SourceBuffer,
  616. IN UINTN Length
  617. )
  618. {
  619. UINT8 *Destination8;
  620. CONST UINT8 *Source8;
  621. UINT32 *Destination32;
  622. CONST UINT32 *Source32;
  623. UINT64 *Destination64;
  624. CONST UINT64 *Source64;
  625. if (BOTH_ALIGNED(DestinationBuffer, SourceBuffer, 8) && Length >= 8) {
  626. Destination64 = DestinationBuffer;
  627. Source64 = SourceBuffer;
  628. while (Length >= 8) {
  629. *Destination64++ = *Source64++;
  630. Length -= 8;
  631. }
  632. Destination8 = (UINT8 *)Destination64;
  633. Source8 = (CONST UINT8 *)Source64;
  634. } else if (BOTH_ALIGNED(DestinationBuffer, SourceBuffer, 4) && Length >= 4) {
  635. Destination32 = DestinationBuffer;
  636. Source32 = SourceBuffer;
  637. while (Length >= 4) {
  638. *Destination32++ = *Source32++;
  639. Length -= 4;
  640. }
  641. Destination8 = (UINT8 *)Destination32;
  642. Source8 = (CONST UINT8 *)Source32;
  643. } else {
  644. Destination8 = DestinationBuffer;
  645. Source8 = SourceBuffer;
  646. }
  647. while (Length-- != 0) {
  648. *Destination8++ = *Source8++;
  649. }
  650. return DestinationBuffer;
  651. }
  652. EFI_STATUS
  653. NorFlashReadBlocks (
  654. IN NOR_FLASH_INSTANCE *Instance,
  655. IN EFI_LBA Lba,
  656. IN UINTN BufferSizeInBytes,
  657. OUT VOID *Buffer
  658. )
  659. {
  660. UINT32 NumBlocks;
  661. UINTN StartAddress;
  662. DEBUG((DEBUG_BLKIO, "NorFlashReadBlocks: BufferSize=0x%xB BlockSize=0x%xB LastBlock=%ld, Lba=%ld.\n",
  663. BufferSizeInBytes, Instance->Media.BlockSize, Instance->Media.LastBlock, Lba));
  664. // The buffer must be valid
  665. if (Buffer == NULL) {
  666. return EFI_INVALID_PARAMETER;
  667. }
  668. // Return if we have not any byte to read
  669. if (BufferSizeInBytes == 0) {
  670. return EFI_SUCCESS;
  671. }
  672. // The size of the buffer must be a multiple of the block size
  673. if ((BufferSizeInBytes % Instance->Media.BlockSize) != 0) {
  674. return EFI_BAD_BUFFER_SIZE;
  675. }
  676. // All blocks must be within the device
  677. NumBlocks = ((UINT32)BufferSizeInBytes) / Instance->Media.BlockSize ;
  678. if ((Lba + NumBlocks) > (Instance->Media.LastBlock + 1)) {
  679. DEBUG((EFI_D_ERROR, "NorFlashReadBlocks: ERROR - Read will exceed last block\n"));
  680. return EFI_INVALID_PARAMETER;
  681. }
  682. // Get the address to start reading from
  683. StartAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
  684. Lba,
  685. Instance->Media.BlockSize
  686. );
  687. // Put the device into Read Array mode
  688. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
  689. // Readout the data
  690. AlignedCopyMem (Buffer, (VOID *)StartAddress, BufferSizeInBytes);
  691. return EFI_SUCCESS;
  692. }
  693. EFI_STATUS
  694. NorFlashRead (
  695. IN NOR_FLASH_INSTANCE *Instance,
  696. IN EFI_LBA Lba,
  697. IN UINTN Offset,
  698. IN UINTN BufferSizeInBytes,
  699. OUT VOID *Buffer
  700. )
  701. {
  702. UINTN StartAddress;
  703. // The buffer must be valid
  704. if (Buffer == NULL) {
  705. return EFI_INVALID_PARAMETER;
  706. }
  707. // Return if we have not any byte to read
  708. if (BufferSizeInBytes == 0) {
  709. return EFI_SUCCESS;
  710. }
  711. if (((Lba * Instance->Media.BlockSize) + Offset + BufferSizeInBytes) > Instance->Size) {
  712. DEBUG ((EFI_D_ERROR, "NorFlashRead: ERROR - Read will exceed device size.\n"));
  713. return EFI_INVALID_PARAMETER;
  714. }
  715. // Get the address to start reading from
  716. StartAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
  717. Lba,
  718. Instance->Media.BlockSize
  719. );
  720. // Put the device into Read Array mode
  721. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
  722. // Readout the data
  723. AlignedCopyMem (Buffer, (VOID *)(StartAddress + Offset), BufferSizeInBytes);
  724. return EFI_SUCCESS;
  725. }
  726. /*
  727. Write a full or portion of a block. It must not span block boundaries; that is,
  728. Offset + *NumBytes <= Instance->Media.BlockSize.
  729. */
  730. EFI_STATUS
  731. NorFlashWriteSingleBlock (
  732. IN NOR_FLASH_INSTANCE *Instance,
  733. IN EFI_LBA Lba,
  734. IN UINTN Offset,
  735. IN OUT UINTN *NumBytes,
  736. IN UINT8 *Buffer
  737. )
  738. {
  739. EFI_STATUS TempStatus;
  740. UINT32 Tmp;
  741. UINT32 TmpBuf;
  742. UINT32 WordToWrite;
  743. UINT32 Mask;
  744. BOOLEAN DoErase;
  745. UINTN BytesToWrite;
  746. UINTN CurOffset;
  747. UINTN WordAddr;
  748. UINTN BlockSize;
  749. UINTN BlockAddress;
  750. UINTN PrevBlockAddress;
  751. PrevBlockAddress = 0;
  752. DEBUG ((DEBUG_BLKIO, "NorFlashWriteSingleBlock(Parameters: Lba=%ld, Offset=0x%x, *NumBytes=0x%x, Buffer @ 0x%08x)\n", Lba, Offset, *NumBytes, Buffer));
  753. // Detect WriteDisabled state
  754. if (Instance->Media.ReadOnly == TRUE) {
  755. DEBUG ((EFI_D_ERROR, "NorFlashWriteSingleBlock: ERROR - Can not write: Device is in WriteDisabled state.\n"));
  756. // It is in WriteDisabled state, return an error right away
  757. return EFI_ACCESS_DENIED;
  758. }
  759. // Cache the block size to avoid de-referencing pointers all the time
  760. BlockSize = Instance->Media.BlockSize;
  761. // The write must not span block boundaries.
  762. // We need to check each variable individually because adding two large values together overflows.
  763. if ( ( Offset >= BlockSize ) ||
  764. ( *NumBytes > BlockSize ) ||
  765. ( (Offset + *NumBytes) > BlockSize ) ) {
  766. DEBUG ((EFI_D_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
  767. return EFI_BAD_BUFFER_SIZE;
  768. }
  769. // We must have some bytes to write
  770. if (*NumBytes == 0) {
  771. DEBUG ((EFI_D_ERROR, "NorFlashWriteSingleBlock: ERROR - EFI_BAD_BUFFER_SIZE: (Offset=0x%x + NumBytes=0x%x) > BlockSize=0x%x\n", Offset, *NumBytes, BlockSize ));
  772. return EFI_BAD_BUFFER_SIZE;
  773. }
  774. // Pick 128bytes as a good start for word operations as opposed to erasing the
  775. // block and writing the data regardless if an erase is really needed.
  776. // It looks like most individual NV variable writes are smaller than 128bytes.
  777. if (*NumBytes <= 128) {
  778. // Check to see if we need to erase before programming the data into NOR.
  779. // If the destination bits are only changing from 1s to 0s we can just write.
  780. // After a block is erased all bits in the block is set to 1.
  781. // If any byte requires us to erase we just give up and rewrite all of it.
  782. DoErase = FALSE;
  783. BytesToWrite = *NumBytes;
  784. CurOffset = Offset;
  785. while (BytesToWrite > 0) {
  786. // Read full word from NOR, splice as required. A word is the smallest
  787. // unit we can write.
  788. TempStatus = NorFlashRead (Instance, Lba, CurOffset & ~(0x3), sizeof(Tmp), &Tmp);
  789. if (EFI_ERROR (TempStatus)) {
  790. return EFI_DEVICE_ERROR;
  791. }
  792. // Physical address of word in NOR to write.
  793. WordAddr = (CurOffset & ~(0x3)) + GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress,
  794. Lba, BlockSize);
  795. // The word of data that is to be written.
  796. TmpBuf = *((UINT32*)(Buffer + (*NumBytes - BytesToWrite)));
  797. // First do word aligned chunks.
  798. if ((CurOffset & 0x3) == 0) {
  799. if (BytesToWrite >= 4) {
  800. // Is the destination still in 'erased' state?
  801. if (~Tmp != 0) {
  802. // Check to see if we are only changing bits to zero.
  803. if ((Tmp ^ TmpBuf) & TmpBuf) {
  804. DoErase = TRUE;
  805. break;
  806. }
  807. }
  808. // Write this word to NOR
  809. WordToWrite = TmpBuf;
  810. CurOffset += sizeof(TmpBuf);
  811. BytesToWrite -= sizeof(TmpBuf);
  812. } else {
  813. // BytesToWrite < 4. Do small writes and left-overs
  814. Mask = ~((~0) << (BytesToWrite * 8));
  815. // Mask out the bytes we want.
  816. TmpBuf &= Mask;
  817. // Is the destination still in 'erased' state?
  818. if ((Tmp & Mask) != Mask) {
  819. // Check to see if we are only changing bits to zero.
  820. if ((Tmp ^ TmpBuf) & TmpBuf) {
  821. DoErase = TRUE;
  822. break;
  823. }
  824. }
  825. // Merge old and new data. Write merged word to NOR
  826. WordToWrite = (Tmp & ~Mask) | TmpBuf;
  827. CurOffset += BytesToWrite;
  828. BytesToWrite = 0;
  829. }
  830. } else {
  831. // Do multiple words, but starting unaligned.
  832. if (BytesToWrite > (4 - (CurOffset & 0x3))) {
  833. Mask = ((~0) << ((CurOffset & 0x3) * 8));
  834. // Mask out the bytes we want.
  835. TmpBuf &= Mask;
  836. // Is the destination still in 'erased' state?
  837. if ((Tmp & Mask) != Mask) {
  838. // Check to see if we are only changing bits to zero.
  839. if ((Tmp ^ TmpBuf) & TmpBuf) {
  840. DoErase = TRUE;
  841. break;
  842. }
  843. }
  844. // Merge old and new data. Write merged word to NOR
  845. WordToWrite = (Tmp & ~Mask) | TmpBuf;
  846. BytesToWrite -= (4 - (CurOffset & 0x3));
  847. CurOffset += (4 - (CurOffset & 0x3));
  848. } else {
  849. // Unaligned and fits in one word.
  850. Mask = (~((~0) << (BytesToWrite * 8))) << ((CurOffset & 0x3) * 8);
  851. // Mask out the bytes we want.
  852. TmpBuf = (TmpBuf << ((CurOffset & 0x3) * 8)) & Mask;
  853. // Is the destination still in 'erased' state?
  854. if ((Tmp & Mask) != Mask) {
  855. // Check to see if we are only changing bits to zero.
  856. if ((Tmp ^ TmpBuf) & TmpBuf) {
  857. DoErase = TRUE;
  858. break;
  859. }
  860. }
  861. // Merge old and new data. Write merged word to NOR
  862. WordToWrite = (Tmp & ~Mask) | TmpBuf;
  863. CurOffset += BytesToWrite;
  864. BytesToWrite = 0;
  865. }
  866. }
  867. //
  868. // Write the word to NOR.
  869. //
  870. BlockAddress = GET_NOR_BLOCK_ADDRESS (Instance->RegionBaseAddress, Lba, BlockSize);
  871. if (BlockAddress != PrevBlockAddress) {
  872. TempStatus = NorFlashUnlockSingleBlockIfNecessary (Instance, BlockAddress);
  873. if (EFI_ERROR (TempStatus)) {
  874. return EFI_DEVICE_ERROR;
  875. }
  876. PrevBlockAddress = BlockAddress;
  877. }
  878. TempStatus = NorFlashWriteSingleWord (Instance, WordAddr, WordToWrite);
  879. if (EFI_ERROR (TempStatus)) {
  880. return EFI_DEVICE_ERROR;
  881. }
  882. }
  883. // Exit if we got here and could write all the data. Otherwise do the
  884. // Erase-Write cycle.
  885. if (!DoErase) {
  886. return EFI_SUCCESS;
  887. }
  888. }
  889. // Check we did get some memory. Buffer is BlockSize.
  890. if (Instance->ShadowBuffer == NULL) {
  891. DEBUG ((EFI_D_ERROR, "FvbWrite: ERROR - Buffer not ready\n"));
  892. return EFI_DEVICE_ERROR;
  893. }
  894. // Read NOR Flash data into shadow buffer
  895. TempStatus = NorFlashReadBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer);
  896. if (EFI_ERROR (TempStatus)) {
  897. // Return one of the pre-approved error statuses
  898. return EFI_DEVICE_ERROR;
  899. }
  900. // Put the data at the appropriate location inside the buffer area
  901. CopyMem ((VOID*)((UINTN)Instance->ShadowBuffer + Offset), Buffer, *NumBytes);
  902. // Write the modified buffer back to the NorFlash
  903. TempStatus = NorFlashWriteBlocks (Instance, Lba, BlockSize, Instance->ShadowBuffer);
  904. if (EFI_ERROR (TempStatus)) {
  905. // Return one of the pre-approved error statuses
  906. return EFI_DEVICE_ERROR;
  907. }
  908. return EFI_SUCCESS;
  909. }
  910. /*
  911. Although DiskIoDxe will automatically install the DiskIO protocol whenever
  912. we install the BlockIO protocol, its implementation is sub-optimal as it reads
  913. and writes entire blocks using the BlockIO protocol. In fact we can access
  914. NOR flash with a finer granularity than that, so we can improve performance
  915. by directly producing the DiskIO protocol.
  916. */
  917. /**
  918. Read BufferSize bytes from Offset into Buffer.
  919. @param This Protocol instance pointer.
  920. @param MediaId Id of the media, changes every time the media is replaced.
  921. @param Offset The starting byte offset to read from
  922. @param BufferSize Size of Buffer
  923. @param Buffer Buffer containing read data
  924. @retval EFI_SUCCESS The data was read correctly from the device.
  925. @retval EFI_DEVICE_ERROR The device reported an error while performing the read.
  926. @retval EFI_NO_MEDIA There is no media in the device.
  927. @retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
  928. @retval EFI_INVALID_PARAMETER The read request contains device addresses that are not
  929. valid for the device.
  930. **/
  931. EFI_STATUS
  932. EFIAPI
  933. NorFlashDiskIoReadDisk (
  934. IN EFI_DISK_IO_PROTOCOL *This,
  935. IN UINT32 MediaId,
  936. IN UINT64 DiskOffset,
  937. IN UINTN BufferSize,
  938. OUT VOID *Buffer
  939. )
  940. {
  941. NOR_FLASH_INSTANCE *Instance;
  942. UINT32 BlockSize;
  943. UINT32 BlockOffset;
  944. EFI_LBA Lba;
  945. Instance = INSTANCE_FROM_DISKIO_THIS(This);
  946. if (MediaId != Instance->Media.MediaId) {
  947. return EFI_MEDIA_CHANGED;
  948. }
  949. BlockSize = Instance->Media.BlockSize;
  950. Lba = (EFI_LBA) DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset);
  951. return NorFlashRead (Instance, Lba, BlockOffset, BufferSize, Buffer);
  952. }
  953. /**
  954. Writes a specified number of bytes to a device.
  955. @param This Indicates a pointer to the calling context.
  956. @param MediaId ID of the medium to be written.
  957. @param Offset The starting byte offset on the logical block I/O device to write.
  958. @param BufferSize The size in bytes of Buffer. The number of bytes to write to the device.
  959. @param Buffer A pointer to the buffer containing the data to be written.
  960. @retval EFI_SUCCESS The data was written correctly to the device.
  961. @retval EFI_WRITE_PROTECTED The device can not be written to.
  962. @retval EFI_DEVICE_ERROR The device reported an error while performing the write.
  963. @retval EFI_NO_MEDIA There is no media in the device.
  964. @retval EFI_MEDIA_CHNAGED The MediaId does not matched the current device.
  965. @retval EFI_INVALID_PARAMETER The write request contains device addresses that are not
  966. valid for the device.
  967. **/
  968. EFI_STATUS
  969. EFIAPI
  970. NorFlashDiskIoWriteDisk (
  971. IN EFI_DISK_IO_PROTOCOL *This,
  972. IN UINT32 MediaId,
  973. IN UINT64 DiskOffset,
  974. IN UINTN BufferSize,
  975. IN VOID *Buffer
  976. )
  977. {
  978. NOR_FLASH_INSTANCE *Instance;
  979. UINT32 BlockSize;
  980. UINT32 BlockOffset;
  981. EFI_LBA Lba;
  982. UINTN RemainingBytes;
  983. UINTN WriteSize;
  984. EFI_STATUS Status;
  985. Instance = INSTANCE_FROM_DISKIO_THIS(This);
  986. if (MediaId != Instance->Media.MediaId) {
  987. return EFI_MEDIA_CHANGED;
  988. }
  989. BlockSize = Instance->Media.BlockSize;
  990. Lba = (EFI_LBA) DivU64x32Remainder (DiskOffset, BlockSize, &BlockOffset);
  991. RemainingBytes = BufferSize;
  992. // Write either all the remaining bytes, or the number of bytes that bring
  993. // us up to a block boundary, whichever is less.
  994. // (DiskOffset | (BlockSize - 1)) + 1) rounds DiskOffset up to the next
  995. // block boundary (even if it is already on one).
  996. WriteSize = MIN (RemainingBytes, ((DiskOffset | (BlockSize - 1)) + 1) - DiskOffset);
  997. do {
  998. if (WriteSize == BlockSize) {
  999. // Write a full block
  1000. Status = NorFlashWriteFullBlock (Instance, Lba, Buffer, BlockSize / sizeof (UINT32));
  1001. } else {
  1002. // Write a partial block
  1003. Status = NorFlashWriteSingleBlock (Instance, Lba, BlockOffset, &WriteSize, Buffer);
  1004. }
  1005. if (EFI_ERROR (Status)) {
  1006. return Status;
  1007. }
  1008. // Now continue writing either all the remaining bytes or single blocks.
  1009. RemainingBytes -= WriteSize;
  1010. Buffer = (UINT8 *) Buffer + WriteSize;
  1011. Lba++;
  1012. BlockOffset = 0;
  1013. WriteSize = MIN (RemainingBytes, BlockSize);
  1014. } while (RemainingBytes);
  1015. return Status;
  1016. }
  1017. EFI_STATUS
  1018. NorFlashReset (
  1019. IN NOR_FLASH_INSTANCE *Instance
  1020. )
  1021. {
  1022. // As there is no specific RESET to perform, ensure that the devices is in the default Read Array mode
  1023. SEND_NOR_COMMAND (Instance->DeviceBaseAddress, 0, P30_CMD_READ_ARRAY);
  1024. return EFI_SUCCESS;
  1025. }
  1026. /**
  1027. Fixup internal data so that EFI can be call in virtual mode.
  1028. Call the passed in Child Notify event and convert any pointers in
  1029. lib to virtual mode.
  1030. @param[in] Event The Event that is being processed
  1031. @param[in] Context Event Context
  1032. **/
  1033. VOID
  1034. EFIAPI
  1035. NorFlashVirtualNotifyEvent (
  1036. IN EFI_EVENT Event,
  1037. IN VOID *Context
  1038. )
  1039. {
  1040. UINTN Index;
  1041. for (Index = 0; Index < mNorFlashDeviceCount; Index++) {
  1042. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->DeviceBaseAddress);
  1043. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->RegionBaseAddress);
  1044. // Convert BlockIo protocol
  1045. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->BlockIoProtocol.FlushBlocks);
  1046. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->BlockIoProtocol.ReadBlocks);
  1047. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->BlockIoProtocol.Reset);
  1048. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->BlockIoProtocol.WriteBlocks);
  1049. // Convert Fvb
  1050. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.EraseBlocks);
  1051. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.GetAttributes);
  1052. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.GetBlockSize);
  1053. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.GetPhysicalAddress);
  1054. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.Read);
  1055. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.SetAttributes);
  1056. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->FvbProtocol.Write);
  1057. if (mNorFlashInstances[Index]->ShadowBuffer != NULL) {
  1058. EfiConvertPointer (0x0, (VOID**)&mNorFlashInstances[Index]->ShadowBuffer);
  1059. }
  1060. }
  1061. return;
  1062. }
  1063. EFI_STATUS
  1064. EFIAPI
  1065. NorFlashInitialise (
  1066. IN EFI_HANDLE ImageHandle,
  1067. IN EFI_SYSTEM_TABLE *SystemTable
  1068. )
  1069. {
  1070. EFI_STATUS Status;
  1071. UINT32 Index;
  1072. NOR_FLASH_DESCRIPTION* NorFlashDevices;
  1073. BOOLEAN ContainVariableStorage;
  1074. Status = NorFlashPlatformInitialization ();
  1075. if (EFI_ERROR(Status)) {
  1076. DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to initialize Nor Flash devices\n"));
  1077. return Status;
  1078. }
  1079. Status = NorFlashPlatformGetDevices (&NorFlashDevices, &mNorFlashDeviceCount);
  1080. if (EFI_ERROR(Status)) {
  1081. DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to get Nor Flash devices\n"));
  1082. return Status;
  1083. }
  1084. mNorFlashInstances = AllocateRuntimePool (sizeof(NOR_FLASH_INSTANCE*) * mNorFlashDeviceCount);
  1085. for (Index = 0; Index < mNorFlashDeviceCount; Index++) {
  1086. // Check if this NOR Flash device contain the variable storage region
  1087. ContainVariableStorage =
  1088. (NorFlashDevices[Index].RegionBaseAddress <= PcdGet32 (PcdFlashNvStorageVariableBase)) &&
  1089. (PcdGet32 (PcdFlashNvStorageVariableBase) + PcdGet32 (PcdFlashNvStorageVariableSize) <= NorFlashDevices[Index].RegionBaseAddress + NorFlashDevices[Index].Size);
  1090. Status = NorFlashCreateInstance (
  1091. NorFlashDevices[Index].DeviceBaseAddress,
  1092. NorFlashDevices[Index].RegionBaseAddress,
  1093. NorFlashDevices[Index].Size,
  1094. Index,
  1095. NorFlashDevices[Index].BlockSize,
  1096. ContainVariableStorage,
  1097. &mNorFlashInstances[Index]
  1098. );
  1099. if (EFI_ERROR(Status)) {
  1100. DEBUG((EFI_D_ERROR,"NorFlashInitialise: Fail to create instance for NorFlash[%d]\n",Index));
  1101. }
  1102. }
  1103. //
  1104. // Register for the virtual address change event
  1105. //
  1106. Status = gBS->CreateEventEx (
  1107. EVT_NOTIFY_SIGNAL,
  1108. TPL_NOTIFY,
  1109. NorFlashVirtualNotifyEvent,
  1110. NULL,
  1111. &gEfiEventVirtualAddressChangeGuid,
  1112. &mNorFlashVirtualAddrChangeEvent
  1113. );
  1114. ASSERT_EFI_ERROR (Status);
  1115. return Status;
  1116. }