kwboot.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483
  1. /*
  2. * Boot a Marvell SoC, with Xmodem over UART0.
  3. * supports Kirkwood, Dove, Avanta, Armada 370, Armada XP, Armada 375,
  4. * Armada 38x and Armada 39x.
  5. *
  6. * (c) 2012 Daniel Stodden <daniel.stodden@gmail.com>
  7. * (c) 2021 Pali Rohár <pali@kernel.org>
  8. * (c) 2021 Marek Behún <kabel@kernel.org>
  9. *
  10. * References:
  11. * - "88F6180, 88F6190, 88F6192, and 88F6281: Integrated Controller: Functional
  12. * Specifications" December 2, 2008. Chapter 24.2 "BootROM Firmware".
  13. * https://web.archive.org/web/20130730091033/https://www.marvell.com/embedded-processors/kirkwood/assets/FS_88F6180_9x_6281_OpenSource.pdf
  14. * - "88AP510: High-Performance SoC with Integrated CPU, 2D/3D Graphics
  15. * Processor, and High-Definition Video Decoder: Functional Specifications"
  16. * August 3, 2011. Chapter 5 "BootROM Firmware"
  17. * https://web.archive.org/web/20120130172443/https://www.marvell.com/application-processors/armada-500/assets/Armada-510-Functional-Spec.pdf
  18. * - "88F6665, 88F6660, 88F6658, 88F6655, 88F6655F, 88F6650, 88F6650F, 88F6610,
  19. * and 88F6610F Avanta LP Family Integrated Single/Dual CPU Ecosystem for
  20. * Gateway (GW), Home Gateway Unit (HGU), and Single Family Unit (SFU)
  21. * Functional Specifications" Doc. No. MV-S108952-00, Rev. A. November 7, 2013.
  22. * Chapter 7 "Boot Flow"
  23. * CONFIDENTIAL, no public documentation available
  24. * - "88F6710, 88F6707, and 88F6W11: ARMADA(R) 370 SoC: Functional Specifications"
  25. * May 26, 2014. Chapter 6 "BootROM Firmware".
  26. * https://web.archive.org/web/20140617183701/https://www.marvell.com/embedded-processors/armada-300/assets/ARMADA370-FunctionalSpec-datasheet.pdf
  27. * - "MV78230, MV78260, and MV78460: ARMADA(R) XP Family of Highly Integrated
  28. * Multi-Core ARMv7 Based SoC Processors: Functional Specifications"
  29. * May 29, 2014. Chapter 6 "BootROM Firmware".
  30. * https://web.archive.org/web/20180829171131/https://www.marvell.com/embedded-processors/armada-xp/assets/ARMADA-XP-Functional-SpecDatasheet.pdf
  31. * - "BobCat2 Control and Management Subsystem Functional Specifications"
  32. * Doc. No. MV-S109400-00, Rev. A. December 4, 2014.
  33. * Chapter 1.6 BootROM Firmware
  34. * CONFIDENTIAL, no public documentation available
  35. * - "AlleyCat3 and PONCat3 Highly Integrated 1/10 Gigabit Ethernet Switch
  36. * Control and Management Subsystem: Functional Specifications"
  37. * Doc. No. MV-S109693-00, Rev. A. May 20, 2014.
  38. * Chapter 1.6 BootROM Firmware
  39. * CONFIDENTIAL, no public documentation available
  40. * - "ARMADA(R) 375 Value-Performance Dual Core CPU System on Chip: Functional
  41. * Specifications" Doc. No. MV-S109377-00, Rev. A. September 18, 2013.
  42. * Chapter 7 "Boot Sequence"
  43. * CONFIDENTIAL, no public documentation available
  44. * - "88F6810, 88F6811, 88F6821, 88F6W21, 88F6820, and 88F6828: ARMADA(R) 38x
  45. * Family High-Performance Single/Dual CPU System on Chip: Functional
  46. * Specifications" Doc. No. MV-S109094-00, Rev. C. August 2, 2015.
  47. * Chapter 7 "Boot Flow"
  48. * CONFIDENTIAL, no public documentation available
  49. * - "88F6920, 88F6925 and 88F6928: ARMADA(R) 39x High-Performance Dual Core CPU
  50. * System on Chip Functional Specifications" Doc. No. MV-S109896-00, Rev. B.
  51. * December 22, 2015. Chapter 7 "Boot Flow"
  52. * CONFIDENTIAL, no public documentation available
  53. * - "Marvell boot image parser", Marvell U-Boot 2013.01, version 18.06. September 17, 2015.
  54. * https://github.com/MarvellEmbeddedProcessors/u-boot-marvell/blob/u-boot-2013.01-armada-18.06/tools/marvell/doimage_mv/hdrparser.c
  55. * - "Marvell doimage Tool", Marvell U-Boot 2013.01, version 18.06. August 30, 2015.
  56. * https://github.com/MarvellEmbeddedProcessors/u-boot-marvell/blob/u-boot-2013.01-armada-18.06/tools/marvell/doimage_mv/doimage.c
  57. *
  58. * Storage location / offset of different image types:
  59. * - IBR_HDR_SPI_ID (0x5A):
  60. * SPI image can be stored at any 2 MB aligned offset in the first 16 MB of
  61. * SPI-NOR or parallel-NOR. Despite the type name it really can be stored on
  62. * parallel-NOR and cannot be stored on other SPI devices, like SPI-NAND.
  63. * So it should have been named NOR image, not SPI image. This image type
  64. * supports XIP - Execute In Place directly from NOR memory. Destination
  65. * address of the XIP image is set to 0xFFFFFFFF and execute address to the
  66. * absolute offset in bytes from the beginning of NOR memory.
  67. *
  68. * - IBR_HDR_NAND_ID (0x8B):
  69. * NAND image can be stored either at any 2 MB aligned offset in the first
  70. * 16 MB of SPI-NAND or at any blocksize aligned offset in the first 64 MB
  71. * of parallel-NAND.
  72. *
  73. * - IBR_HDR_PEX_ID (0x9C):
  74. * PEX image is used for booting from PCI Express device. Source address
  75. * stored in image is ignored by BootROM. It is not the BootROM who parses
  76. * or loads data part of the PEX image. BootROM just configures SoC to the
  77. * PCIe endpoint mode and let the PCIe device on the other end of the PCIe
  78. * link (which must be in Root Complex mode) to load kwbimage into SoC's
  79. * memory and tell BootROM physical address.
  80. *
  81. * - IBR_HDR_UART_ID (0x69):
  82. * UART image can be transfered via xmodem protocol over first UART.
  83. * Unlike all other image types, header size stored in the image must be
  84. * multiply of the 128 bytes (for all other image types it can be any size)
  85. * and data part of the image does not have to contain 32-bit checksum
  86. * (all other image types must have valid 32-bit checksum in its data part).
  87. * And data size stored in the image is ignored. A38x BootROM determinates
  88. * size of the data part implicitly by the end of the xmodem transfer.
  89. * A38x BootROM has a bug which cause that BootROM loads data part of UART
  90. * image into RAM target address increased by one byte when source address
  91. * and header size stored in the image header are not same. So UART image
  92. * should be constructed in a way that there is no gap between header and
  93. * data part.
  94. *
  95. * - IBR_HDR_I2C_ID (0x4D):
  96. * It is unknown for what kind of storage is used this image. It is not
  97. * specified in any document from References section.
  98. *
  99. * - IBR_HDR_SATA_ID (0x78):
  100. * SATA image can be stored at sector 1 (after the MBR table), sector 34
  101. * (after the GPT table) or at any next sector which is aligned to 2 MB and
  102. * is in the first 16 MB of SATA disk. Note that source address in SATA image
  103. * is stored in sector unit and not in bytes like for any other images.
  104. * Unfortunately sector size is disk specific, in most cases it is 512 bytes
  105. * but there are also Native 4K SATA disks which have 4096 bytes long sectors.
  106. *
  107. * - IBR_HDR_SDIO_ID (0xAE):
  108. * SDIO image can be stored on different medias:
  109. * - SD(SC) card
  110. * - SDHC/SDXC card
  111. * - eMMC HW boot partition
  112. * - eMMC user data partition / MMC card
  113. * It cannot be stored on SDIO card despite the image name.
  114. *
  115. * For SD(SC)/SDHC/SDXC cards, image can be stored at the same locations as
  116. * the SATA image (sector 1, sector 34 or any 2 MB aligned sector) but within
  117. * the first 64 MB. SDHC and SDXC cards have fixed 512 bytes long sector size.
  118. * Old SD(SC) cards unfortunately can have also different sector sizes, mostly
  119. * 1024 bytes long sector sizes and also can be changed at runtime.
  120. *
  121. * For MMC-compatible devices, image can be stored at offset 0 or at offset
  122. * 2 MB. If MMC device supports HW boot partitions then image must be stored
  123. * on the HW partition as is configured in the EXT_CSC register (it can be
  124. * either boot or user data).
  125. *
  126. * Note that source address for SDIO image is stored in byte unit, like for
  127. * any other images (except SATA). Marvell Functional Specifications for
  128. * A38x and A39x SoCs say that source address is in sector units, but this
  129. * is purely incorrect information. A385 BootROM really expects source address
  130. * for SDIO images in bytes and also Marvell tools generate SDIO image with
  131. * source address in byte units.
  132. */
  133. #include "kwbimage.h"
  134. #include "mkimage.h"
  135. #include "version.h"
  136. #include <stdlib.h>
  137. #include <stdio.h>
  138. #include <string.h>
  139. #include <stdarg.h>
  140. #include <image.h>
  141. #include <libgen.h>
  142. #include <fcntl.h>
  143. #include <errno.h>
  144. #include <unistd.h>
  145. #include <stdint.h>
  146. #include <time.h>
  147. #include <sys/stat.h>
  148. #include <pthread.h>
  149. #ifdef __linux__
  150. #include "termios_linux.h"
  151. #else
  152. #include <termios.h>
  153. #endif
  154. /*
  155. * These functions are in <term.h> header file, but this header file conflicts
  156. * with "termios_linux.h" header file. So declare these functions manually.
  157. */
  158. extern int setupterm(const char *, int, int *);
  159. extern char *tigetstr(const char *);
  160. /*
  161. * Marvell BootROM UART Sensing
  162. */
  163. static unsigned char kwboot_msg_boot[] = {
  164. 0xBB, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77
  165. };
  166. static unsigned char kwboot_msg_debug[] = {
  167. 0xDD, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77
  168. };
  169. /* Defines known to work on Kirkwood */
  170. #define KWBOOT_MSG_RSP_TIMEO 50 /* ms */
  171. /* Defines known to work on Armada XP */
  172. #define KWBOOT_MSG_RSP_TIMEO_AXP 10 /* ms */
  173. /*
  174. * Xmodem Transfers
  175. */
  176. #define SOH 1 /* sender start of block header */
  177. #define EOT 4 /* sender end of block transfer */
  178. #define ACK 6 /* target block ack */
  179. #define NAK 21 /* target block negative ack */
  180. #define KWBOOT_XM_BLKSZ 128 /* xmodem block size */
  181. struct kwboot_block {
  182. uint8_t soh;
  183. uint8_t pnum;
  184. uint8_t _pnum;
  185. uint8_t data[KWBOOT_XM_BLKSZ];
  186. uint8_t csum;
  187. } __packed;
  188. #define KWBOOT_BLK_RSP_TIMEO 2000 /* ms */
  189. #define KWBOOT_HDR_RSP_TIMEO 10000 /* ms */
  190. /* ARM code to change baudrate */
  191. static unsigned char kwboot_baud_code[] = {
  192. /* ; #define UART_BASE 0xd0012000 */
  193. /* ; #define DLL 0x00 */
  194. /* ; #define DLH 0x04 */
  195. /* ; #define LCR 0x0c */
  196. /* ; #define DLAB 0x80 */
  197. /* ; #define LSR 0x14 */
  198. /* ; #define TEMT 0x40 */
  199. /* ; #define DIV_ROUND(a, b) ((a + b/2) / b) */
  200. /* ; */
  201. /* ; u32 set_baudrate(u32 old_b, u32 new_b) { */
  202. /* ; while */
  203. /* ; (!(readl(UART_BASE + LSR) & TEMT)); */
  204. /* ; u32 lcr = readl(UART_BASE + LCR); */
  205. /* ; writel(UART_BASE + LCR, lcr | DLAB); */
  206. /* ; u8 old_dll = readl(UART_BASE + DLL); */
  207. /* ; u8 old_dlh = readl(UART_BASE + DLH); */
  208. /* ; u16 old_dl = old_dll | (old_dlh << 8); */
  209. /* ; u32 clk = old_b * old_dl; */
  210. /* ; u16 new_dl = DIV_ROUND(clk, new_b); */
  211. /* ; u8 new_dll = new_dl & 0xff; */
  212. /* ; u8 new_dlh = (new_dl >> 8) & 0xff; */
  213. /* ; writel(UART_BASE + DLL, new_dll); */
  214. /* ; writel(UART_BASE + DLH, new_dlh); */
  215. /* ; writel(UART_BASE + LCR, lcr & ~DLAB); */
  216. /* ; msleep(5); */
  217. /* ; return 0; */
  218. /* ; } */
  219. /* ; r0 = UART_BASE */
  220. 0x0d, 0x02, 0xa0, 0xe3, /* mov r0, #0xd0000000 */
  221. 0x12, 0x0a, 0x80, 0xe3, /* orr r0, r0, #0x12000 */
  222. /* ; Wait until Transmitter FIFO is Empty */
  223. /* .Lloop_txempty: */
  224. /* ; r1 = UART_BASE[LSR] & TEMT */
  225. 0x14, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x14] */
  226. 0x40, 0x00, 0x11, 0xe3, /* tst r1, #0x40 */
  227. 0xfc, 0xff, 0xff, 0x0a, /* beq .Lloop_txempty */
  228. /* ; Set Divisor Latch Access Bit */
  229. /* ; UART_BASE[LCR] |= DLAB */
  230. 0x0c, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x0c] */
  231. 0x80, 0x10, 0x81, 0xe3, /* orr r1, r1, #0x80 */
  232. 0x0c, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0c] */
  233. /* ; Read current Divisor Latch */
  234. /* ; r1 = UART_BASE[DLH]<<8 | UART_BASE[DLL] */
  235. 0x00, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x00] */
  236. 0xff, 0x10, 0x01, 0xe2, /* and r1, r1, #0xff */
  237. 0x01, 0x20, 0xa0, 0xe1, /* mov r2, r1 */
  238. 0x04, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x04] */
  239. 0xff, 0x10, 0x01, 0xe2, /* and r1, r1, #0xff */
  240. 0x41, 0x14, 0xa0, 0xe1, /* asr r1, r1, #8 */
  241. 0x02, 0x10, 0x81, 0xe1, /* orr r1, r1, r2 */
  242. /* ; Read old baudrate value */
  243. /* ; r2 = old_baudrate */
  244. 0x74, 0x20, 0x9f, 0xe5, /* ldr r2, old_baudrate */
  245. /* ; Calculate base clock */
  246. /* ; r1 = r2 * r1 */
  247. 0x92, 0x01, 0x01, 0xe0, /* mul r1, r2, r1 */
  248. /* ; Read new baudrate value */
  249. /* ; r2 = new_baudrate */
  250. 0x70, 0x20, 0x9f, 0xe5, /* ldr r2, new_baudrate */
  251. /* ; Calculate new Divisor Latch */
  252. /* ; r1 = DIV_ROUND(r1, r2) = */
  253. /* ; = (r1 + r2/2) / r2 */
  254. 0xa2, 0x10, 0x81, 0xe0, /* add r1, r1, r2, lsr #1 */
  255. 0x02, 0x40, 0xa0, 0xe1, /* mov r4, r2 */
  256. 0xa1, 0x00, 0x54, 0xe1, /* cmp r4, r1, lsr #1 */
  257. /* .Lloop_div1: */
  258. 0x84, 0x40, 0xa0, 0x91, /* movls r4, r4, lsl #1 */
  259. 0xa1, 0x00, 0x54, 0xe1, /* cmp r4, r1, lsr #1 */
  260. 0xfc, 0xff, 0xff, 0x9a, /* bls .Lloop_div1 */
  261. 0x00, 0x30, 0xa0, 0xe3, /* mov r3, #0 */
  262. /* .Lloop_div2: */
  263. 0x04, 0x00, 0x51, 0xe1, /* cmp r1, r4 */
  264. 0x04, 0x10, 0x41, 0x20, /* subhs r1, r1, r4 */
  265. 0x03, 0x30, 0xa3, 0xe0, /* adc r3, r3, r3 */
  266. 0xa4, 0x40, 0xa0, 0xe1, /* mov r4, r4, lsr #1 */
  267. 0x02, 0x00, 0x54, 0xe1, /* cmp r4, r2 */
  268. 0xf9, 0xff, 0xff, 0x2a, /* bhs .Lloop_div2 */
  269. 0x03, 0x10, 0xa0, 0xe1, /* mov r1, r3 */
  270. /* ; Set new Divisor Latch Low */
  271. /* ; UART_BASE[DLL] = r1 & 0xff */
  272. 0x01, 0x20, 0xa0, 0xe1, /* mov r2, r1 */
  273. 0xff, 0x20, 0x02, 0xe2, /* and r2, r2, #0xff */
  274. 0x00, 0x20, 0x80, 0xe5, /* str r2, [r0, #0x00] */
  275. /* ; Set new Divisor Latch High */
  276. /* ; UART_BASE[DLH] = r1>>8 & 0xff */
  277. 0x41, 0x24, 0xa0, 0xe1, /* asr r2, r1, #8 */
  278. 0xff, 0x20, 0x02, 0xe2, /* and r2, r2, #0xff */
  279. 0x04, 0x20, 0x80, 0xe5, /* str r2, [r0, #0x04] */
  280. /* ; Clear Divisor Latch Access Bit */
  281. /* ; UART_BASE[LCR] &= ~DLAB */
  282. 0x0c, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x0c] */
  283. 0x80, 0x10, 0xc1, 0xe3, /* bic r1, r1, #0x80 */
  284. 0x0c, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0c] */
  285. /* ; Loop 0x2dc000 (2998272) cycles */
  286. /* ; which is about 5ms on 1200 MHz CPU */
  287. /* ; r1 = 0x2dc000 */
  288. 0xb7, 0x19, 0xa0, 0xe3, /* mov r1, #0x2dc000 */
  289. /* .Lloop_sleep: */
  290. 0x01, 0x10, 0x41, 0xe2, /* sub r1, r1, #1 */
  291. 0x00, 0x00, 0x51, 0xe3, /* cmp r1, #0 */
  292. 0xfc, 0xff, 0xff, 0x1a, /* bne .Lloop_sleep */
  293. /* ; Jump to the end of execution */
  294. 0x01, 0x00, 0x00, 0xea, /* b end */
  295. /* ; Placeholder for old baudrate value */
  296. /* old_baudrate: */
  297. 0x00, 0x00, 0x00, 0x00, /* .word 0 */
  298. /* ; Placeholder for new baudrate value */
  299. /* new_baudrate: */
  300. 0x00, 0x00, 0x00, 0x00, /* .word 0 */
  301. /* end: */
  302. };
  303. /* ARM code from binary header executed by BootROM before changing baudrate */
  304. static unsigned char kwboot_baud_code_binhdr_pre[] = {
  305. /* ; #define UART_BASE 0xd0012000 */
  306. /* ; #define THR 0x00 */
  307. /* ; #define LSR 0x14 */
  308. /* ; #define THRE 0x20 */
  309. /* ; */
  310. /* ; void send_preamble(void) { */
  311. /* ; const u8 *str = "$baudratechange"; */
  312. /* ; u8 c; */
  313. /* ; do { */
  314. /* ; while */
  315. /* ; ((readl(UART_BASE + LSR) & THRE)); */
  316. /* ; c = *str++; */
  317. /* ; writel(UART_BASE + THR, c); */
  318. /* ; } while (c); */
  319. /* ; } */
  320. /* ; Preserve registers for BootROM */
  321. 0xfe, 0x5f, 0x2d, 0xe9, /* push { r1 - r12, lr } */
  322. /* ; r0 = UART_BASE */
  323. 0x0d, 0x02, 0xa0, 0xe3, /* mov r0, #0xd0000000 */
  324. 0x12, 0x0a, 0x80, 0xe3, /* orr r0, r0, #0x12000 */
  325. /* ; r2 = address of preamble string */
  326. 0x00, 0x20, 0x8f, 0xe2, /* adr r2, .Lstr_preamble */
  327. /* ; Skip preamble data section */
  328. 0x03, 0x00, 0x00, 0xea, /* b .Lloop_preamble */
  329. /* ; Preamble string */
  330. /* .Lstr_preamble: */
  331. 0x24, 0x62, 0x61, 0x75, /* .asciz "$baudratechange" */
  332. 0x64, 0x72, 0x61, 0x74,
  333. 0x65, 0x63, 0x68, 0x61,
  334. 0x6e, 0x67, 0x65, 0x00,
  335. /* ; Send preamble string over UART */
  336. /* .Lloop_preamble: */
  337. /* */
  338. /* ; Wait until Transmitter Holding is Empty */
  339. /* .Lloop_thre: */
  340. /* ; r1 = UART_BASE[LSR] & THRE */
  341. 0x14, 0x10, 0x90, 0xe5, /* ldr r1, [r0, #0x14] */
  342. 0x20, 0x00, 0x11, 0xe3, /* tst r1, #0x20 */
  343. 0xfc, 0xff, 0xff, 0x0a, /* beq .Lloop_thre */
  344. /* ; Put character into Transmitter FIFO */
  345. /* ; r1 = *r2++ */
  346. 0x01, 0x10, 0xd2, 0xe4, /* ldrb r1, [r2], #1 */
  347. /* ; UART_BASE[THR] = r1 */
  348. 0x00, 0x10, 0x80, 0xe5, /* str r1, [r0, #0x0] */
  349. /* ; Loop until end of preamble string */
  350. 0x00, 0x00, 0x51, 0xe3, /* cmp r1, #0 */
  351. 0xf8, 0xff, 0xff, 0x1a, /* bne .Lloop_preamble */
  352. };
  353. /* ARM code for returning from binary header back to BootROM */
  354. static unsigned char kwboot_baud_code_binhdr_post[] = {
  355. /* ; Return 0 - no error */
  356. 0x00, 0x00, 0xa0, 0xe3, /* mov r0, #0 */
  357. 0xfe, 0x9f, 0xbd, 0xe8, /* pop { r1 - r12, pc } */
  358. };
  359. /* ARM code for jumping to the original image exec_addr */
  360. static unsigned char kwboot_baud_code_data_jump[] = {
  361. 0x04, 0xf0, 0x1f, 0xe5, /* ldr pc, exec_addr */
  362. /* ; Placeholder for exec_addr */
  363. /* exec_addr: */
  364. 0x00, 0x00, 0x00, 0x00, /* .word 0 */
  365. };
  366. static const char kwb_baud_magic[16] = "$baudratechange";
  367. static int kwboot_verbose;
  368. static int msg_rsp_timeo = KWBOOT_MSG_RSP_TIMEO;
  369. static int blk_rsp_timeo = KWBOOT_BLK_RSP_TIMEO;
  370. static ssize_t
  371. kwboot_write(int fd, const char *buf, size_t len)
  372. {
  373. ssize_t tot = 0;
  374. while (tot < len) {
  375. ssize_t wr = write(fd, buf + tot, len - tot);
  376. if (wr < 0 && errno == EINTR)
  377. continue;
  378. else if (wr < 0)
  379. return wr;
  380. tot += wr;
  381. }
  382. return tot;
  383. }
  384. static void
  385. kwboot_printv(const char *fmt, ...)
  386. {
  387. va_list ap;
  388. if (kwboot_verbose) {
  389. va_start(ap, fmt);
  390. vprintf(fmt, ap);
  391. va_end(ap);
  392. fflush(stdout);
  393. }
  394. }
  395. static void
  396. __spinner(void)
  397. {
  398. const char seq[] = { '-', '\\', '|', '/' };
  399. const int div = 8;
  400. static int state, bs;
  401. if (state % div == 0) {
  402. fputc(bs, stdout);
  403. fputc(seq[state / div % sizeof(seq)], stdout);
  404. fflush(stdout);
  405. }
  406. bs = '\b';
  407. state++;
  408. }
  409. static void
  410. kwboot_spinner(void)
  411. {
  412. if (kwboot_verbose)
  413. __spinner();
  414. }
  415. static void
  416. __progress(int pct, char c)
  417. {
  418. const int width = 70;
  419. static const char *nl = "";
  420. static int pos;
  421. if (pos % width == 0)
  422. printf("%s%3d %% [", nl, pct);
  423. fputc(c, stdout);
  424. nl = "]\n";
  425. pos = (pos + 1) % width;
  426. if (pct == 100) {
  427. while (pos && pos++ < width)
  428. fputc(' ', stdout);
  429. fputs(nl, stdout);
  430. nl = "";
  431. pos = 0;
  432. }
  433. fflush(stdout);
  434. }
  435. static void
  436. kwboot_progress(int _pct, char c)
  437. {
  438. static int pct;
  439. if (_pct != -1)
  440. pct = _pct;
  441. if (kwboot_verbose)
  442. __progress(pct, c);
  443. if (pct == 100)
  444. pct = 0;
  445. }
  446. static int
  447. kwboot_tty_recv(int fd, void *buf, size_t len, int timeo)
  448. {
  449. int rc, nfds;
  450. fd_set rfds;
  451. struct timeval tv;
  452. ssize_t n;
  453. rc = -1;
  454. FD_ZERO(&rfds);
  455. FD_SET(fd, &rfds);
  456. tv.tv_sec = 0;
  457. tv.tv_usec = timeo * 1000;
  458. if (tv.tv_usec > 1000000) {
  459. tv.tv_sec += tv.tv_usec / 1000000;
  460. tv.tv_usec %= 1000000;
  461. }
  462. do {
  463. nfds = select(fd + 1, &rfds, NULL, NULL, &tv);
  464. if (nfds < 0 && errno == EINTR)
  465. continue;
  466. else if (nfds < 0)
  467. goto out;
  468. else if (!nfds) {
  469. errno = ETIMEDOUT;
  470. goto out;
  471. }
  472. n = read(fd, buf, len);
  473. if (n < 0 && errno == EINTR)
  474. continue;
  475. else if (n <= 0)
  476. goto out;
  477. buf = (char *)buf + n;
  478. len -= n;
  479. } while (len > 0);
  480. rc = 0;
  481. out:
  482. return rc;
  483. }
  484. static int
  485. kwboot_tty_send(int fd, const void *buf, size_t len, int nodrain)
  486. {
  487. if (!buf)
  488. return 0;
  489. if (kwboot_write(fd, buf, len) < 0)
  490. return -1;
  491. if (nodrain)
  492. return 0;
  493. return tcdrain(fd);
  494. }
  495. static int
  496. kwboot_tty_send_char(int fd, unsigned char c)
  497. {
  498. return kwboot_tty_send(fd, &c, 1, 0);
  499. }
  500. static speed_t
  501. kwboot_tty_baudrate_to_speed(int baudrate)
  502. {
  503. switch (baudrate) {
  504. #ifdef B4000000
  505. case 4000000:
  506. return B4000000;
  507. #endif
  508. #ifdef B3500000
  509. case 3500000:
  510. return B3500000;
  511. #endif
  512. #ifdef B3000000
  513. case 3000000:
  514. return B3000000;
  515. #endif
  516. #ifdef B2500000
  517. case 2500000:
  518. return B2500000;
  519. #endif
  520. #ifdef B2000000
  521. case 2000000:
  522. return B2000000;
  523. #endif
  524. #ifdef B1500000
  525. case 1500000:
  526. return B1500000;
  527. #endif
  528. #ifdef B1152000
  529. case 1152000:
  530. return B1152000;
  531. #endif
  532. #ifdef B1000000
  533. case 1000000:
  534. return B1000000;
  535. #endif
  536. #ifdef B921600
  537. case 921600:
  538. return B921600;
  539. #endif
  540. #ifdef B614400
  541. case 614400:
  542. return B614400;
  543. #endif
  544. #ifdef B576000
  545. case 576000:
  546. return B576000;
  547. #endif
  548. #ifdef B500000
  549. case 500000:
  550. return B500000;
  551. #endif
  552. #ifdef B460800
  553. case 460800:
  554. return B460800;
  555. #endif
  556. #ifdef B307200
  557. case 307200:
  558. return B307200;
  559. #endif
  560. #ifdef B230400
  561. case 230400:
  562. return B230400;
  563. #endif
  564. #ifdef B153600
  565. case 153600:
  566. return B153600;
  567. #endif
  568. #ifdef B115200
  569. case 115200:
  570. return B115200;
  571. #endif
  572. #ifdef B76800
  573. case 76800:
  574. return B76800;
  575. #endif
  576. #ifdef B57600
  577. case 57600:
  578. return B57600;
  579. #endif
  580. #ifdef B38400
  581. case 38400:
  582. return B38400;
  583. #endif
  584. #ifdef B19200
  585. case 19200:
  586. return B19200;
  587. #endif
  588. #ifdef B9600
  589. case 9600:
  590. return B9600;
  591. #endif
  592. #ifdef B4800
  593. case 4800:
  594. return B4800;
  595. #endif
  596. #ifdef B2400
  597. case 2400:
  598. return B2400;
  599. #endif
  600. #ifdef B1800
  601. case 1800:
  602. return B1800;
  603. #endif
  604. #ifdef B1200
  605. case 1200:
  606. return B1200;
  607. #endif
  608. #ifdef B600
  609. case 600:
  610. return B600;
  611. #endif
  612. #ifdef B300
  613. case 300:
  614. return B300;
  615. #endif
  616. #ifdef B200
  617. case 200:
  618. return B200;
  619. #endif
  620. #ifdef B150
  621. case 150:
  622. return B150;
  623. #endif
  624. #ifdef B134
  625. case 134:
  626. return B134;
  627. #endif
  628. #ifdef B110
  629. case 110:
  630. return B110;
  631. #endif
  632. #ifdef B75
  633. case 75:
  634. return B75;
  635. #endif
  636. #ifdef B50
  637. case 50:
  638. return B50;
  639. #endif
  640. default:
  641. #ifdef BOTHER
  642. return BOTHER;
  643. #else
  644. return B0;
  645. #endif
  646. }
  647. }
  648. static int
  649. _is_within_tolerance(int value, int reference, int tolerance)
  650. {
  651. return 100 * value >= reference * (100 - tolerance) &&
  652. 100 * value <= reference * (100 + tolerance);
  653. }
  654. static int
  655. kwboot_tty_change_baudrate(int fd, int baudrate)
  656. {
  657. struct termios tio;
  658. speed_t speed;
  659. int rc;
  660. rc = tcgetattr(fd, &tio);
  661. if (rc)
  662. return rc;
  663. speed = kwboot_tty_baudrate_to_speed(baudrate);
  664. if (speed == B0) {
  665. errno = EINVAL;
  666. return -1;
  667. }
  668. #ifdef BOTHER
  669. if (speed == BOTHER)
  670. tio.c_ospeed = tio.c_ispeed = baudrate;
  671. #endif
  672. rc = cfsetospeed(&tio, speed);
  673. if (rc)
  674. return rc;
  675. rc = cfsetispeed(&tio, speed);
  676. if (rc)
  677. return rc;
  678. rc = tcsetattr(fd, TCSANOW, &tio);
  679. if (rc)
  680. return rc;
  681. rc = tcgetattr(fd, &tio);
  682. if (rc)
  683. return rc;
  684. if (cfgetospeed(&tio) != speed || cfgetispeed(&tio) != speed)
  685. goto baud_fail;
  686. #ifdef BOTHER
  687. /*
  688. * Check whether set baudrate is within 3% tolerance.
  689. * If BOTHER is defined, Linux always fills out c_ospeed / c_ispeed
  690. * with real values.
  691. */
  692. if (!_is_within_tolerance(tio.c_ospeed, baudrate, 3))
  693. goto baud_fail;
  694. if (!_is_within_tolerance(tio.c_ispeed, baudrate, 3))
  695. goto baud_fail;
  696. #endif
  697. return 0;
  698. baud_fail:
  699. fprintf(stderr, "Could not set baudrate to requested value\n");
  700. errno = EINVAL;
  701. return -1;
  702. }
  703. static int
  704. kwboot_open_tty(const char *path, int baudrate)
  705. {
  706. int rc, fd, flags;
  707. struct termios tio;
  708. rc = -1;
  709. fd = open(path, O_RDWR | O_NOCTTY | O_NDELAY);
  710. if (fd < 0)
  711. goto out;
  712. rc = tcgetattr(fd, &tio);
  713. if (rc)
  714. goto out;
  715. cfmakeraw(&tio);
  716. tio.c_cflag |= CREAD | CLOCAL;
  717. tio.c_cflag &= ~(CSTOPB | HUPCL | CRTSCTS);
  718. tio.c_cc[VMIN] = 1;
  719. tio.c_cc[VTIME] = 0;
  720. rc = tcsetattr(fd, TCSANOW, &tio);
  721. if (rc)
  722. goto out;
  723. flags = fcntl(fd, F_GETFL);
  724. if (flags < 0)
  725. goto out;
  726. rc = fcntl(fd, F_SETFL, flags & ~O_NDELAY);
  727. if (rc)
  728. goto out;
  729. rc = kwboot_tty_change_baudrate(fd, baudrate);
  730. if (rc)
  731. goto out;
  732. rc = fd;
  733. out:
  734. if (rc < 0) {
  735. if (fd >= 0)
  736. close(fd);
  737. }
  738. return rc;
  739. }
  740. static void *
  741. kwboot_msg_write_handler(void *arg)
  742. {
  743. int tty = *(int *)((void **)arg)[0];
  744. const void *msg = ((void **)arg)[1];
  745. int rsp_timeo = msg_rsp_timeo;
  746. int i, dummy_oldtype;
  747. /* allow to cancel this thread at any time */
  748. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &dummy_oldtype);
  749. while (1) {
  750. /* write 128 samples of message pattern into the output queue without waiting */
  751. for (i = 0; i < 128; i++) {
  752. if (kwboot_tty_send(tty, msg, 8, 1) < 0) {
  753. perror("\nFailed to send message pattern");
  754. exit(1);
  755. }
  756. }
  757. /* wait until output queue is transmitted and then make pause */
  758. if (tcdrain(tty) < 0) {
  759. perror("\nFailed to send message pattern");
  760. exit(1);
  761. }
  762. /* BootROM requires pause on UART after it detects message pattern */
  763. usleep(rsp_timeo * 1000);
  764. }
  765. }
  766. static int
  767. kwboot_msg_start_thread(pthread_t *thread, int *tty, void *msg)
  768. {
  769. void *arg[2];
  770. int rc;
  771. arg[0] = tty;
  772. arg[1] = msg;
  773. rc = pthread_create(thread, NULL, kwboot_msg_write_handler, arg);
  774. if (rc) {
  775. errno = rc;
  776. return -1;
  777. }
  778. return 0;
  779. }
  780. static int
  781. kwboot_msg_stop_thread(pthread_t thread)
  782. {
  783. int rc;
  784. rc = pthread_cancel(thread);
  785. if (rc) {
  786. errno = rc;
  787. return -1;
  788. }
  789. rc = pthread_join(thread, NULL);
  790. if (rc) {
  791. errno = rc;
  792. return -1;
  793. }
  794. return 0;
  795. }
  796. static int
  797. kwboot_bootmsg(int tty)
  798. {
  799. struct kwboot_block block;
  800. pthread_t write_thread;
  801. int rc, err;
  802. char c;
  803. /* flush input and output queue */
  804. tcflush(tty, TCIOFLUSH);
  805. rc = kwboot_msg_start_thread(&write_thread, &tty, kwboot_msg_boot);
  806. if (rc) {
  807. perror("Failed to start write thread");
  808. return rc;
  809. }
  810. kwboot_printv("Sending boot message. Please reboot the target...");
  811. err = 0;
  812. while (1) {
  813. kwboot_spinner();
  814. rc = kwboot_tty_recv(tty, &c, 1, msg_rsp_timeo);
  815. if (rc && errno == ETIMEDOUT) {
  816. continue;
  817. } else if (rc) {
  818. err = errno;
  819. break;
  820. }
  821. if (c == NAK)
  822. break;
  823. }
  824. kwboot_printv("\n");
  825. rc = kwboot_msg_stop_thread(write_thread);
  826. if (rc) {
  827. perror("Failed to stop write thread");
  828. return rc;
  829. }
  830. if (err) {
  831. errno = err;
  832. perror("Failed to read response for boot message pattern");
  833. return -1;
  834. }
  835. /*
  836. * At this stage we have sent more boot message patterns and BootROM
  837. * (at least on Armada XP and 385) started interpreting sent bytes as
  838. * part of xmodem packets. If BootROM is expecting SOH byte as start of
  839. * a xmodem packet and it receives byte 0xff, then it throws it away and
  840. * sends a NAK reply to host. If BootROM does not receive any byte for
  841. * 2s when expecting some continuation of the xmodem packet, it throws
  842. * away the partially received xmodem data and sends NAK reply to host.
  843. *
  844. * Therefore for starting xmodem transfer we have two options: Either
  845. * wait 2s or send 132 0xff bytes (which is the size of xmodem packet)
  846. * to ensure that BootROM throws away any partially received data.
  847. */
  848. /* flush output queue with remaining boot message patterns */
  849. rc = tcflush(tty, TCOFLUSH);
  850. if (rc) {
  851. perror("Failed to flush output queue");
  852. return rc;
  853. }
  854. /* send one xmodem packet with 0xff bytes to force BootROM to re-sync */
  855. memset(&block, 0xff, sizeof(block));
  856. rc = kwboot_tty_send(tty, &block, sizeof(block), 0);
  857. if (rc) {
  858. perror("Failed to send sync sequence");
  859. return rc;
  860. }
  861. /*
  862. * Sending 132 bytes via 115200B/8-N-1 takes 11.45 ms, reading 132 bytes
  863. * takes 11.45 ms, so waiting for 30 ms should be enough.
  864. */
  865. usleep(30 * 1000);
  866. /* flush remaining NAK replies from input queue */
  867. rc = tcflush(tty, TCIFLUSH);
  868. if (rc) {
  869. perror("Failed to flush input queue");
  870. return rc;
  871. }
  872. return 0;
  873. }
  874. static int
  875. kwboot_debugmsg(int tty)
  876. {
  877. unsigned char buf[8192];
  878. pthread_t write_thread;
  879. int rc, err, i, pos;
  880. size_t off;
  881. /* flush input and output queue */
  882. tcflush(tty, TCIOFLUSH);
  883. rc = kwboot_msg_start_thread(&write_thread, &tty, kwboot_msg_debug);
  884. if (rc) {
  885. perror("Failed to start write thread");
  886. return rc;
  887. }
  888. kwboot_printv("Sending debug message. Please reboot the target...");
  889. kwboot_spinner();
  890. err = 0;
  891. off = 0;
  892. while (1) {
  893. /* Read immediately all bytes in queue without waiting */
  894. rc = read(tty, buf + off, sizeof(buf) - off);
  895. if ((rc < 0 && errno == EINTR) || rc == 0) {
  896. continue;
  897. } else if (rc < 0) {
  898. err = errno;
  899. break;
  900. }
  901. off += rc - 1;
  902. kwboot_spinner();
  903. /*
  904. * Check if we received at least 4 debug message patterns
  905. * (console echo from BootROM) in cyclic buffer
  906. */
  907. for (pos = 0; pos < sizeof(kwboot_msg_debug); pos++)
  908. if (buf[off] == kwboot_msg_debug[(pos + off) % sizeof(kwboot_msg_debug)])
  909. break;
  910. for (i = off; i >= 0; i--)
  911. if (buf[i] != kwboot_msg_debug[(pos + i) % sizeof(kwboot_msg_debug)])
  912. break;
  913. off -= i;
  914. if (off >= 4 * sizeof(kwboot_msg_debug))
  915. break;
  916. /* If not move valid suffix from end of the buffer to the beginning of buffer */
  917. memmove(buf, buf + i + 1, off);
  918. }
  919. kwboot_printv("\n");
  920. rc = kwboot_msg_stop_thread(write_thread);
  921. if (rc) {
  922. perror("Failed to stop write thread");
  923. return rc;
  924. }
  925. if (err) {
  926. errno = err;
  927. perror("Failed to read response for debug message pattern");
  928. return -1;
  929. }
  930. /* flush output queue with remaining debug message patterns */
  931. rc = tcflush(tty, TCOFLUSH);
  932. if (rc) {
  933. perror("Failed to flush output queue");
  934. return rc;
  935. }
  936. kwboot_printv("Clearing input buffer...\n");
  937. /*
  938. * Wait until BootROM transmit all remaining echo characters.
  939. * Experimentally it was measured that for Armada 385 BootROM
  940. * it is required to wait at least 0.415s. So wait 0.5s.
  941. */
  942. usleep(500 * 1000);
  943. /*
  944. * In off variable is stored number of characters received after the
  945. * successful detection of echo reply. So these characters are console
  946. * echo for other following debug message patterns. BootROM may have in
  947. * its output queue other echo characters which were being transmitting
  948. * before above sleep call. So read remaining number of echo characters
  949. * sent by the BootROM now.
  950. */
  951. while ((rc = kwboot_tty_recv(tty, &buf[0], 1, 0)) == 0)
  952. off++;
  953. if (errno != ETIMEDOUT) {
  954. perror("Failed to read response");
  955. return rc;
  956. }
  957. /*
  958. * Clear every echo character set by the BootROM by backspace byte.
  959. * This is required prior writing any command to the BootROM debug
  960. * because BootROM command line buffer has limited size. If length
  961. * of the command is larger than buffer size then it looks like
  962. * that Armada 385 BootROM crashes after sending ENTER. So erase it.
  963. * Experimentally it was measured that for Armada 385 BootROM it is
  964. * required to send at least 3 backspace bytes for one echo character.
  965. * This is unknown why. But lets do it.
  966. */
  967. off *= 3;
  968. memset(buf, '\x08', sizeof(buf));
  969. while (off > sizeof(buf)) {
  970. rc = kwboot_tty_send(tty, buf, sizeof(buf), 1);
  971. if (rc) {
  972. perror("Failed to send clear sequence");
  973. return rc;
  974. }
  975. off -= sizeof(buf);
  976. }
  977. rc = kwboot_tty_send(tty, buf, off, 0);
  978. if (rc) {
  979. perror("Failed to send clear sequence");
  980. return rc;
  981. }
  982. usleep(msg_rsp_timeo * 1000);
  983. rc = tcflush(tty, TCIFLUSH);
  984. if (rc) {
  985. perror("Failed to flush input queue");
  986. return rc;
  987. }
  988. return 0;
  989. }
  990. static size_t
  991. kwboot_xm_makeblock(struct kwboot_block *block, const void *data,
  992. size_t size, int pnum)
  993. {
  994. size_t i, n;
  995. block->soh = SOH;
  996. block->pnum = pnum;
  997. block->_pnum = ~block->pnum;
  998. n = size < KWBOOT_XM_BLKSZ ? size : KWBOOT_XM_BLKSZ;
  999. memcpy(&block->data[0], data, n);
  1000. memset(&block->data[n], 0, KWBOOT_XM_BLKSZ - n);
  1001. block->csum = 0;
  1002. for (i = 0; i < n; i++)
  1003. block->csum += block->data[i];
  1004. return n;
  1005. }
  1006. static uint64_t
  1007. _now(void)
  1008. {
  1009. struct timespec ts;
  1010. if (clock_gettime(CLOCK_MONOTONIC, &ts)) {
  1011. static int err_print;
  1012. if (!err_print) {
  1013. perror("clock_gettime() does not work");
  1014. err_print = 1;
  1015. }
  1016. /* this will just make the timeout not work */
  1017. return -1ULL;
  1018. }
  1019. return ts.tv_sec * 1000ULL + (ts.tv_nsec + 500000) / 1000000;
  1020. }
  1021. static int
  1022. _is_xm_reply(char c)
  1023. {
  1024. return c == ACK || c == NAK;
  1025. }
  1026. static int
  1027. _xm_reply_to_error(int c)
  1028. {
  1029. int rc = -1;
  1030. switch (c) {
  1031. case ACK:
  1032. rc = 0;
  1033. break;
  1034. case NAK:
  1035. errno = EBADMSG;
  1036. break;
  1037. default:
  1038. errno = EPROTO;
  1039. break;
  1040. }
  1041. return rc;
  1042. }
  1043. static int
  1044. kwboot_baud_magic_handle(int fd, char c, int baudrate)
  1045. {
  1046. static size_t rcv_len;
  1047. if (rcv_len < sizeof(kwb_baud_magic)) {
  1048. /* try to recognize whole magic word */
  1049. if (c == kwb_baud_magic[rcv_len]) {
  1050. rcv_len++;
  1051. } else {
  1052. printf("%.*s%c", (int)rcv_len, kwb_baud_magic, c);
  1053. fflush(stdout);
  1054. rcv_len = 0;
  1055. }
  1056. }
  1057. if (rcv_len == sizeof(kwb_baud_magic)) {
  1058. /* magic word received */
  1059. kwboot_printv("\nChanging baudrate to %d Bd\n", baudrate);
  1060. return kwboot_tty_change_baudrate(fd, baudrate) ? : 1;
  1061. } else {
  1062. return 0;
  1063. }
  1064. }
  1065. static int
  1066. kwboot_xm_recv_reply(int fd, char *c, int stop_on_non_xm,
  1067. int ignore_nak_reply,
  1068. int allow_non_xm, int *non_xm_print,
  1069. int baudrate, int *baud_changed)
  1070. {
  1071. int timeout = allow_non_xm ? KWBOOT_HDR_RSP_TIMEO : blk_rsp_timeo;
  1072. uint64_t recv_until = _now() + timeout;
  1073. int rc;
  1074. while (1) {
  1075. rc = kwboot_tty_recv(fd, c, 1, timeout);
  1076. if (rc) {
  1077. if (errno != ETIMEDOUT)
  1078. return rc;
  1079. else if (allow_non_xm && *non_xm_print)
  1080. return -1;
  1081. else
  1082. *c = NAK;
  1083. }
  1084. /* If received xmodem reply, end. */
  1085. if (_is_xm_reply(*c)) {
  1086. if (*c == NAK && ignore_nak_reply) {
  1087. timeout = recv_until - _now();
  1088. if (timeout >= 0)
  1089. continue;
  1090. }
  1091. break;
  1092. }
  1093. /*
  1094. * If receiving/printing non-xmodem text output is allowed and
  1095. * such a byte was received, we want to increase receiving time
  1096. * and either:
  1097. * - print the byte, if it is not part of baudrate change magic
  1098. * sequence while baudrate change was requested (-B option)
  1099. * - change baudrate
  1100. * Otherwise decrease timeout by time elapsed.
  1101. */
  1102. if (allow_non_xm) {
  1103. recv_until = _now() + timeout;
  1104. if (baudrate && !*baud_changed) {
  1105. rc = kwboot_baud_magic_handle(fd, *c, baudrate);
  1106. if (rc == 1)
  1107. *baud_changed = 1;
  1108. else if (!rc)
  1109. *non_xm_print = 1;
  1110. else
  1111. return rc;
  1112. } else if (!baudrate || !*baud_changed) {
  1113. putchar(*c);
  1114. fflush(stdout);
  1115. *non_xm_print = 1;
  1116. }
  1117. } else {
  1118. if (stop_on_non_xm)
  1119. break;
  1120. timeout = recv_until - _now();
  1121. if (timeout < 0) {
  1122. errno = ETIMEDOUT;
  1123. return -1;
  1124. }
  1125. }
  1126. }
  1127. return 0;
  1128. }
  1129. static int
  1130. kwboot_xm_sendblock(int fd, struct kwboot_block *block, int allow_non_xm,
  1131. int *done_print, int baudrate, int allow_retries)
  1132. {
  1133. int non_xm_print, baud_changed;
  1134. int rc, err, retries;
  1135. char c;
  1136. *done_print = 0;
  1137. non_xm_print = 0;
  1138. baud_changed = 0;
  1139. retries = 0;
  1140. do {
  1141. rc = kwboot_tty_send(fd, block, sizeof(*block), 1);
  1142. if (rc)
  1143. goto err;
  1144. if (allow_non_xm && !*done_print) {
  1145. kwboot_progress(100, '.');
  1146. kwboot_printv("Done\n");
  1147. *done_print = 1;
  1148. }
  1149. rc = kwboot_xm_recv_reply(fd, &c, retries < 3,
  1150. retries > 8,
  1151. allow_non_xm, &non_xm_print,
  1152. baudrate, &baud_changed);
  1153. if (rc)
  1154. goto err;
  1155. if (!allow_non_xm && c != ACK) {
  1156. if (c == NAK && allow_retries && retries + 1 < 16)
  1157. kwboot_progress(-1, '+');
  1158. else
  1159. kwboot_progress(-1, 'E');
  1160. }
  1161. } while (c == NAK && allow_retries && retries++ < 16);
  1162. if (non_xm_print)
  1163. kwboot_printv("\n");
  1164. if (allow_non_xm && baudrate && !baud_changed) {
  1165. fprintf(stderr, "Baudrate was not changed\n");
  1166. errno = EPROTO;
  1167. return -1;
  1168. }
  1169. return _xm_reply_to_error(c);
  1170. err:
  1171. err = errno;
  1172. kwboot_printv("\n");
  1173. errno = err;
  1174. return rc;
  1175. }
  1176. static int
  1177. kwboot_xm_finish(int fd)
  1178. {
  1179. int rc, retries;
  1180. char c;
  1181. kwboot_printv("Finishing transfer\n");
  1182. retries = 0;
  1183. do {
  1184. rc = kwboot_tty_send_char(fd, EOT);
  1185. if (rc)
  1186. return rc;
  1187. rc = kwboot_xm_recv_reply(fd, &c, retries < 3,
  1188. retries > 8,
  1189. 0, NULL, 0, NULL);
  1190. if (rc)
  1191. return rc;
  1192. } while (c == NAK && retries++ < 16);
  1193. return _xm_reply_to_error(c);
  1194. }
  1195. static int
  1196. kwboot_xmodem_one(int tty, int *pnum, int header, const uint8_t *data,
  1197. size_t size, int baudrate)
  1198. {
  1199. int done_print = 0;
  1200. size_t sent, left;
  1201. int rc;
  1202. kwboot_printv("Sending boot image %s (%zu bytes)...\n",
  1203. header ? "header" : "data", size);
  1204. left = size;
  1205. sent = 0;
  1206. while (sent < size) {
  1207. struct kwboot_block block;
  1208. int last_block;
  1209. size_t blksz;
  1210. blksz = kwboot_xm_makeblock(&block, data, left, (*pnum)++);
  1211. data += blksz;
  1212. last_block = (left <= blksz);
  1213. /*
  1214. * Handling of repeated xmodem packets is completely broken in
  1215. * Armada 385 BootROM - it completely ignores xmodem packet
  1216. * numbers, they are only used for checksum verification.
  1217. * BootROM can handle a retry of the xmodem packet only during
  1218. * the transmission of kwbimage header and only if BootROM
  1219. * itself sent NAK response to previous attempt (it does it on
  1220. * checksum failure). During the transmission of kwbimage data
  1221. * part, BootROM always expects next xmodem packet, even if it
  1222. * sent NAK to previous attempt - there is absolutely no way to
  1223. * repair incorrectly transmitted xmodem packet during kwbimage
  1224. * data part upload. Also, if kwboot receives non-ACK/NAK
  1225. * response (meaning that original BootROM response was damaged
  1226. * on UART) there is no way to detect if BootROM accepted xmodem
  1227. * packet or not and no way to check if kwboot could repeat the
  1228. * packet or not.
  1229. *
  1230. * Stop transfer and return failure if kwboot receives unknown
  1231. * reply if non-xmodem reply is not allowed (for all xmodem
  1232. * packets except the last header packet) or when non-ACK reply
  1233. * is received during data part transfer.
  1234. */
  1235. rc = kwboot_xm_sendblock(tty, &block, header && last_block,
  1236. &done_print, baudrate, header);
  1237. if (rc)
  1238. goto out;
  1239. sent += blksz;
  1240. left -= blksz;
  1241. if (!done_print)
  1242. kwboot_progress(sent * 100 / size, '.');
  1243. }
  1244. if (!done_print)
  1245. kwboot_printv("Done\n");
  1246. return 0;
  1247. out:
  1248. kwboot_printv("\n");
  1249. return rc;
  1250. }
  1251. static int
  1252. kwboot_xmodem(int tty, const void *_img, size_t size, int baudrate)
  1253. {
  1254. const uint8_t *img = _img;
  1255. int rc, pnum;
  1256. size_t hdrsz;
  1257. hdrsz = kwbheader_size(img);
  1258. /*
  1259. * If header size is not aligned to xmodem block size (which applies
  1260. * for all images in kwbimage v0 format) then we have to ensure that
  1261. * the last xmodem block of header contains beginning of the data
  1262. * followed by the header. So align header size to xmodem block size.
  1263. */
  1264. hdrsz += (KWBOOT_XM_BLKSZ - hdrsz % KWBOOT_XM_BLKSZ) % KWBOOT_XM_BLKSZ;
  1265. if (hdrsz > size)
  1266. hdrsz = size;
  1267. pnum = 1;
  1268. rc = kwboot_xmodem_one(tty, &pnum, 1, img, hdrsz, baudrate);
  1269. if (rc)
  1270. return rc;
  1271. /*
  1272. * If we have already sent image data as a part of the last
  1273. * xmodem header block then we have nothing more to send.
  1274. */
  1275. if (hdrsz < size) {
  1276. img += hdrsz;
  1277. size -= hdrsz;
  1278. rc = kwboot_xmodem_one(tty, &pnum, 0, img, size, 0);
  1279. if (rc)
  1280. return rc;
  1281. }
  1282. rc = kwboot_xm_finish(tty);
  1283. if (rc)
  1284. return rc;
  1285. if (baudrate) {
  1286. kwboot_printv("\nChanging baudrate back to 115200 Bd\n\n");
  1287. rc = kwboot_tty_change_baudrate(tty, 115200);
  1288. if (rc)
  1289. return rc;
  1290. }
  1291. return 0;
  1292. }
  1293. static int
  1294. kwboot_term_pipe(int in, int out, const char *quit, int *s, const char *kbs, int *k)
  1295. {
  1296. char buf[128];
  1297. ssize_t nin, noff;
  1298. nin = read(in, buf, sizeof(buf));
  1299. if (nin <= 0)
  1300. return -1;
  1301. noff = 0;
  1302. if (quit || kbs) {
  1303. int i;
  1304. for (i = 0; i < nin; i++) {
  1305. if ((quit || kbs) &&
  1306. (!quit || buf[i] != quit[*s]) &&
  1307. (!kbs || buf[i] != kbs[*k])) {
  1308. const char *prefix;
  1309. int plen;
  1310. if (quit && kbs) {
  1311. prefix = (*s >= *k) ? quit : kbs;
  1312. plen = (*s >= *k) ? *s : *k;
  1313. } else if (quit) {
  1314. prefix = quit;
  1315. plen = *s;
  1316. } else {
  1317. prefix = kbs;
  1318. plen = *k;
  1319. }
  1320. if (plen > i && kwboot_write(out, prefix, plen - i) < 0)
  1321. return -1;
  1322. }
  1323. if (quit && buf[i] == quit[*s]) {
  1324. (*s)++;
  1325. if (!quit[*s]) {
  1326. nin = (i > *s) ? (i - *s) : 0;
  1327. break;
  1328. }
  1329. } else if (quit) {
  1330. *s = 0;
  1331. }
  1332. if (kbs && buf[i] == kbs[*k]) {
  1333. (*k)++;
  1334. if (!kbs[*k]) {
  1335. if (i > *k + noff &&
  1336. kwboot_write(out, buf + noff, i - *k - noff) < 0)
  1337. return -1;
  1338. /*
  1339. * Replace backspace key by '\b' (0x08)
  1340. * byte which is the only recognized
  1341. * backspace byte by Marvell BootROM.
  1342. */
  1343. if (write(out, "\x08", 1) < 0)
  1344. return -1;
  1345. noff = i + 1;
  1346. *k = 0;
  1347. }
  1348. } else if (kbs) {
  1349. *k = 0;
  1350. }
  1351. }
  1352. if (i == nin) {
  1353. i = 0;
  1354. if (quit && i < *s)
  1355. i = *s;
  1356. if (kbs && i < *k)
  1357. i = *k;
  1358. nin -= (nin > i) ? i : nin;
  1359. }
  1360. }
  1361. if (nin > noff && kwboot_write(out, buf + noff, nin - noff) < 0)
  1362. return -1;
  1363. return 0;
  1364. }
  1365. static int
  1366. kwboot_terminal(int tty)
  1367. {
  1368. int rc, in, s, k;
  1369. const char *kbs = NULL;
  1370. const char *quit = "\34c";
  1371. struct termios otio, tio;
  1372. rc = -1;
  1373. in = STDIN_FILENO;
  1374. if (isatty(in)) {
  1375. rc = tcgetattr(in, &otio);
  1376. if (!rc) {
  1377. tio = otio;
  1378. cfmakeraw(&tio);
  1379. rc = tcsetattr(in, TCSANOW, &tio);
  1380. }
  1381. if (rc) {
  1382. perror("tcsetattr");
  1383. goto out;
  1384. }
  1385. /*
  1386. * Get sequence for backspace key used by the current
  1387. * terminal. Every occurrence of this sequence will be
  1388. * replaced by '\b' byte which is the only recognized
  1389. * backspace byte by Marvell BootROM.
  1390. *
  1391. * Note that we cannot read this sequence from termios
  1392. * c_cc[VERASE] as VERASE is valid only when ICANON is
  1393. * set in termios c_lflag, which is not case for us.
  1394. *
  1395. * Also most terminals do not set termios c_cc[VERASE]
  1396. * as c_cc[VERASE] can specify only one-byte sequence
  1397. * and instead let applications to read (possible
  1398. * multi-byte) sequence for backspace key from "kbs"
  1399. * terminfo database based on $TERM env variable.
  1400. *
  1401. * So read "kbs" from terminfo database via tigetstr()
  1402. * call after successful setupterm(). Most terminals
  1403. * use byte 0x7F for backspace key, so replacement with
  1404. * '\b' is required.
  1405. */
  1406. if (setupterm(NULL, STDOUT_FILENO, &rc) == 0) {
  1407. kbs = tigetstr("kbs");
  1408. if (kbs == (char *)-1)
  1409. kbs = NULL;
  1410. }
  1411. kwboot_printv("[Type Ctrl-%c + %c to quit]\r\n",
  1412. quit[0] | 0100, quit[1]);
  1413. } else
  1414. in = -1;
  1415. rc = 0;
  1416. s = 0;
  1417. k = 0;
  1418. do {
  1419. fd_set rfds;
  1420. int nfds = 0;
  1421. FD_ZERO(&rfds);
  1422. FD_SET(tty, &rfds);
  1423. nfds = nfds < tty ? tty : nfds;
  1424. if (in >= 0) {
  1425. FD_SET(in, &rfds);
  1426. nfds = nfds < in ? in : nfds;
  1427. }
  1428. nfds = select(nfds + 1, &rfds, NULL, NULL, NULL);
  1429. if (nfds < 0)
  1430. break;
  1431. if (FD_ISSET(tty, &rfds)) {
  1432. rc = kwboot_term_pipe(tty, STDOUT_FILENO, NULL, NULL, NULL, NULL);
  1433. if (rc)
  1434. break;
  1435. }
  1436. if (in >= 0 && FD_ISSET(in, &rfds)) {
  1437. rc = kwboot_term_pipe(in, tty, quit, &s, kbs, &k);
  1438. if (rc)
  1439. break;
  1440. }
  1441. } while (quit[s] != 0);
  1442. if (in >= 0)
  1443. tcsetattr(in, TCSANOW, &otio);
  1444. printf("\n");
  1445. out:
  1446. return rc;
  1447. }
  1448. static void *
  1449. kwboot_read_image(const char *path, size_t *size, size_t reserve)
  1450. {
  1451. int rc, fd;
  1452. void *img;
  1453. off_t len;
  1454. off_t tot;
  1455. rc = -1;
  1456. img = NULL;
  1457. fd = open(path, O_RDONLY);
  1458. if (fd < 0)
  1459. goto out;
  1460. len = lseek(fd, 0, SEEK_END);
  1461. if (len == (off_t)-1)
  1462. goto out;
  1463. if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
  1464. goto out;
  1465. img = malloc(len + reserve);
  1466. if (!img)
  1467. goto out;
  1468. tot = 0;
  1469. while (tot < len) {
  1470. ssize_t rd = read(fd, img + tot, len - tot);
  1471. if (rd < 0)
  1472. goto out;
  1473. tot += rd;
  1474. if (!rd && tot < len) {
  1475. errno = EIO;
  1476. goto out;
  1477. }
  1478. }
  1479. rc = 0;
  1480. *size = len;
  1481. out:
  1482. if (rc && img) {
  1483. free(img);
  1484. img = NULL;
  1485. }
  1486. if (fd >= 0)
  1487. close(fd);
  1488. return img;
  1489. }
  1490. static uint8_t
  1491. kwboot_hdr_csum8(const void *hdr)
  1492. {
  1493. const uint8_t *data = hdr;
  1494. uint8_t csum;
  1495. size_t size;
  1496. size = kwbheader_size_for_csum(hdr);
  1497. for (csum = 0; size-- > 0; data++)
  1498. csum += *data;
  1499. return csum;
  1500. }
  1501. static uint32_t *
  1502. kwboot_img_csum32_ptr(void *img)
  1503. {
  1504. struct main_hdr_v1 *hdr = img;
  1505. uint32_t datasz;
  1506. datasz = le32_to_cpu(hdr->blocksize) - sizeof(uint32_t);
  1507. return img + le32_to_cpu(hdr->srcaddr) + datasz;
  1508. }
  1509. static uint32_t
  1510. kwboot_img_csum32(const void *img)
  1511. {
  1512. const struct main_hdr_v1 *hdr = img;
  1513. uint32_t datasz, csum = 0;
  1514. const uint32_t *data;
  1515. datasz = le32_to_cpu(hdr->blocksize) - sizeof(csum);
  1516. if (datasz % sizeof(uint32_t))
  1517. return 0;
  1518. data = img + le32_to_cpu(hdr->srcaddr);
  1519. while (datasz > 0) {
  1520. csum += le32_to_cpu(*data++);
  1521. datasz -= 4;
  1522. }
  1523. return cpu_to_le32(csum);
  1524. }
  1525. static int
  1526. kwboot_img_is_secure(void *img)
  1527. {
  1528. struct opt_hdr_v1 *ohdr;
  1529. for_each_opt_hdr_v1 (ohdr, img)
  1530. if (ohdr->headertype == OPT_HDR_V1_SECURE_TYPE)
  1531. return 1;
  1532. return 0;
  1533. }
  1534. static int
  1535. kwboot_img_has_ddr_init(void *img)
  1536. {
  1537. const struct register_set_hdr_v1 *rhdr;
  1538. const struct main_hdr_v0 *hdr0;
  1539. struct opt_hdr_v1 *ohdr;
  1540. u32 ohdrsz;
  1541. int last;
  1542. /*
  1543. * kwbimage v0 image headers contain DDR init code either in
  1544. * extension header or in binary code header.
  1545. */
  1546. if (kwbimage_version(img) == 0) {
  1547. hdr0 = img;
  1548. return hdr0->ext || hdr0->bin;
  1549. }
  1550. /*
  1551. * kwbimage v1 image headers contain DDR init code either in binary
  1552. * code header or in a register set list header with SDRAM_SETUP.
  1553. */
  1554. for_each_opt_hdr_v1 (ohdr, img) {
  1555. if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE)
  1556. return 1;
  1557. if (ohdr->headertype == OPT_HDR_V1_REGISTER_TYPE) {
  1558. rhdr = (const struct register_set_hdr_v1 *)ohdr;
  1559. ohdrsz = opt_hdr_v1_size(ohdr);
  1560. if (ohdrsz >= sizeof(*ohdr) + sizeof(rhdr->data[0].last_entry)) {
  1561. ohdrsz -= sizeof(*ohdr) + sizeof(rhdr->data[0].last_entry);
  1562. last = ohdrsz / sizeof(rhdr->data[0].entry);
  1563. if (rhdr->data[last].last_entry.delay ==
  1564. REGISTER_SET_HDR_OPT_DELAY_SDRAM_SETUP)
  1565. return 1;
  1566. }
  1567. }
  1568. }
  1569. return 0;
  1570. }
  1571. static void *
  1572. kwboot_img_grow_data_right(void *img, size_t *size, size_t grow)
  1573. {
  1574. struct main_hdr_v1 *hdr = img;
  1575. void *result;
  1576. /*
  1577. * 32-bit checksum comes after end of image code, so we will be putting
  1578. * new code there. So we get this pointer and then increase data size
  1579. * (since increasing data size changes kwboot_img_csum32_ptr() return
  1580. * value).
  1581. */
  1582. result = kwboot_img_csum32_ptr(img);
  1583. hdr->blocksize = cpu_to_le32(le32_to_cpu(hdr->blocksize) + grow);
  1584. *size += grow;
  1585. return result;
  1586. }
  1587. static void
  1588. kwboot_img_grow_hdr(void *img, size_t *size, size_t grow)
  1589. {
  1590. uint32_t hdrsz, datasz, srcaddr;
  1591. struct main_hdr_v1 *hdr = img;
  1592. struct opt_hdr_v1 *ohdr;
  1593. uint8_t *data;
  1594. srcaddr = le32_to_cpu(hdr->srcaddr);
  1595. /* calculate real used space in kwbimage header */
  1596. if (kwbimage_version(img) == 0) {
  1597. hdrsz = kwbheader_size(img);
  1598. } else {
  1599. hdrsz = sizeof(*hdr);
  1600. for_each_opt_hdr_v1 (ohdr, hdr)
  1601. hdrsz += opt_hdr_v1_size(ohdr);
  1602. }
  1603. data = (uint8_t *)img + srcaddr;
  1604. datasz = *size - srcaddr;
  1605. /* only move data if there is not enough space */
  1606. if (hdrsz + grow > srcaddr) {
  1607. size_t need = hdrsz + grow - srcaddr;
  1608. /* move data by enough bytes */
  1609. memmove(data + need, data, datasz);
  1610. hdr->srcaddr = cpu_to_le32(srcaddr + need);
  1611. *size += need;
  1612. }
  1613. if (kwbimage_version(img) == 1) {
  1614. hdrsz += grow;
  1615. if (hdrsz > kwbheader_size(img)) {
  1616. hdr->headersz_msb = hdrsz >> 16;
  1617. hdr->headersz_lsb = cpu_to_le16(hdrsz & 0xffff);
  1618. }
  1619. }
  1620. }
  1621. static void *
  1622. kwboot_add_bin_ohdr_v1(void *img, size_t *size, uint32_t binsz)
  1623. {
  1624. struct main_hdr_v1 *hdr = img;
  1625. struct opt_hdr_v1 *ohdr;
  1626. uint32_t num_args;
  1627. uint32_t offset;
  1628. uint32_t ohdrsz;
  1629. uint8_t *prev_ext;
  1630. if (hdr->ext) {
  1631. for_each_opt_hdr_v1 (ohdr, img)
  1632. if (opt_hdr_v1_next(ohdr) == NULL)
  1633. break;
  1634. prev_ext = opt_hdr_v1_ext(ohdr);
  1635. ohdr = _opt_hdr_v1_next(ohdr);
  1636. } else {
  1637. ohdr = (void *)(hdr + 1);
  1638. prev_ext = &hdr->ext;
  1639. }
  1640. /*
  1641. * ARM executable code inside the BIN header on some mvebu platforms
  1642. * (e.g. A370, AXP) must always be aligned with the 128-bit boundary.
  1643. * This requirement can be met by inserting dummy arguments into
  1644. * BIN header, if needed.
  1645. */
  1646. offset = &ohdr->data[4] - (char *)img;
  1647. num_args = ((16 - offset % 16) % 16) / sizeof(uint32_t);
  1648. ohdrsz = sizeof(*ohdr) + 4 + 4 * num_args + binsz + 4;
  1649. kwboot_img_grow_hdr(hdr, size, ohdrsz);
  1650. *prev_ext = 1;
  1651. ohdr->headertype = OPT_HDR_V1_BINARY_TYPE;
  1652. ohdr->headersz_msb = ohdrsz >> 16;
  1653. ohdr->headersz_lsb = cpu_to_le16(ohdrsz & 0xffff);
  1654. memset(&ohdr->data[0], 0, ohdrsz - sizeof(*ohdr));
  1655. *(uint32_t *)&ohdr->data[0] = cpu_to_le32(num_args);
  1656. return &ohdr->data[4 + 4 * num_args];
  1657. }
  1658. static void
  1659. _inject_baudrate_change_code(void *img, size_t *size, int for_data,
  1660. int old_baud, int new_baud)
  1661. {
  1662. struct main_hdr_v1 *hdr = img;
  1663. uint32_t orig_datasz;
  1664. uint32_t codesz;
  1665. uint8_t *code;
  1666. if (for_data) {
  1667. orig_datasz = le32_to_cpu(hdr->blocksize) - sizeof(uint32_t);
  1668. codesz = sizeof(kwboot_baud_code) +
  1669. sizeof(kwboot_baud_code_data_jump);
  1670. code = kwboot_img_grow_data_right(img, size, codesz);
  1671. } else {
  1672. codesz = sizeof(kwboot_baud_code_binhdr_pre) +
  1673. sizeof(kwboot_baud_code) +
  1674. sizeof(kwboot_baud_code_binhdr_post);
  1675. code = kwboot_add_bin_ohdr_v1(img, size, codesz);
  1676. codesz = sizeof(kwboot_baud_code_binhdr_pre);
  1677. memcpy(code, kwboot_baud_code_binhdr_pre, codesz);
  1678. code += codesz;
  1679. }
  1680. codesz = sizeof(kwboot_baud_code) - 2 * sizeof(uint32_t);
  1681. memcpy(code, kwboot_baud_code, codesz);
  1682. code += codesz;
  1683. *(uint32_t *)code = cpu_to_le32(old_baud);
  1684. code += sizeof(uint32_t);
  1685. *(uint32_t *)code = cpu_to_le32(new_baud);
  1686. code += sizeof(uint32_t);
  1687. if (for_data) {
  1688. codesz = sizeof(kwboot_baud_code_data_jump) - sizeof(uint32_t);
  1689. memcpy(code, kwboot_baud_code_data_jump, codesz);
  1690. code += codesz;
  1691. *(uint32_t *)code = hdr->execaddr;
  1692. code += sizeof(uint32_t);
  1693. hdr->execaddr = cpu_to_le32(le32_to_cpu(hdr->destaddr) + orig_datasz);
  1694. } else {
  1695. codesz = sizeof(kwboot_baud_code_binhdr_post);
  1696. memcpy(code, kwboot_baud_code_binhdr_post, codesz);
  1697. code += codesz;
  1698. }
  1699. }
  1700. static int
  1701. kwboot_img_guess_sata_blksz(void *img, uint32_t blkoff, uint32_t data_size, size_t total_size)
  1702. {
  1703. uint32_t sum, *ptr, *end;
  1704. int blksz;
  1705. /*
  1706. * Try all possible sector sizes which are power of two,
  1707. * at least 512 bytes and up to the 32 kB.
  1708. */
  1709. for (blksz = 512; blksz < 0x10000; blksz *= 2) {
  1710. if (blkoff * blksz > total_size ||
  1711. blkoff * blksz + data_size > total_size ||
  1712. data_size % 4)
  1713. break;
  1714. /*
  1715. * Calculate data checksum and if it matches
  1716. * then tried blksz should be correct.
  1717. */
  1718. ptr = img + blkoff * blksz;
  1719. end = (void *)ptr + data_size - 4;
  1720. for (sum = 0; ptr < end; ptr++)
  1721. sum += *ptr;
  1722. if (sum == *end)
  1723. return blksz;
  1724. }
  1725. /* Fallback to 512 bytes */
  1726. return 512;
  1727. }
  1728. static const char *
  1729. kwboot_img_type(uint8_t blockid)
  1730. {
  1731. switch (blockid) {
  1732. case IBR_HDR_I2C_ID: return "I2C";
  1733. case IBR_HDR_SPI_ID: return "SPI";
  1734. case IBR_HDR_NAND_ID: return "NAND";
  1735. case IBR_HDR_SATA_ID: return "SATA";
  1736. case IBR_HDR_PEX_ID: return "PEX";
  1737. case IBR_HDR_UART_ID: return "UART";
  1738. case IBR_HDR_SDIO_ID: return "SDIO";
  1739. default: return "unknown";
  1740. }
  1741. }
  1742. static int
  1743. kwboot_img_patch(void *img, size_t *size, int baudrate)
  1744. {
  1745. struct main_hdr_v1 *hdr;
  1746. struct opt_hdr_v1 *ohdr;
  1747. uint32_t srcaddr;
  1748. uint8_t csum;
  1749. size_t hdrsz;
  1750. int image_ver;
  1751. int is_secure;
  1752. hdr = img;
  1753. if (*size < sizeof(struct main_hdr_v1)) {
  1754. fprintf(stderr, "Invalid image header size\n");
  1755. goto err;
  1756. }
  1757. image_ver = kwbimage_version(img);
  1758. if (image_ver != 0 && image_ver != 1) {
  1759. fprintf(stderr, "Invalid image header version\n");
  1760. goto err;
  1761. }
  1762. hdrsz = kwbheader_size(hdr);
  1763. if (*size < hdrsz) {
  1764. fprintf(stderr, "Invalid image header size\n");
  1765. goto err;
  1766. }
  1767. kwboot_printv("Detected kwbimage v%d with %s boot signature\n", image_ver, kwboot_img_type(hdr->blockid));
  1768. csum = kwboot_hdr_csum8(hdr) - hdr->checksum;
  1769. if (csum != hdr->checksum) {
  1770. fprintf(stderr, "Image has invalid header checksum stored in image header\n");
  1771. goto err;
  1772. }
  1773. srcaddr = le32_to_cpu(hdr->srcaddr);
  1774. switch (hdr->blockid) {
  1775. case IBR_HDR_SATA_ID:
  1776. hdr->srcaddr = cpu_to_le32(srcaddr * kwboot_img_guess_sata_blksz(img, srcaddr, le32_to_cpu(hdr->blocksize), *size));
  1777. break;
  1778. case IBR_HDR_PEX_ID:
  1779. if (srcaddr == 0xFFFFFFFF)
  1780. hdr->srcaddr = cpu_to_le32(hdrsz);
  1781. break;
  1782. case IBR_HDR_SPI_ID:
  1783. if (hdr->destaddr == cpu_to_le32(0xFFFFFFFF)) {
  1784. kwboot_printv("Patching destination and execution addresses from SPI/NOR XIP area to DDR area 0x00800000\n");
  1785. hdr->destaddr = cpu_to_le32(0x00800000 + le32_to_cpu(hdr->srcaddr));
  1786. hdr->execaddr = cpu_to_le32(0x00800000 + le32_to_cpu(hdr->execaddr));
  1787. }
  1788. break;
  1789. }
  1790. if (hdrsz > le32_to_cpu(hdr->srcaddr)) {
  1791. fprintf(stderr, "Image has invalid data offset stored in image header\n");
  1792. goto err;
  1793. }
  1794. if (*size < le32_to_cpu(hdr->srcaddr) + le32_to_cpu(hdr->blocksize)) {
  1795. fprintf(stderr, "Image has invalid data size stored in image header\n");
  1796. goto err;
  1797. }
  1798. for_each_opt_hdr_v1 (ohdr, hdr) {
  1799. if (!opt_hdr_v1_valid_size(ohdr, (const uint8_t *)hdr + hdrsz)) {
  1800. fprintf(stderr, "Invalid optional image header\n");
  1801. goto err;
  1802. }
  1803. }
  1804. /*
  1805. * The 32-bit data checksum is optional for UART image. If it is not
  1806. * present (checksum detected as invalid) then grow data part of the
  1807. * image for the checksum, so it can be inserted there.
  1808. */
  1809. if (kwboot_img_csum32(img) != *kwboot_img_csum32_ptr(img)) {
  1810. if (hdr->blockid != IBR_HDR_UART_ID) {
  1811. fprintf(stderr, "Image has invalid data checksum\n");
  1812. goto err;
  1813. }
  1814. kwboot_img_grow_data_right(img, size, sizeof(uint32_t));
  1815. /* Update the 32-bit data checksum */
  1816. *kwboot_img_csum32_ptr(img) = kwboot_img_csum32(img);
  1817. }
  1818. if (!kwboot_img_has_ddr_init(img) &&
  1819. (le32_to_cpu(hdr->destaddr) < 0x40000000 ||
  1820. le32_to_cpu(hdr->destaddr) + le32_to_cpu(hdr->blocksize) > 0x40034000)) {
  1821. fprintf(stderr, "Image does not contain DDR init code needed for UART booting\n");
  1822. goto err;
  1823. }
  1824. is_secure = kwboot_img_is_secure(img);
  1825. if (hdr->blockid != IBR_HDR_UART_ID) {
  1826. if (is_secure) {
  1827. fprintf(stderr,
  1828. "Image has secure header with signature for non-UART booting\n");
  1829. goto err;
  1830. }
  1831. kwboot_printv("Patching image boot signature to UART\n");
  1832. hdr->blockid = IBR_HDR_UART_ID;
  1833. }
  1834. if (!is_secure) {
  1835. if (image_ver == 1) {
  1836. /*
  1837. * Tell BootROM to send BootROM messages to UART port
  1838. * number 0 (used also for UART booting) with default
  1839. * baudrate (which should be 115200) and do not touch
  1840. * UART MPP configuration.
  1841. */
  1842. hdr->flags |= 0x1;
  1843. hdr->options &= ~0x1F;
  1844. hdr->options |= MAIN_HDR_V1_OPT_BAUD_DEFAULT;
  1845. hdr->options |= 0 << 3;
  1846. }
  1847. if (image_ver == 0)
  1848. ((struct main_hdr_v0 *)img)->nandeccmode = IBR_HDR_ECC_DISABLED;
  1849. hdr->nandpagesize = 0;
  1850. }
  1851. if (baudrate) {
  1852. if (image_ver == 0) {
  1853. fprintf(stderr,
  1854. "Cannot inject code for changing baudrate into v0 image header\n");
  1855. goto err;
  1856. }
  1857. if (is_secure) {
  1858. fprintf(stderr,
  1859. "Cannot inject code for changing baudrate into image with secure header\n");
  1860. goto err;
  1861. }
  1862. /*
  1863. * First inject code that changes the baudrate from the default
  1864. * value of 115200 Bd to requested value. This code is inserted
  1865. * as a new opt hdr, so it is executed by BootROM after the
  1866. * header part is received.
  1867. */
  1868. kwboot_printv("Injecting binary header code for changing baudrate to %d Bd\n",
  1869. baudrate);
  1870. _inject_baudrate_change_code(img, size, 0, 115200, baudrate);
  1871. /*
  1872. * Now inject code that changes the baudrate back to 115200 Bd.
  1873. * This code is appended after the data part of the image, and
  1874. * execaddr is changed so that it is executed before U-Boot
  1875. * proper.
  1876. */
  1877. kwboot_printv("Injecting code for changing baudrate back\n");
  1878. _inject_baudrate_change_code(img, size, 1, baudrate, 115200);
  1879. /* Update the 32-bit data checksum */
  1880. *kwboot_img_csum32_ptr(img) = kwboot_img_csum32(img);
  1881. /* recompute header size */
  1882. hdrsz = kwbheader_size(hdr);
  1883. }
  1884. if (hdrsz % KWBOOT_XM_BLKSZ) {
  1885. size_t grow = KWBOOT_XM_BLKSZ - hdrsz % KWBOOT_XM_BLKSZ;
  1886. if (is_secure) {
  1887. fprintf(stderr, "Cannot align image with secure header\n");
  1888. goto err;
  1889. }
  1890. kwboot_printv("Aligning image header to Xmodem block size\n");
  1891. kwboot_img_grow_hdr(img, size, grow);
  1892. hdrsz += grow;
  1893. /*
  1894. * kwbimage v1 contains header size field and for UART type it
  1895. * must be set to the aligned xmodem header size because BootROM
  1896. * rounds header size down to xmodem block size.
  1897. */
  1898. if (kwbimage_version(img) == 1) {
  1899. hdr->headersz_msb = hdrsz >> 16;
  1900. hdr->headersz_lsb = cpu_to_le16(hdrsz & 0xffff);
  1901. }
  1902. }
  1903. /* Header size and source address must be same for UART type due to A38x BootROM bug */
  1904. if (hdrsz != le32_to_cpu(hdr->srcaddr)) {
  1905. if (is_secure) {
  1906. fprintf(stderr, "Cannot align image with secure header\n");
  1907. goto err;
  1908. }
  1909. kwboot_printv("Removing gap between image header and data\n");
  1910. memmove(img + hdrsz, img + le32_to_cpu(hdr->srcaddr), le32_to_cpu(hdr->blocksize));
  1911. hdr->srcaddr = cpu_to_le32(hdrsz);
  1912. }
  1913. hdr->checksum = kwboot_hdr_csum8(hdr) - csum;
  1914. *size = le32_to_cpu(hdr->srcaddr) + le32_to_cpu(hdr->blocksize);
  1915. return 0;
  1916. err:
  1917. errno = EINVAL;
  1918. return -1;
  1919. }
  1920. static void
  1921. kwboot_usage(FILE *stream, char *progname)
  1922. {
  1923. fprintf(stream,
  1924. "Usage: %s [OPTIONS] [-b <image> | -D <image> | -b | -d ] [-B <baud> ] [-t] <TTY>\n",
  1925. progname);
  1926. fprintf(stream, "\n");
  1927. fprintf(stream,
  1928. " -b <image>: boot <image> with preamble (Kirkwood, Avanta, Armada 370/XP/375/38x/39x)\n");
  1929. fprintf(stream,
  1930. " -D <image>: boot <image> without preamble (Dove)\n");
  1931. fprintf(stream, " -b: enter xmodem boot mode\n");
  1932. fprintf(stream, " -d: enter console debug mode\n");
  1933. fprintf(stream, " -a: use timings for Armada XP\n");
  1934. fprintf(stream, " -s <resp-timeo>: use specific response-timeout\n");
  1935. fprintf(stream,
  1936. " -o <block-timeo>: use specific xmodem block timeout\n");
  1937. fprintf(stream, "\n");
  1938. fprintf(stream, " -t: mini terminal\n");
  1939. fprintf(stream, "\n");
  1940. fprintf(stream, " -B <baud>: set baud rate\n");
  1941. fprintf(stream, "\n");
  1942. }
  1943. int
  1944. main(int argc, char **argv)
  1945. {
  1946. const char *ttypath, *imgpath;
  1947. int rv, rc, tty, term;
  1948. int bootmsg;
  1949. int debugmsg;
  1950. void *img;
  1951. size_t size;
  1952. size_t after_img_rsv;
  1953. int baudrate;
  1954. int prev_optind;
  1955. int c;
  1956. rv = 1;
  1957. tty = -1;
  1958. bootmsg = 0;
  1959. debugmsg = 0;
  1960. imgpath = NULL;
  1961. img = NULL;
  1962. term = 0;
  1963. size = 0;
  1964. after_img_rsv = KWBOOT_XM_BLKSZ;
  1965. baudrate = 115200;
  1966. printf("kwboot version %s\n", PLAIN_VERSION);
  1967. kwboot_verbose = isatty(STDOUT_FILENO);
  1968. do {
  1969. prev_optind = optind;
  1970. c = getopt(argc, argv, "hbptaB:dD:q:s:o:");
  1971. if (c < 0)
  1972. break;
  1973. switch (c) {
  1974. case 'b':
  1975. if (imgpath || bootmsg || debugmsg)
  1976. goto usage;
  1977. bootmsg = 1;
  1978. if (prev_optind == optind)
  1979. goto usage;
  1980. /* Option -b could have optional argument which specify image path */
  1981. if (optind < argc && argv[optind] && argv[optind][0] != '-')
  1982. imgpath = argv[optind++];
  1983. break;
  1984. case 'D':
  1985. if (imgpath || bootmsg || debugmsg)
  1986. goto usage;
  1987. bootmsg = 0;
  1988. imgpath = optarg;
  1989. break;
  1990. case 'd':
  1991. if (imgpath || bootmsg || debugmsg)
  1992. goto usage;
  1993. debugmsg = 1;
  1994. break;
  1995. case 'p':
  1996. /* nop, for backward compatibility */
  1997. break;
  1998. case 't':
  1999. term = 1;
  2000. break;
  2001. case 'a':
  2002. msg_rsp_timeo = KWBOOT_MSG_RSP_TIMEO_AXP;
  2003. break;
  2004. case 'q':
  2005. /* nop, for backward compatibility */
  2006. break;
  2007. case 's':
  2008. msg_rsp_timeo = atoi(optarg);
  2009. break;
  2010. case 'o':
  2011. blk_rsp_timeo = atoi(optarg);
  2012. break;
  2013. case 'B':
  2014. baudrate = atoi(optarg);
  2015. break;
  2016. case 'h':
  2017. rv = 0;
  2018. default:
  2019. goto usage;
  2020. }
  2021. } while (1);
  2022. if (!bootmsg && !term && !debugmsg && !imgpath)
  2023. goto usage;
  2024. /*
  2025. * If there is no remaining argument but optional imgpath was parsed
  2026. * then it means that optional imgpath was eaten by getopt parser.
  2027. * Reassing imgpath to required ttypath argument.
  2028. */
  2029. if (optind == argc && imgpath) {
  2030. ttypath = imgpath;
  2031. imgpath = NULL;
  2032. } else if (optind + 1 == argc) {
  2033. ttypath = argv[optind];
  2034. } else {
  2035. goto usage;
  2036. }
  2037. /* boot and debug message use baudrate 115200 */
  2038. if (((bootmsg && !imgpath) || debugmsg) && baudrate != 115200) {
  2039. fprintf(stderr, "Baudrate other than 115200 cannot be used for this operation.\n");
  2040. goto usage;
  2041. }
  2042. tty = kwboot_open_tty(ttypath, baudrate);
  2043. if (tty < 0) {
  2044. perror(ttypath);
  2045. goto out;
  2046. }
  2047. /*
  2048. * initial baudrate for image transfer is always 115200,
  2049. * the change to different baudrate is done only after the header is sent
  2050. */
  2051. if (imgpath && baudrate != 115200) {
  2052. rc = kwboot_tty_change_baudrate(tty, 115200);
  2053. if (rc) {
  2054. perror(ttypath);
  2055. goto out;
  2056. }
  2057. }
  2058. if (baudrate == 115200)
  2059. /* do not change baudrate during Xmodem to the same value */
  2060. baudrate = 0;
  2061. else
  2062. /* ensure we have enough space for baudrate change code */
  2063. after_img_rsv += sizeof(struct opt_hdr_v1) + 8 + 16 +
  2064. sizeof(kwboot_baud_code_binhdr_pre) +
  2065. sizeof(kwboot_baud_code) +
  2066. sizeof(kwboot_baud_code_binhdr_post) +
  2067. KWBOOT_XM_BLKSZ +
  2068. sizeof(kwboot_baud_code) +
  2069. sizeof(kwboot_baud_code_data_jump) +
  2070. sizeof(uint32_t) +
  2071. KWBOOT_XM_BLKSZ;
  2072. if (imgpath) {
  2073. img = kwboot_read_image(imgpath, &size, after_img_rsv);
  2074. if (!img) {
  2075. perror(imgpath);
  2076. goto out;
  2077. }
  2078. rc = kwboot_img_patch(img, &size, baudrate);
  2079. if (rc) {
  2080. fprintf(stderr, "%s: Invalid image.\n", imgpath);
  2081. goto out;
  2082. }
  2083. }
  2084. if (debugmsg) {
  2085. rc = kwboot_debugmsg(tty);
  2086. if (rc)
  2087. goto out;
  2088. } else if (bootmsg) {
  2089. rc = kwboot_bootmsg(tty);
  2090. if (rc)
  2091. goto out;
  2092. }
  2093. if (img) {
  2094. rc = kwboot_xmodem(tty, img, size, baudrate);
  2095. if (rc) {
  2096. perror("xmodem");
  2097. goto out;
  2098. }
  2099. }
  2100. if (term) {
  2101. rc = kwboot_terminal(tty);
  2102. if (rc && !(errno == EINTR)) {
  2103. perror("terminal");
  2104. goto out;
  2105. }
  2106. }
  2107. rv = 0;
  2108. out:
  2109. if (tty >= 0)
  2110. close(tty);
  2111. if (img)
  2112. free(img);
  2113. return rv;
  2114. usage:
  2115. kwboot_usage(rv ? stderr : stdout, basename(argv[0]));
  2116. goto out;
  2117. }