flashrom.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223
  1. /*
  2. * This file is part of the flashrom project.
  3. *
  4. * Copyright (C) 2000 Silicon Integrated System Corporation
  5. * Copyright (C) 2004 Tyan Corp <yhlu@tyan.com>
  6. * Copyright (C) 2005-2008 coresystems GmbH
  7. * Copyright (C) 2008,2009 Carl-Daniel Hailfinger
  8. * Copyright (C) 2016-2017 Raptor Engineering, LLC
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 2 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  23. */
  24. #include <stdio.h>
  25. #include <sys/types.h>
  26. #ifndef __LIBPAYLOAD__
  27. #include <fcntl.h>
  28. #include <sys/stat.h>
  29. #endif
  30. #include <string.h>
  31. #include <unistd.h>
  32. #include <stdlib.h>
  33. #include <errno.h>
  34. #include <ctype.h>
  35. #include <getopt.h>
  36. #if HAVE_UTSNAME == 1
  37. #include <sys/utsname.h>
  38. #endif
  39. #include "flash.h"
  40. #include "flashchips.h"
  41. #include "programmer.h"
  42. #include "hwaccess.h"
  43. const char flashrom_version[] = FLASHROM_VERSION;
  44. const char *chip_to_probe = NULL;
  45. static enum programmer programmer = PROGRAMMER_INVALID;
  46. static const char *programmer_param = NULL;
  47. /*
  48. * Programmers supporting multiple buses can have differing size limits on
  49. * each bus. Store the limits for each bus in a common struct.
  50. */
  51. struct decode_sizes max_rom_decode;
  52. /* If nonzero, used as the start address of bottom-aligned flash. */
  53. unsigned long flashbase;
  54. /* Is writing allowed with this programmer? */
  55. int programmer_may_write;
  56. const struct programmer_entry programmer_table[] = {
  57. #if CONFIG_INTERNAL == 1
  58. {
  59. .name = "internal",
  60. .type = OTHER,
  61. .devs.note = NULL,
  62. .init = internal_init,
  63. .map_flash_region = physmap,
  64. .unmap_flash_region = physunmap,
  65. .delay = internal_delay,
  66. },
  67. #endif
  68. #if CONFIG_DUMMY == 1
  69. {
  70. .name = "dummy",
  71. .type = OTHER,
  72. /* FIXME */
  73. .devs.note = "Dummy device, does nothing and logs all accesses\n",
  74. .init = dummy_init,
  75. .map_flash_region = dummy_map,
  76. .unmap_flash_region = dummy_unmap,
  77. .delay = internal_delay,
  78. },
  79. #endif
  80. #if CONFIG_NIC3COM == 1
  81. {
  82. .name = "nic3com",
  83. .type = PCI,
  84. .devs.dev = nics_3com,
  85. .init = nic3com_init,
  86. .map_flash_region = fallback_map,
  87. .unmap_flash_region = fallback_unmap,
  88. .delay = internal_delay,
  89. },
  90. #endif
  91. #if CONFIG_NICREALTEK == 1
  92. {
  93. /* This programmer works for Realtek RTL8139 and SMC 1211. */
  94. .name = "nicrealtek",
  95. .type = PCI,
  96. .devs.dev = nics_realtek,
  97. .init = nicrealtek_init,
  98. .map_flash_region = fallback_map,
  99. .unmap_flash_region = fallback_unmap,
  100. .delay = internal_delay,
  101. },
  102. #endif
  103. #if CONFIG_NICNATSEMI == 1
  104. {
  105. .name = "nicnatsemi",
  106. .type = PCI,
  107. .devs.dev = nics_natsemi,
  108. .init = nicnatsemi_init,
  109. .map_flash_region = fallback_map,
  110. .unmap_flash_region = fallback_unmap,
  111. .delay = internal_delay,
  112. },
  113. #endif
  114. #if CONFIG_GFXNVIDIA == 1
  115. {
  116. .name = "gfxnvidia",
  117. .type = PCI,
  118. .devs.dev = gfx_nvidia,
  119. .init = gfxnvidia_init,
  120. .map_flash_region = fallback_map,
  121. .unmap_flash_region = fallback_unmap,
  122. .delay = internal_delay,
  123. },
  124. #endif
  125. #if CONFIG_AST1100 == 1
  126. {
  127. .name = "ast1100",
  128. .type = PCI,
  129. .devs.dev = bmc_aspeed_ast1100,
  130. .init = ast1100_init,
  131. .map_flash_region = fallback_map,
  132. .unmap_flash_region = fallback_unmap,
  133. .delay = internal_delay,
  134. },
  135. #endif
  136. #if CONFIG_AST2400 == 1
  137. {
  138. .name = "ast2400",
  139. .type = PCI,
  140. .devs.dev = bmc_aspeed_ast2400,
  141. .init = ast2400_init,
  142. .map_flash_region = fallback_map,
  143. .unmap_flash_region = fallback_unmap,
  144. .delay = internal_delay,
  145. },
  146. #endif
  147. #if CONFIG_DRKAISER == 1
  148. {
  149. .name = "drkaiser",
  150. .type = PCI,
  151. .devs.dev = drkaiser_pcidev,
  152. .init = drkaiser_init,
  153. .map_flash_region = fallback_map,
  154. .unmap_flash_region = fallback_unmap,
  155. .delay = internal_delay,
  156. },
  157. #endif
  158. #if CONFIG_SATASII == 1
  159. {
  160. .name = "satasii",
  161. .type = PCI,
  162. .devs.dev = satas_sii,
  163. .init = satasii_init,
  164. .map_flash_region = fallback_map,
  165. .unmap_flash_region = fallback_unmap,
  166. .delay = internal_delay,
  167. },
  168. #endif
  169. #if CONFIG_ATAHPT == 1
  170. {
  171. .name = "atahpt",
  172. .type = PCI,
  173. .devs.dev = ata_hpt,
  174. .init = atahpt_init,
  175. .map_flash_region = fallback_map,
  176. .unmap_flash_region = fallback_unmap,
  177. .delay = internal_delay,
  178. },
  179. #endif
  180. #if CONFIG_ATAVIA == 1
  181. {
  182. .name = "atavia",
  183. .type = PCI,
  184. .devs.dev = ata_via,
  185. .init = atavia_init,
  186. .map_flash_region = atavia_map,
  187. .unmap_flash_region = fallback_unmap,
  188. .delay = internal_delay,
  189. },
  190. #endif
  191. #if CONFIG_ATAPROMISE == 1
  192. {
  193. .name = "atapromise",
  194. .type = PCI,
  195. .devs.dev = ata_promise,
  196. .init = atapromise_init,
  197. .map_flash_region = atapromise_map,
  198. .unmap_flash_region = fallback_unmap,
  199. .delay = internal_delay,
  200. },
  201. #endif
  202. #if CONFIG_IT8212 == 1
  203. {
  204. .name = "it8212",
  205. .type = PCI,
  206. .devs.dev = devs_it8212,
  207. .init = it8212_init,
  208. .map_flash_region = fallback_map,
  209. .unmap_flash_region = fallback_unmap,
  210. .delay = internal_delay,
  211. },
  212. #endif
  213. #if CONFIG_FT2232_SPI == 1
  214. {
  215. .name = "ft2232_spi",
  216. .type = USB,
  217. .devs.dev = devs_ft2232spi,
  218. .init = ft2232_spi_init,
  219. .map_flash_region = fallback_map,
  220. .unmap_flash_region = fallback_unmap,
  221. .delay = internal_delay,
  222. },
  223. #endif
  224. #if CONFIG_SERPROG == 1
  225. {
  226. .name = "serprog",
  227. .type = OTHER,
  228. /* FIXME */
  229. .devs.note = "All programmer devices speaking the serprog protocol\n",
  230. .init = serprog_init,
  231. .map_flash_region = serprog_map,
  232. .unmap_flash_region = fallback_unmap,
  233. .delay = serprog_delay,
  234. },
  235. #endif
  236. #if CONFIG_BUSPIRATE_SPI == 1
  237. {
  238. .name = "buspirate_spi",
  239. .type = OTHER,
  240. /* FIXME */
  241. .devs.note = "Dangerous Prototypes Bus Pirate\n",
  242. .init = buspirate_spi_init,
  243. .map_flash_region = fallback_map,
  244. .unmap_flash_region = fallback_unmap,
  245. .delay = internal_delay,
  246. },
  247. #endif
  248. #if CONFIG_DEDIPROG == 1
  249. {
  250. .name = "dediprog",
  251. .type = USB,
  252. .devs.dev = devs_dediprog,
  253. .init = dediprog_init,
  254. .map_flash_region = fallback_map,
  255. .unmap_flash_region = fallback_unmap,
  256. .delay = internal_delay,
  257. },
  258. #endif
  259. #if CONFIG_RAYER_SPI == 1
  260. {
  261. .name = "rayer_spi",
  262. .type = OTHER,
  263. /* FIXME */
  264. .devs.note = "RayeR parallel port programmer\n",
  265. .init = rayer_spi_init,
  266. .map_flash_region = fallback_map,
  267. .unmap_flash_region = fallback_unmap,
  268. .delay = internal_delay,
  269. },
  270. #endif
  271. #if CONFIG_PONY_SPI == 1
  272. {
  273. .name = "pony_spi",
  274. .type = OTHER,
  275. /* FIXME */
  276. .devs.note = "Programmers compatible with SI-Prog, serbang or AJAWe\n",
  277. .init = pony_spi_init,
  278. .map_flash_region = fallback_map,
  279. .unmap_flash_region = fallback_unmap,
  280. .delay = internal_delay,
  281. },
  282. #endif
  283. #if CONFIG_NICINTEL == 1
  284. {
  285. .name = "nicintel",
  286. .type = PCI,
  287. .devs.dev = nics_intel,
  288. .init = nicintel_init,
  289. .map_flash_region = fallback_map,
  290. .unmap_flash_region = fallback_unmap,
  291. .delay = internal_delay,
  292. },
  293. #endif
  294. #if CONFIG_NICINTEL_SPI == 1
  295. {
  296. .name = "nicintel_spi",
  297. .type = PCI,
  298. .devs.dev = nics_intel_spi,
  299. .init = nicintel_spi_init,
  300. .map_flash_region = fallback_map,
  301. .unmap_flash_region = fallback_unmap,
  302. .delay = internal_delay,
  303. },
  304. #endif
  305. #if CONFIG_NICINTEL_EEPROM == 1
  306. {
  307. .name = "nicintel_eeprom",
  308. .type = PCI,
  309. .devs.dev = nics_intel_ee,
  310. .init = nicintel_ee_init,
  311. .map_flash_region = fallback_map,
  312. .unmap_flash_region = fallback_unmap,
  313. .delay = internal_delay,
  314. },
  315. #endif
  316. #if CONFIG_OGP_SPI == 1
  317. {
  318. .name = "ogp_spi",
  319. .type = PCI,
  320. .devs.dev = ogp_spi,
  321. .init = ogp_spi_init,
  322. .map_flash_region = fallback_map,
  323. .unmap_flash_region = fallback_unmap,
  324. .delay = internal_delay,
  325. },
  326. #endif
  327. #if CONFIG_SATAMV == 1
  328. {
  329. .name = "satamv",
  330. .type = PCI,
  331. .devs.dev = satas_mv,
  332. .init = satamv_init,
  333. .map_flash_region = fallback_map,
  334. .unmap_flash_region = fallback_unmap,
  335. .delay = internal_delay,
  336. },
  337. #endif
  338. #if CONFIG_LINUX_SPI == 1
  339. {
  340. .name = "linux_spi",
  341. .type = OTHER,
  342. .devs.note = "Device files /dev/spidev*.*\n",
  343. .init = linux_spi_init,
  344. .map_flash_region = fallback_map,
  345. .unmap_flash_region = fallback_unmap,
  346. .delay = internal_delay,
  347. },
  348. #endif
  349. #if CONFIG_USBBLASTER_SPI == 1
  350. {
  351. .name = "usbblaster_spi",
  352. .type = USB,
  353. .devs.dev = devs_usbblasterspi,
  354. .init = usbblaster_spi_init,
  355. .map_flash_region = fallback_map,
  356. .unmap_flash_region = fallback_unmap,
  357. .delay = internal_delay,
  358. },
  359. #endif
  360. #if CONFIG_MSTARDDC_SPI == 1
  361. {
  362. .name = "mstarddc_spi",
  363. .type = OTHER,
  364. .devs.note = "MSTAR DDC devices addressable via /dev/i2c-* on Linux.\n",
  365. .init = mstarddc_spi_init,
  366. .map_flash_region = fallback_map,
  367. .unmap_flash_region = fallback_unmap,
  368. .delay = internal_delay,
  369. },
  370. #endif
  371. #if CONFIG_PICKIT2_SPI == 1
  372. {
  373. .name = "pickit2_spi",
  374. .type = USB,
  375. .devs.dev = devs_pickit2_spi,
  376. .init = pickit2_spi_init,
  377. .map_flash_region = fallback_map,
  378. .unmap_flash_region = fallback_unmap,
  379. .delay = internal_delay,
  380. },
  381. #endif
  382. #if CONFIG_CH341A_SPI == 1
  383. {
  384. .name = "ch341a_spi",
  385. .type = USB,
  386. .devs.dev = devs_ch341a_spi,
  387. .init = ch341a_spi_init,
  388. .map_flash_region = fallback_map,
  389. .unmap_flash_region = fallback_unmap,
  390. .delay = ch341a_spi_delay,
  391. },
  392. #endif
  393. {0}, /* This entry corresponds to PROGRAMMER_INVALID. */
  394. };
  395. #define SHUTDOWN_MAXFN 32
  396. static int shutdown_fn_count = 0;
  397. struct shutdown_func_data {
  398. int (*func) (void *data);
  399. void *data;
  400. } static shutdown_fn[SHUTDOWN_MAXFN];
  401. /* Initialize to 0 to make sure nobody registers a shutdown function before
  402. * programmer init.
  403. */
  404. static int may_register_shutdown = 0;
  405. /* Did we change something or was every erase/write skipped (if any)? */
  406. static bool all_skipped = true;
  407. static int check_block_eraser(const struct flashctx *flash, int k, int log);
  408. int shutdown_free(void *data)
  409. {
  410. free(data);
  411. return 0;
  412. }
  413. /* Register a function to be executed on programmer shutdown.
  414. * The advantage over atexit() is that you can supply a void pointer which will
  415. * be used as parameter to the registered function upon programmer shutdown.
  416. * This pointer can point to arbitrary data used by said function, e.g. undo
  417. * information for GPIO settings etc. If unneeded, set data=NULL.
  418. * Please note that the first (void *data) belongs to the function signature of
  419. * the function passed as first parameter.
  420. */
  421. int register_shutdown(int (*function) (void *data), void *data)
  422. {
  423. if (shutdown_fn_count >= SHUTDOWN_MAXFN) {
  424. msg_perr("Tried to register more than %i shutdown functions.\n",
  425. SHUTDOWN_MAXFN);
  426. return 1;
  427. }
  428. if (!may_register_shutdown) {
  429. msg_perr("Tried to register a shutdown function before "
  430. "programmer init.\n");
  431. return 1;
  432. }
  433. shutdown_fn[shutdown_fn_count].func = function;
  434. shutdown_fn[shutdown_fn_count].data = data;
  435. shutdown_fn_count++;
  436. return 0;
  437. }
  438. int programmer_init(enum programmer prog, const char *param)
  439. {
  440. int ret;
  441. if (prog >= PROGRAMMER_INVALID) {
  442. msg_perr("Invalid programmer specified!\n");
  443. return -1;
  444. }
  445. programmer = prog;
  446. /* Initialize all programmer specific data. */
  447. /* Default to unlimited decode sizes. */
  448. max_rom_decode = (const struct decode_sizes) {
  449. .parallel = 0xffffffff,
  450. .lpc = 0xffffffff,
  451. .fwh = 0xffffffff,
  452. .spi = 0xffffffff,
  453. };
  454. /* Default to top aligned flash at 4 GB. */
  455. flashbase = 0;
  456. /* Registering shutdown functions is now allowed. */
  457. may_register_shutdown = 1;
  458. /* Default to allowing writes. Broken programmers set this to 0. */
  459. programmer_may_write = 1;
  460. programmer_param = param;
  461. msg_pdbg("Initializing %s programmer\n", programmer_table[programmer].name);
  462. ret = programmer_table[programmer].init();
  463. if (programmer_param && strlen(programmer_param)) {
  464. if (ret != 0) {
  465. /* It is quite possible that any unhandled programmer parameter would have been valid,
  466. * but an error in actual programmer init happened before the parameter was evaluated.
  467. */
  468. msg_pwarn("Unhandled programmer parameters (possibly due to another failure): %s\n",
  469. programmer_param);
  470. } else {
  471. /* Actual programmer init was successful, but the user specified an invalid or unusable
  472. * (for the current programmer configuration) parameter.
  473. */
  474. msg_perr("Unhandled programmer parameters: %s\n", programmer_param);
  475. msg_perr("Aborting.\n");
  476. ret = ERROR_FATAL;
  477. }
  478. }
  479. return ret;
  480. }
  481. /** Calls registered shutdown functions and resets internal programmer-related variables.
  482. * Calling it is safe even without previous initialization, but further interactions with programmer support
  483. * require a call to programmer_init() (afterwards).
  484. *
  485. * @return The OR-ed result values of all shutdown functions (i.e. 0 on success). */
  486. int programmer_shutdown(void)
  487. {
  488. int ret = 0;
  489. /* Registering shutdown functions is no longer allowed. */
  490. may_register_shutdown = 0;
  491. while (shutdown_fn_count > 0) {
  492. int i = --shutdown_fn_count;
  493. ret |= shutdown_fn[i].func(shutdown_fn[i].data);
  494. }
  495. programmer_param = NULL;
  496. registered_master_count = 0;
  497. return ret;
  498. }
  499. void *programmer_map_flash_region(const char *descr, uintptr_t phys_addr, size_t len)
  500. {
  501. void *ret = programmer_table[programmer].map_flash_region(descr, phys_addr, len);
  502. msg_gspew("%s: mapping %s from 0x%0*" PRIxPTR " to 0x%0*" PRIxPTR "\n",
  503. __func__, descr, PRIxPTR_WIDTH, phys_addr, PRIxPTR_WIDTH, (uintptr_t) ret);
  504. return ret;
  505. }
  506. void programmer_unmap_flash_region(void *virt_addr, size_t len)
  507. {
  508. programmer_table[programmer].unmap_flash_region(virt_addr, len);
  509. msg_gspew("%s: unmapped 0x%0*" PRIxPTR "\n", __func__, PRIxPTR_WIDTH, (uintptr_t)virt_addr);
  510. }
  511. void chip_writeb(const struct flashctx *flash, uint8_t val, chipaddr addr)
  512. {
  513. flash->mst->par.chip_writeb(flash, val, addr);
  514. }
  515. void chip_writew(const struct flashctx *flash, uint16_t val, chipaddr addr)
  516. {
  517. flash->mst->par.chip_writew(flash, val, addr);
  518. }
  519. void chip_writel(const struct flashctx *flash, uint32_t val, chipaddr addr)
  520. {
  521. flash->mst->par.chip_writel(flash, val, addr);
  522. }
  523. void chip_writen(const struct flashctx *flash, const uint8_t *buf, chipaddr addr, size_t len)
  524. {
  525. flash->mst->par.chip_writen(flash, buf, addr, len);
  526. }
  527. uint8_t chip_readb(const struct flashctx *flash, const chipaddr addr)
  528. {
  529. return flash->mst->par.chip_readb(flash, addr);
  530. }
  531. uint16_t chip_readw(const struct flashctx *flash, const chipaddr addr)
  532. {
  533. return flash->mst->par.chip_readw(flash, addr);
  534. }
  535. uint32_t chip_readl(const struct flashctx *flash, const chipaddr addr)
  536. {
  537. return flash->mst->par.chip_readl(flash, addr);
  538. }
  539. void chip_readn(const struct flashctx *flash, uint8_t *buf, chipaddr addr,
  540. size_t len)
  541. {
  542. flash->mst->par.chip_readn(flash, buf, addr, len);
  543. }
  544. void programmer_delay(unsigned int usecs)
  545. {
  546. if (usecs > 0)
  547. programmer_table[programmer].delay(usecs);
  548. }
  549. int read_memmapped(struct flashctx *flash, uint8_t *buf, unsigned int start,
  550. int unsigned len)
  551. {
  552. chip_readn(flash, buf, flash->virtual_memory + start, len);
  553. return 0;
  554. }
  555. /* This is a somewhat hacked function similar in some ways to strtok().
  556. * It will look for needle with a subsequent '=' in haystack, return a copy of
  557. * needle and remove everything from the first occurrence of needle to the next
  558. * delimiter from haystack.
  559. */
  560. char *extract_param(const char *const *haystack, const char *needle, const char *delim)
  561. {
  562. char *param_pos, *opt_pos, *rest;
  563. char *opt = NULL;
  564. int optlen;
  565. int needlelen;
  566. needlelen = strlen(needle);
  567. if (!needlelen) {
  568. msg_gerr("%s: empty needle! Please report a bug at "
  569. "flashrom@flashrom.org\n", __func__);
  570. return NULL;
  571. }
  572. /* No programmer parameters given. */
  573. if (*haystack == NULL)
  574. return NULL;
  575. param_pos = strstr(*haystack, needle);
  576. do {
  577. if (!param_pos)
  578. return NULL;
  579. /* Needle followed by '='? */
  580. if (param_pos[needlelen] == '=') {
  581. /* Beginning of the string? */
  582. if (param_pos == *haystack)
  583. break;
  584. /* After a delimiter? */
  585. if (strchr(delim, *(param_pos - 1)))
  586. break;
  587. }
  588. /* Continue searching. */
  589. param_pos++;
  590. param_pos = strstr(param_pos, needle);
  591. } while (1);
  592. if (param_pos) {
  593. /* Get the string after needle and '='. */
  594. opt_pos = param_pos + needlelen + 1;
  595. optlen = strcspn(opt_pos, delim);
  596. /* Return an empty string if the parameter was empty. */
  597. opt = malloc(optlen + 1);
  598. if (!opt) {
  599. msg_gerr("Out of memory!\n");
  600. exit(1);
  601. }
  602. strncpy(opt, opt_pos, optlen);
  603. opt[optlen] = '\0';
  604. rest = opt_pos + optlen;
  605. /* Skip all delimiters after the current parameter. */
  606. rest += strspn(rest, delim);
  607. memmove(param_pos, rest, strlen(rest) + 1);
  608. /* We could shrink haystack, but the effort is not worth it. */
  609. }
  610. return opt;
  611. }
  612. char *extract_programmer_param(const char *param_name)
  613. {
  614. return extract_param(&programmer_param, param_name, ",");
  615. }
  616. /* Returns the number of well-defined erasers for a chip. */
  617. static unsigned int count_usable_erasers(const struct flashctx *flash)
  618. {
  619. unsigned int usable_erasefunctions = 0;
  620. int k;
  621. for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
  622. if (!check_block_eraser(flash, k, 0))
  623. usable_erasefunctions++;
  624. }
  625. return usable_erasefunctions;
  626. }
  627. static int compare_range(const uint8_t *wantbuf, const uint8_t *havebuf, unsigned int start, unsigned int len)
  628. {
  629. int ret = 0, failcount = 0;
  630. unsigned int i;
  631. for (i = 0; i < len; i++) {
  632. if (wantbuf[i] != havebuf[i]) {
  633. /* Only print the first failure. */
  634. if (!failcount++)
  635. msg_cerr("FAILED at 0x%08x! Expected=0x%02x, Found=0x%02x,",
  636. start + i, wantbuf[i], havebuf[i]);
  637. }
  638. }
  639. if (failcount) {
  640. msg_cerr(" failed byte count from 0x%08x-0x%08x: 0x%x\n",
  641. start, start + len - 1, failcount);
  642. ret = -1;
  643. }
  644. return ret;
  645. }
  646. /* start is an offset to the base address of the flash chip */
  647. int check_erased_range(struct flashctx *flash, unsigned int start,
  648. unsigned int len)
  649. {
  650. int ret;
  651. uint8_t *cmpbuf = malloc(len);
  652. if (!cmpbuf) {
  653. msg_gerr("Could not allocate memory!\n");
  654. exit(1);
  655. }
  656. memset(cmpbuf, 0xff, len);
  657. ret = verify_range(flash, cmpbuf, start, len);
  658. free(cmpbuf);
  659. return ret;
  660. }
  661. /*
  662. * @cmpbuf buffer to compare against, cmpbuf[0] is expected to match the
  663. * flash content at location start
  664. * @start offset to the base address of the flash chip
  665. * @len length of the verified area
  666. * @return 0 for success, -1 for failure
  667. */
  668. int verify_range(struct flashctx *flash, const uint8_t *cmpbuf, unsigned int start, unsigned int len)
  669. {
  670. if (!len)
  671. return -1;
  672. if (!flash->chip->read) {
  673. msg_cerr("ERROR: flashrom has no read function for this flash chip.\n");
  674. return -1;
  675. }
  676. uint8_t *readbuf = malloc(len);
  677. if (!readbuf) {
  678. msg_gerr("Could not allocate memory!\n");
  679. return -1;
  680. }
  681. int ret = 0;
  682. if (start + len > flash->chip->total_size * 1024) {
  683. msg_gerr("Error: %s called with start 0x%x + len 0x%x >"
  684. " total_size 0x%x\n", __func__, start, len,
  685. flash->chip->total_size * 1024);
  686. ret = -1;
  687. goto out_free;
  688. }
  689. ret = flash->chip->read(flash, readbuf, start, len);
  690. if (ret) {
  691. msg_gerr("Verification impossible because read failed "
  692. "at 0x%x (len 0x%x)\n", start, len);
  693. ret = -1;
  694. goto out_free;
  695. }
  696. ret = compare_range(cmpbuf, readbuf, start, len);
  697. out_free:
  698. free(readbuf);
  699. return ret;
  700. }
  701. /* Helper function for need_erase() that focuses on granularities of gran bytes. */
  702. static int need_erase_gran_bytes(const uint8_t *have, const uint8_t *want, unsigned int len, unsigned int gran)
  703. {
  704. unsigned int i, j, limit;
  705. for (j = 0; j < len / gran; j++) {
  706. limit = min (gran, len - j * gran);
  707. /* Are 'have' and 'want' identical? */
  708. if (!memcmp(have + j * gran, want + j * gran, limit))
  709. continue;
  710. /* have needs to be in erased state. */
  711. for (i = 0; i < limit; i++)
  712. if (have[j * gran + i] != 0xff)
  713. return 1;
  714. }
  715. return 0;
  716. }
  717. /*
  718. * Check if the buffer @have can be programmed to the content of @want without
  719. * erasing. This is only possible if all chunks of size @gran are either kept
  720. * as-is or changed from an all-ones state to any other state.
  721. *
  722. * Warning: This function assumes that @have and @want point to naturally
  723. * aligned regions.
  724. *
  725. * @have buffer with current content
  726. * @want buffer with desired content
  727. * @len length of the checked area
  728. * @gran write granularity (enum, not count)
  729. * @return 0 if no erase is needed, 1 otherwise
  730. */
  731. int need_erase(const uint8_t *have, const uint8_t *want, unsigned int len, enum write_granularity gran)
  732. {
  733. int result = 0;
  734. unsigned int i;
  735. switch (gran) {
  736. case write_gran_1bit:
  737. for (i = 0; i < len; i++)
  738. if ((have[i] & want[i]) != want[i]) {
  739. result = 1;
  740. break;
  741. }
  742. break;
  743. case write_gran_1byte:
  744. for (i = 0; i < len; i++)
  745. if ((have[i] != want[i]) && (have[i] != 0xff)) {
  746. result = 1;
  747. break;
  748. }
  749. break;
  750. case write_gran_128bytes:
  751. result = need_erase_gran_bytes(have, want, len, 128);
  752. break;
  753. case write_gran_256bytes:
  754. result = need_erase_gran_bytes(have, want, len, 256);
  755. break;
  756. case write_gran_264bytes:
  757. result = need_erase_gran_bytes(have, want, len, 264);
  758. break;
  759. case write_gran_512bytes:
  760. result = need_erase_gran_bytes(have, want, len, 512);
  761. break;
  762. case write_gran_528bytes:
  763. result = need_erase_gran_bytes(have, want, len, 528);
  764. break;
  765. case write_gran_1024bytes:
  766. result = need_erase_gran_bytes(have, want, len, 1024);
  767. break;
  768. case write_gran_1056bytes:
  769. result = need_erase_gran_bytes(have, want, len, 1056);
  770. break;
  771. case write_gran_1byte_implicit_erase:
  772. /* Do not erase, handle content changes from anything->0xff by writing 0xff. */
  773. result = 0;
  774. break;
  775. default:
  776. msg_cerr("%s: Unsupported granularity! Please report a bug at "
  777. "flashrom@flashrom.org\n", __func__);
  778. }
  779. return result;
  780. }
  781. /**
  782. * Check if the buffer @have needs to be programmed to get the content of @want.
  783. * If yes, return 1 and fill in first_start with the start address of the
  784. * write operation and first_len with the length of the first to-be-written
  785. * chunk. If not, return 0 and leave first_start and first_len undefined.
  786. *
  787. * Warning: This function assumes that @have and @want point to naturally
  788. * aligned regions.
  789. *
  790. * @have buffer with current content
  791. * @want buffer with desired content
  792. * @len length of the checked area
  793. * @gran write granularity (enum, not count)
  794. * @first_start offset of the first byte which needs to be written (passed in
  795. * value is increased by the offset of the first needed write
  796. * relative to have/want or unchanged if no write is needed)
  797. * @return length of the first contiguous area which needs to be written
  798. * 0 if no write is needed
  799. *
  800. * FIXME: This function needs a parameter which tells it about coalescing
  801. * in relation to the max write length of the programmer and the max write
  802. * length of the chip.
  803. */
  804. static unsigned int get_next_write(const uint8_t *have, const uint8_t *want, unsigned int len,
  805. unsigned int *first_start,
  806. enum write_granularity gran)
  807. {
  808. int need_write = 0;
  809. unsigned int rel_start = 0, first_len = 0;
  810. unsigned int i, limit, stride;
  811. switch (gran) {
  812. case write_gran_1bit:
  813. case write_gran_1byte:
  814. case write_gran_1byte_implicit_erase:
  815. stride = 1;
  816. break;
  817. case write_gran_128bytes:
  818. stride = 128;
  819. break;
  820. case write_gran_256bytes:
  821. stride = 256;
  822. break;
  823. case write_gran_264bytes:
  824. stride = 264;
  825. break;
  826. case write_gran_512bytes:
  827. stride = 512;
  828. break;
  829. case write_gran_528bytes:
  830. stride = 528;
  831. break;
  832. case write_gran_1024bytes:
  833. stride = 1024;
  834. break;
  835. case write_gran_1056bytes:
  836. stride = 1056;
  837. break;
  838. default:
  839. msg_cerr("%s: Unsupported granularity! Please report a bug at "
  840. "flashrom@flashrom.org\n", __func__);
  841. /* Claim that no write was needed. A write with unknown
  842. * granularity is too dangerous to try.
  843. */
  844. return 0;
  845. }
  846. for (i = 0; i < len / stride; i++) {
  847. limit = min(stride, len - i * stride);
  848. /* Are 'have' and 'want' identical? */
  849. if (memcmp(have + i * stride, want + i * stride, limit)) {
  850. if (!need_write) {
  851. /* First location where have and want differ. */
  852. need_write = 1;
  853. rel_start = i * stride;
  854. }
  855. } else {
  856. if (need_write) {
  857. /* First location where have and want
  858. * do not differ anymore.
  859. */
  860. break;
  861. }
  862. }
  863. }
  864. if (need_write)
  865. first_len = min(i * stride - rel_start, len);
  866. *first_start += rel_start;
  867. return first_len;
  868. }
  869. /* This function generates various test patterns useful for testing controller
  870. * and chip communication as well as chip behaviour.
  871. *
  872. * If a byte can be written multiple times, each time keeping 0-bits at 0
  873. * and changing 1-bits to 0 if the new value for that bit is 0, the effect
  874. * is essentially an AND operation. That's also the reason why this function
  875. * provides the result of AND between various patterns.
  876. *
  877. * Below is a list of patterns (and their block length).
  878. * Pattern 0 is 05 15 25 35 45 55 65 75 85 95 a5 b5 c5 d5 e5 f5 (16 Bytes)
  879. * Pattern 1 is 0a 1a 2a 3a 4a 5a 6a 7a 8a 9a aa ba ca da ea fa (16 Bytes)
  880. * Pattern 2 is 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f (16 Bytes)
  881. * Pattern 3 is a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af (16 Bytes)
  882. * Pattern 4 is 00 10 20 30 40 50 60 70 80 90 a0 b0 c0 d0 e0 f0 (16 Bytes)
  883. * Pattern 5 is 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f (16 Bytes)
  884. * Pattern 6 is 00 (1 Byte)
  885. * Pattern 7 is ff (1 Byte)
  886. * Patterns 0-7 have a big-endian block number in the last 2 bytes of each 256
  887. * byte block.
  888. *
  889. * Pattern 8 is 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11... (256 B)
  890. * Pattern 9 is ff fe fd fc fb fa f9 f8 f7 f6 f5 f4 f3 f2 f1 f0 ef ee... (256 B)
  891. * Pattern 10 is 00 00 00 01 00 02 00 03 00 04... (128 kB big-endian counter)
  892. * Pattern 11 is ff ff ff fe ff fd ff fc ff fb... (128 kB big-endian downwards)
  893. * Pattern 12 is 00 (1 Byte)
  894. * Pattern 13 is ff (1 Byte)
  895. * Patterns 8-13 have no block number.
  896. *
  897. * Patterns 0-3 are created to detect and efficiently diagnose communication
  898. * slips like missed bits or bytes and their repetitive nature gives good visual
  899. * cues to the person inspecting the results. In addition, the following holds:
  900. * AND Pattern 0/1 == Pattern 4
  901. * AND Pattern 2/3 == Pattern 5
  902. * AND Pattern 0/1/2/3 == AND Pattern 4/5 == Pattern 6
  903. * A weakness of pattern 0-5 is the inability to detect swaps/copies between
  904. * any two 16-byte blocks except for the last 16-byte block in a 256-byte bloc.
  905. * They work perfectly for detecting any swaps/aliasing of blocks >= 256 bytes.
  906. * 0x5 and 0xa were picked because they are 0101 and 1010 binary.
  907. * Patterns 8-9 are best for detecting swaps/aliasing of blocks < 256 bytes.
  908. * Besides that, they provide for bit testing of the last two bytes of every
  909. * 256 byte block which contains the block number for patterns 0-6.
  910. * Patterns 10-11 are special purpose for detecting subblock aliasing with
  911. * block sizes >256 bytes (some Dataflash chips etc.)
  912. * AND Pattern 8/9 == Pattern 12
  913. * AND Pattern 10/11 == Pattern 12
  914. * Pattern 13 is the completely erased state.
  915. * None of the patterns can detect aliasing at boundaries which are a multiple
  916. * of 16 MBytes (but such chips do not exist anyway for Parallel/LPC/FWH/SPI).
  917. */
  918. int generate_testpattern(uint8_t *buf, uint32_t size, int variant)
  919. {
  920. int i;
  921. if (!buf) {
  922. msg_gerr("Invalid buffer!\n");
  923. return 1;
  924. }
  925. switch (variant) {
  926. case 0:
  927. for (i = 0; i < size; i++)
  928. buf[i] = (i & 0xf) << 4 | 0x5;
  929. break;
  930. case 1:
  931. for (i = 0; i < size; i++)
  932. buf[i] = (i & 0xf) << 4 | 0xa;
  933. break;
  934. case 2:
  935. for (i = 0; i < size; i++)
  936. buf[i] = 0x50 | (i & 0xf);
  937. break;
  938. case 3:
  939. for (i = 0; i < size; i++)
  940. buf[i] = 0xa0 | (i & 0xf);
  941. break;
  942. case 4:
  943. for (i = 0; i < size; i++)
  944. buf[i] = (i & 0xf) << 4;
  945. break;
  946. case 5:
  947. for (i = 0; i < size; i++)
  948. buf[i] = i & 0xf;
  949. break;
  950. case 6:
  951. memset(buf, 0x00, size);
  952. break;
  953. case 7:
  954. memset(buf, 0xff, size);
  955. break;
  956. case 8:
  957. for (i = 0; i < size; i++)
  958. buf[i] = i & 0xff;
  959. break;
  960. case 9:
  961. for (i = 0; i < size; i++)
  962. buf[i] = ~(i & 0xff);
  963. break;
  964. case 10:
  965. for (i = 0; i < size % 2; i++) {
  966. buf[i * 2] = (i >> 8) & 0xff;
  967. buf[i * 2 + 1] = i & 0xff;
  968. }
  969. if (size & 0x1)
  970. buf[i * 2] = (i >> 8) & 0xff;
  971. break;
  972. case 11:
  973. for (i = 0; i < size % 2; i++) {
  974. buf[i * 2] = ~((i >> 8) & 0xff);
  975. buf[i * 2 + 1] = ~(i & 0xff);
  976. }
  977. if (size & 0x1)
  978. buf[i * 2] = ~((i >> 8) & 0xff);
  979. break;
  980. case 12:
  981. memset(buf, 0x00, size);
  982. break;
  983. case 13:
  984. memset(buf, 0xff, size);
  985. break;
  986. }
  987. if ((variant >= 0) && (variant <= 7)) {
  988. /* Write block number in the last two bytes of each 256-byte
  989. * block, big endian for easier reading of the hexdump.
  990. * Note that this wraps around for chips larger than 2^24 bytes
  991. * (16 MB).
  992. */
  993. for (i = 0; i < size / 256; i++) {
  994. buf[i * 256 + 254] = (i >> 8) & 0xff;
  995. buf[i * 256 + 255] = i & 0xff;
  996. }
  997. }
  998. return 0;
  999. }
  1000. /* Returns the number of busses commonly supported by the current programmer and flash chip where the latter
  1001. * can not be completely accessed due to size/address limits of the programmer. */
  1002. unsigned int count_max_decode_exceedings(const struct flashctx *flash)
  1003. {
  1004. unsigned int limitexceeded = 0;
  1005. uint32_t size = flash->chip->total_size * 1024;
  1006. enum chipbustype buses = flash->mst->buses_supported & flash->chip->bustype;
  1007. if ((buses & BUS_PARALLEL) && (max_rom_decode.parallel < size)) {
  1008. limitexceeded++;
  1009. msg_pdbg("Chip size %u kB is bigger than supported "
  1010. "size %u kB of chipset/board/programmer "
  1011. "for %s interface, "
  1012. "probe/read/erase/write may fail. ", size / 1024,
  1013. max_rom_decode.parallel / 1024, "Parallel");
  1014. }
  1015. if ((buses & BUS_LPC) && (max_rom_decode.lpc < size)) {
  1016. limitexceeded++;
  1017. msg_pdbg("Chip size %u kB is bigger than supported "
  1018. "size %u kB of chipset/board/programmer "
  1019. "for %s interface, "
  1020. "probe/read/erase/write may fail. ", size / 1024,
  1021. max_rom_decode.lpc / 1024, "LPC");
  1022. }
  1023. if ((buses & BUS_FWH) && (max_rom_decode.fwh < size)) {
  1024. limitexceeded++;
  1025. msg_pdbg("Chip size %u kB is bigger than supported "
  1026. "size %u kB of chipset/board/programmer "
  1027. "for %s interface, "
  1028. "probe/read/erase/write may fail. ", size / 1024,
  1029. max_rom_decode.fwh / 1024, "FWH");
  1030. }
  1031. if ((buses & BUS_SPI) && (max_rom_decode.spi < size)) {
  1032. limitexceeded++;
  1033. msg_pdbg("Chip size %u kB is bigger than supported "
  1034. "size %u kB of chipset/board/programmer "
  1035. "for %s interface, "
  1036. "probe/read/erase/write may fail. ", size / 1024,
  1037. max_rom_decode.spi / 1024, "SPI");
  1038. }
  1039. return limitexceeded;
  1040. }
  1041. void unmap_flash(struct flashctx *flash)
  1042. {
  1043. if (flash->virtual_registers != (chipaddr)ERROR_PTR) {
  1044. programmer_unmap_flash_region((void *)flash->virtual_registers, flash->chip->total_size * 1024);
  1045. flash->physical_registers = 0;
  1046. flash->virtual_registers = (chipaddr)ERROR_PTR;
  1047. }
  1048. if (flash->virtual_memory != (chipaddr)ERROR_PTR) {
  1049. programmer_unmap_flash_region((void *)flash->virtual_memory, flash->chip->total_size * 1024);
  1050. flash->physical_memory = 0;
  1051. flash->virtual_memory = (chipaddr)ERROR_PTR;
  1052. }
  1053. }
  1054. int map_flash(struct flashctx *flash)
  1055. {
  1056. /* Init pointers to the fail-safe state to distinguish them later from legit values. */
  1057. flash->virtual_memory = (chipaddr)ERROR_PTR;
  1058. flash->virtual_registers = (chipaddr)ERROR_PTR;
  1059. /* FIXME: This avoids mapping (and unmapping) of flash chip definitions with size 0.
  1060. * These are used for various probing-related hacks that would not map successfully anyway and should be
  1061. * removed ASAP. */
  1062. if (flash->chip->total_size == 0)
  1063. return 0;
  1064. const chipsize_t size = flash->chip->total_size * 1024;
  1065. uintptr_t base = flashbase ? flashbase : (0xffffffff - size + 1);
  1066. void *addr = programmer_map_flash_region(flash->chip->name, base, size);
  1067. if (addr == ERROR_PTR) {
  1068. msg_perr("Could not map flash chip %s at 0x%0*" PRIxPTR ".\n",
  1069. flash->chip->name, PRIxPTR_WIDTH, base);
  1070. return 1;
  1071. }
  1072. flash->physical_memory = base;
  1073. flash->virtual_memory = (chipaddr)addr;
  1074. /* FIXME: Special function registers normally live 4 MByte below flash space, but it might be somewhere
  1075. * completely different on some chips and programmers, or not mappable at all.
  1076. * Ignore these problems for now and always report success. */
  1077. if (flash->chip->feature_bits & FEATURE_REGISTERMAP) {
  1078. base = 0xffffffff - size - 0x400000 + 1;
  1079. addr = programmer_map_flash_region("flash chip registers", base, size);
  1080. if (addr == ERROR_PTR) {
  1081. msg_pdbg2("Could not map flash chip registers %s at 0x%0*" PRIxPTR ".\n",
  1082. flash->chip->name, PRIxPTR_WIDTH, base);
  1083. return 0;
  1084. }
  1085. flash->physical_registers = base;
  1086. flash->virtual_registers = (chipaddr)addr;
  1087. }
  1088. return 0;
  1089. }
  1090. int probe_flash(struct registered_master *mst, int startchip, struct flashctx *flash, int force)
  1091. {
  1092. const struct flashchip *chip;
  1093. enum chipbustype buses_common;
  1094. char *tmp;
  1095. for (chip = flashchips + startchip; chip && chip->name; chip++) {
  1096. if (chip_to_probe && strcmp(chip->name, chip_to_probe) != 0)
  1097. continue;
  1098. buses_common = mst->buses_supported & chip->bustype;
  1099. if (!buses_common)
  1100. continue;
  1101. msg_gdbg("Probing for %s %s, %d kB: ", chip->vendor, chip->name, chip->total_size);
  1102. if (!chip->probe && !force) {
  1103. msg_gdbg("failed! flashrom has no probe function for this flash chip.\n");
  1104. continue;
  1105. }
  1106. /* Start filling in the dynamic data. */
  1107. flash->chip = calloc(1, sizeof(struct flashchip));
  1108. if (!flash->chip) {
  1109. msg_gerr("Out of memory!\n");
  1110. exit(1);
  1111. }
  1112. memcpy(flash->chip, chip, sizeof(struct flashchip));
  1113. flash->mst = mst;
  1114. if (map_flash(flash) != 0)
  1115. return -1;
  1116. /* We handle a forced match like a real match, we just avoid probing. Note that probe_flash()
  1117. * is only called with force=1 after normal probing failed.
  1118. */
  1119. if (force)
  1120. break;
  1121. if (flash->chip->probe(flash) != 1)
  1122. goto notfound;
  1123. /* If this is the first chip found, accept it.
  1124. * If this is not the first chip found, accept it only if it is
  1125. * a non-generic match. SFDP and CFI are generic matches.
  1126. * startchip==0 means this call to probe_flash() is the first
  1127. * one for this programmer interface (master) and thus no other chip has
  1128. * been found on this interface.
  1129. */
  1130. if (startchip == 0 && flash->chip->model_id == SFDP_DEVICE_ID) {
  1131. msg_cinfo("===\n"
  1132. "SFDP has autodetected a flash chip which is "
  1133. "not natively supported by flashrom yet.\n");
  1134. if (count_usable_erasers(flash) == 0)
  1135. msg_cinfo("The standard operations read and "
  1136. "verify should work, but to support "
  1137. "erase, write and all other "
  1138. "possible features");
  1139. else
  1140. msg_cinfo("All standard operations (read, "
  1141. "verify, erase and write) should "
  1142. "work, but to support all possible "
  1143. "features");
  1144. msg_cinfo(" we need to add them manually.\n"
  1145. "You can help us by mailing us the output of the following command to "
  1146. "flashrom@flashrom.org:\n"
  1147. "'flashrom -VV [plus the -p/--programmer parameter]'\n"
  1148. "Thanks for your help!\n"
  1149. "===\n");
  1150. }
  1151. /* First flash chip detected on this bus. */
  1152. if (startchip == 0)
  1153. break;
  1154. /* Not the first flash chip detected on this bus, but not a generic match either. */
  1155. if ((flash->chip->model_id != GENERIC_DEVICE_ID) && (flash->chip->model_id != SFDP_DEVICE_ID))
  1156. break;
  1157. /* Not the first flash chip detected on this bus, and it's just a generic match. Ignore it. */
  1158. notfound:
  1159. unmap_flash(flash);
  1160. free(flash->chip);
  1161. flash->chip = NULL;
  1162. }
  1163. if (!flash->chip)
  1164. return -1;
  1165. tmp = flashbuses_to_text(flash->chip->bustype);
  1166. msg_cinfo("%s %s flash chip \"%s\" (%d kB, %s) ", force ? "Assuming" : "Found",
  1167. flash->chip->vendor, flash->chip->name, flash->chip->total_size, tmp);
  1168. free(tmp);
  1169. #if CONFIG_INTERNAL == 1
  1170. if (programmer_table[programmer].map_flash_region == physmap)
  1171. msg_cinfo("mapped at physical address 0x%0*" PRIxPTR ".\n",
  1172. PRIxPTR_WIDTH, flash->physical_memory);
  1173. else
  1174. #endif
  1175. msg_cinfo("on %s.\n", programmer_table[programmer].name);
  1176. /* Flash registers may more likely not be mapped if the chip was forced.
  1177. * Lock info may be stored in registers, so avoid lock info printing. */
  1178. if (!force)
  1179. if (flash->chip->printlock)
  1180. flash->chip->printlock(flash);
  1181. /* Get out of the way for later runs. */
  1182. unmap_flash(flash);
  1183. /* Return position of matching chip. */
  1184. return chip - flashchips;
  1185. }
  1186. int read_buf_from_file(unsigned char *buf, unsigned long size,
  1187. const char *filename)
  1188. {
  1189. #ifdef __LIBPAYLOAD__
  1190. msg_gerr("Error: No file I/O support in libpayload\n");
  1191. return 1;
  1192. #else
  1193. int ret = 0;
  1194. FILE *image;
  1195. if ((image = fopen(filename, "rb")) == NULL) {
  1196. msg_gerr("Error: opening file \"%s\" failed: %s\n", filename, strerror(errno));
  1197. return 1;
  1198. }
  1199. struct stat image_stat;
  1200. if (fstat(fileno(image), &image_stat) != 0) {
  1201. msg_gerr("Error: getting metadata of file \"%s\" failed: %s\n", filename, strerror(errno));
  1202. ret = 1;
  1203. goto out;
  1204. }
  1205. if (image_stat.st_size != size) {
  1206. msg_gerr("Error: Image size (%jd B) doesn't match the flash chip's size (%lu B)!\n",
  1207. (intmax_t)image_stat.st_size, size);
  1208. ret = 1;
  1209. goto out;
  1210. }
  1211. unsigned long numbytes = fread(buf, 1, size, image);
  1212. if (numbytes != size) {
  1213. msg_gerr("Error: Failed to read complete file. Got %ld bytes, "
  1214. "wanted %ld!\n", numbytes, size);
  1215. ret = 1;
  1216. }
  1217. out:
  1218. (void)fclose(image);
  1219. return ret;
  1220. #endif
  1221. }
  1222. int write_buf_to_file(const unsigned char *buf, unsigned long size, const char *filename)
  1223. {
  1224. #ifdef __LIBPAYLOAD__
  1225. msg_gerr("Error: No file I/O support in libpayload\n");
  1226. return 1;
  1227. #else
  1228. FILE *image;
  1229. int ret = 0;
  1230. if (!filename) {
  1231. msg_gerr("No filename specified.\n");
  1232. return 1;
  1233. }
  1234. if ((image = fopen(filename, "wb")) == NULL) {
  1235. msg_gerr("Error: opening file \"%s\" failed: %s\n", filename, strerror(errno));
  1236. return 1;
  1237. }
  1238. unsigned long numbytes = fwrite(buf, 1, size, image);
  1239. if (numbytes != size) {
  1240. msg_gerr("Error: file %s could not be written completely.\n", filename);
  1241. ret = 1;
  1242. goto out;
  1243. }
  1244. if (fflush(image)) {
  1245. msg_gerr("Error: flushing file \"%s\" failed: %s\n", filename, strerror(errno));
  1246. ret = 1;
  1247. }
  1248. // Try to fsync() only regular files and if that function is available at all (e.g. not on MinGW).
  1249. #if defined(_POSIX_FSYNC) && (_POSIX_FSYNC != -1)
  1250. struct stat image_stat;
  1251. if (fstat(fileno(image), &image_stat) != 0) {
  1252. msg_gerr("Error: getting metadata of file \"%s\" failed: %s\n", filename, strerror(errno));
  1253. ret = 1;
  1254. goto out;
  1255. }
  1256. if (S_ISREG(image_stat.st_mode)) {
  1257. if (fsync(fileno(image))) {
  1258. msg_gerr("Error: fsyncing file \"%s\" failed: %s\n", filename, strerror(errno));
  1259. ret = 1;
  1260. }
  1261. }
  1262. #endif
  1263. out:
  1264. if (fclose(image)) {
  1265. msg_gerr("Error: closing file \"%s\" failed: %s\n", filename, strerror(errno));
  1266. ret = 1;
  1267. }
  1268. return ret;
  1269. #endif
  1270. }
  1271. int read_flash_to_file(struct flashctx *flash, const char *filename)
  1272. {
  1273. unsigned long size = flash->chip->total_size * 1024;
  1274. unsigned char *buf = calloc(size, sizeof(char));
  1275. int ret = 0;
  1276. msg_cinfo("Reading flash... ");
  1277. if (!buf) {
  1278. msg_gerr("Memory allocation failed!\n");
  1279. msg_cinfo("FAILED.\n");
  1280. return 1;
  1281. }
  1282. if (!flash->chip->read) {
  1283. msg_cerr("No read function available for this flash chip.\n");
  1284. ret = 1;
  1285. goto out_free;
  1286. }
  1287. if (flash->chip->read(flash, buf, 0, size)) {
  1288. msg_cerr("Read operation failed!\n");
  1289. ret = 1;
  1290. goto out_free;
  1291. }
  1292. ret = write_buf_to_file(buf, size, filename);
  1293. out_free:
  1294. free(buf);
  1295. msg_cinfo("%s.\n", ret ? "FAILED" : "done");
  1296. return ret;
  1297. }
  1298. /* Even if an error is found, the function will keep going and check the rest. */
  1299. static int selfcheck_eraseblocks(const struct flashchip *chip)
  1300. {
  1301. int i, j, k;
  1302. int ret = 0;
  1303. for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
  1304. unsigned int done = 0;
  1305. struct block_eraser eraser = chip->block_erasers[k];
  1306. for (i = 0; i < NUM_ERASEREGIONS; i++) {
  1307. /* Blocks with zero size are bugs in flashchips.c. */
  1308. if (eraser.eraseblocks[i].count &&
  1309. !eraser.eraseblocks[i].size) {
  1310. msg_gerr("ERROR: Flash chip %s erase function "
  1311. "%i region %i has size 0. Please report"
  1312. " a bug at flashrom@flashrom.org\n",
  1313. chip->name, k, i);
  1314. ret = 1;
  1315. }
  1316. /* Blocks with zero count are bugs in flashchips.c. */
  1317. if (!eraser.eraseblocks[i].count &&
  1318. eraser.eraseblocks[i].size) {
  1319. msg_gerr("ERROR: Flash chip %s erase function "
  1320. "%i region %i has count 0. Please report"
  1321. " a bug at flashrom@flashrom.org\n",
  1322. chip->name, k, i);
  1323. ret = 1;
  1324. }
  1325. done += eraser.eraseblocks[i].count *
  1326. eraser.eraseblocks[i].size;
  1327. }
  1328. /* Empty eraseblock definition with erase function. */
  1329. if (!done && eraser.block_erase)
  1330. msg_gspew("Strange: Empty eraseblock definition with "
  1331. "non-empty erase function. Not an error.\n");
  1332. if (!done)
  1333. continue;
  1334. if (done != chip->total_size * 1024) {
  1335. msg_gerr("ERROR: Flash chip %s erase function %i "
  1336. "region walking resulted in 0x%06x bytes total,"
  1337. " expected 0x%06x bytes. Please report a bug at"
  1338. " flashrom@flashrom.org\n", chip->name, k,
  1339. done, chip->total_size * 1024);
  1340. ret = 1;
  1341. }
  1342. if (!eraser.block_erase)
  1343. continue;
  1344. /* Check if there are identical erase functions for different
  1345. * layouts. That would imply "magic" erase functions. The
  1346. * easiest way to check this is with function pointers.
  1347. */
  1348. for (j = k + 1; j < NUM_ERASEFUNCTIONS; j++) {
  1349. if (eraser.block_erase ==
  1350. chip->block_erasers[j].block_erase) {
  1351. msg_gerr("ERROR: Flash chip %s erase function "
  1352. "%i and %i are identical. Please report"
  1353. " a bug at flashrom@flashrom.org\n",
  1354. chip->name, k, j);
  1355. ret = 1;
  1356. }
  1357. }
  1358. }
  1359. return ret;
  1360. }
  1361. static int erase_and_write_block_helper(struct flashctx *flash,
  1362. unsigned int start, unsigned int len,
  1363. uint8_t *curcontents,
  1364. uint8_t *newcontents,
  1365. int (*erasefn) (struct flashctx *flash,
  1366. unsigned int addr,
  1367. unsigned int len))
  1368. {
  1369. unsigned int starthere = 0, lenhere = 0;
  1370. int ret = 0, skip = 1, writecount = 0;
  1371. enum write_granularity gran = flash->chip->gran;
  1372. /* curcontents and newcontents are opaque to walk_eraseregions, and
  1373. * need to be adjusted here to keep the impression of proper abstraction
  1374. */
  1375. curcontents += start;
  1376. newcontents += start;
  1377. msg_cdbg(":");
  1378. if (need_erase(curcontents, newcontents, len, gran)) {
  1379. msg_cdbg("E");
  1380. ret = erasefn(flash, start, len);
  1381. if (ret)
  1382. return ret;
  1383. if (check_erased_range(flash, start, len)) {
  1384. msg_cerr("ERASE FAILED!\n");
  1385. return -1;
  1386. }
  1387. /* Erase was successful. Adjust curcontents. */
  1388. memset(curcontents, 0xff, len);
  1389. skip = 0;
  1390. }
  1391. /* get_next_write() sets starthere to a new value after the call. */
  1392. while ((lenhere = get_next_write(curcontents + starthere,
  1393. newcontents + starthere,
  1394. len - starthere, &starthere, gran))) {
  1395. if (!writecount++)
  1396. msg_cdbg("W");
  1397. /* Needs the partial write function signature. */
  1398. ret = flash->chip->write(flash, newcontents + starthere,
  1399. start + starthere, lenhere);
  1400. if (ret)
  1401. return ret;
  1402. starthere += lenhere;
  1403. skip = 0;
  1404. }
  1405. if (skip)
  1406. msg_cdbg("S");
  1407. else
  1408. all_skipped = false;
  1409. return ret;
  1410. }
  1411. static int walk_eraseregions(struct flashctx *flash, int erasefunction,
  1412. int (*do_something) (struct flashctx *flash,
  1413. unsigned int addr,
  1414. unsigned int len,
  1415. uint8_t *param1,
  1416. uint8_t *param2,
  1417. int (*erasefn) (
  1418. struct flashctx *flash,
  1419. unsigned int addr,
  1420. unsigned int len)),
  1421. void *param1, void *param2)
  1422. {
  1423. int i, j;
  1424. unsigned int start = 0;
  1425. unsigned int len;
  1426. struct block_eraser eraser = flash->chip->block_erasers[erasefunction];
  1427. int show_progress = 0;
  1428. unsigned int percent_last, percent_current;
  1429. unsigned long size = flash->chip->total_size * 1024;
  1430. /* progress visualizaion init */
  1431. if(size >= MIN_LENGTH_TO_SHOW_ERASE_AND_WRITE_PROGRESS) {
  1432. msg_cinfo(" "); /* only this space will go to logfile but all strings with \b wont. */
  1433. msg_cinfo("\b 0%%");
  1434. percent_last = percent_current = 0;
  1435. show_progress = 1; /* enable progress visualizaion */
  1436. }
  1437. for (i = 0; i < NUM_ERASEREGIONS; i++) {
  1438. /* count==0 for all automatically initialized array
  1439. * members so the loop below won't be executed for them.
  1440. */
  1441. len = eraser.eraseblocks[i].size;
  1442. for (j = 0; j < eraser.eraseblocks[i].count; j++) {
  1443. /* Print this for every block except the first one. */
  1444. if (i || j)
  1445. msg_cdbg(", ");
  1446. msg_cdbg("0x%06x-0x%06x", start,
  1447. start + len - 1);
  1448. if (do_something(flash, start, len, param1, param2,
  1449. eraser.block_erase)) {
  1450. return 1;
  1451. }
  1452. start += len;
  1453. if(show_progress) {
  1454. percent_current = (unsigned int) ((unsigned long long)start * 100 / size);
  1455. if(percent_current != percent_last) {
  1456. msg_cinfo("\b\b\b%2d%%", percent_current);
  1457. percent_last = percent_current;
  1458. }
  1459. }
  1460. }
  1461. }
  1462. if(show_progress)
  1463. msg_cinfo("\b\b\b\b"); /* remove progress percents from the screen */
  1464. msg_cdbg("\n");
  1465. return 0;
  1466. }
  1467. static int check_block_eraser(const struct flashctx *flash, int k, int log)
  1468. {
  1469. struct block_eraser eraser = flash->chip->block_erasers[k];
  1470. if (!eraser.block_erase && !eraser.eraseblocks[0].count) {
  1471. if (log)
  1472. msg_cdbg("not defined. ");
  1473. return 1;
  1474. }
  1475. if (!eraser.block_erase && eraser.eraseblocks[0].count) {
  1476. if (log)
  1477. msg_cdbg("eraseblock layout is known, but matching "
  1478. "block erase function is not implemented. ");
  1479. return 1;
  1480. }
  1481. if (eraser.block_erase && !eraser.eraseblocks[0].count) {
  1482. if (log)
  1483. msg_cdbg("block erase function found, but "
  1484. "eraseblock layout is not defined. ");
  1485. return 1;
  1486. }
  1487. // TODO: Once erase functions are annotated with allowed buses, check that as well.
  1488. return 0;
  1489. }
  1490. int erase_and_write_flash(struct flashctx *flash, uint8_t *oldcontents, uint8_t *newcontents)
  1491. {
  1492. int k, ret = 1;
  1493. uint8_t *curcontents;
  1494. unsigned long size = flash->chip->total_size * 1024;
  1495. unsigned int usable_erasefunctions = count_usable_erasers(flash);
  1496. msg_cinfo("Erasing and writing flash chip... ");
  1497. curcontents = malloc(size);
  1498. if (!curcontents) {
  1499. msg_gerr("Out of memory!\n");
  1500. exit(1);
  1501. }
  1502. /* Copy oldcontents to curcontents to avoid clobbering oldcontents. */
  1503. memcpy(curcontents, oldcontents, size);
  1504. for (k = 0; k < NUM_ERASEFUNCTIONS; k++) {
  1505. if (k != 0)
  1506. msg_cinfo("Looking for another erase function.\n");
  1507. if (!usable_erasefunctions) {
  1508. msg_cinfo("No usable erase functions left.\n");
  1509. break;
  1510. }
  1511. msg_cdbg("Trying erase function %i... ", k);
  1512. if (check_block_eraser(flash, k, 1))
  1513. continue;
  1514. usable_erasefunctions--;
  1515. ret = walk_eraseregions(flash, k, &erase_and_write_block_helper,
  1516. curcontents, newcontents);
  1517. /* If everything is OK, don't try another erase function. */
  1518. if (!ret)
  1519. break;
  1520. /* Write/erase failed, so try to find out what the current chip
  1521. * contents are. If no usable erase functions remain, we can
  1522. * skip this: the next iteration will break immediately anyway.
  1523. */
  1524. if (!usable_erasefunctions)
  1525. continue;
  1526. /* Reading the whole chip may take a while, inform the user even
  1527. * in non-verbose mode.
  1528. */
  1529. msg_cinfo("Reading current flash chip contents... ");
  1530. if (flash->chip->read(flash, curcontents, 0, size)) {
  1531. /* Now we are truly screwed. Read failed as well. */
  1532. msg_cerr("Can't read anymore! Aborting.\n");
  1533. /* We have no idea about the flash chip contents, so
  1534. * retrying with another erase function is pointless.
  1535. */
  1536. break;
  1537. }
  1538. msg_cinfo("done. ");
  1539. }
  1540. /* Free the scratchpad. */
  1541. free(curcontents);
  1542. if (ret) {
  1543. msg_cerr("FAILED!\n");
  1544. } else {
  1545. if (all_skipped)
  1546. msg_cinfo("\nWarning: Chip content is identical to the requested image.\n");
  1547. msg_cinfo("Erase/write done.\n");
  1548. }
  1549. return ret;
  1550. }
  1551. static void nonfatal_help_message(void)
  1552. {
  1553. msg_gerr("Good, writing to the flash chip apparently didn't do anything.\n");
  1554. #if CONFIG_INTERNAL == 1
  1555. if (programmer == PROGRAMMER_INTERNAL)
  1556. msg_gerr("This means we have to add special support for your board, programmer or flash\n"
  1557. "chip. Please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
  1558. "mail flashrom@flashrom.org, thanks!\n"
  1559. "-------------------------------------------------------------------------------\n"
  1560. "You may now reboot or simply leave the machine running.\n");
  1561. else
  1562. #endif
  1563. msg_gerr("Please check the connections (especially those to write protection pins) between\n"
  1564. "the programmer and the flash chip. If you think the error is caused by flashrom\n"
  1565. "please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
  1566. "mail flashrom@flashrom.org, thanks!\n");
  1567. }
  1568. static void emergency_help_message(void)
  1569. {
  1570. msg_gerr("Your flash chip is in an unknown state.\n");
  1571. #if CONFIG_INTERNAL == 1
  1572. if (programmer == PROGRAMMER_INTERNAL)
  1573. msg_gerr("Get help on IRC at chat.freenode.net (channel #flashrom) or\n"
  1574. "mail flashrom@flashrom.org with the subject \"FAILED: <your board name>\"!\n"
  1575. "-------------------------------------------------------------------------------\n"
  1576. "DO NOT REBOOT OR POWEROFF!\n");
  1577. else
  1578. #endif
  1579. msg_gerr("Please report this on IRC at chat.freenode.net (channel #flashrom) or\n"
  1580. "mail flashrom@flashrom.org, thanks!\n");
  1581. }
  1582. /* The way to go if you want a delimited list of programmers */
  1583. void list_programmers(const char *delim)
  1584. {
  1585. enum programmer p;
  1586. for (p = 0; p < PROGRAMMER_INVALID; p++) {
  1587. msg_ginfo("%s", programmer_table[p].name);
  1588. if (p < PROGRAMMER_INVALID - 1)
  1589. msg_ginfo("%s", delim);
  1590. }
  1591. msg_ginfo("\n");
  1592. }
  1593. void list_programmers_linebreak(int startcol, int cols, int paren)
  1594. {
  1595. const char *pname;
  1596. int pnamelen;
  1597. int remaining = 0, firstline = 1;
  1598. enum programmer p;
  1599. int i;
  1600. for (p = 0; p < PROGRAMMER_INVALID; p++) {
  1601. pname = programmer_table[p].name;
  1602. pnamelen = strlen(pname);
  1603. if (remaining - pnamelen - 2 < 0) {
  1604. if (firstline)
  1605. firstline = 0;
  1606. else
  1607. msg_ginfo("\n");
  1608. for (i = 0; i < startcol; i++)
  1609. msg_ginfo(" ");
  1610. remaining = cols - startcol;
  1611. } else {
  1612. msg_ginfo(" ");
  1613. remaining--;
  1614. }
  1615. if (paren && (p == 0)) {
  1616. msg_ginfo("(");
  1617. remaining--;
  1618. }
  1619. msg_ginfo("%s", pname);
  1620. remaining -= pnamelen;
  1621. if (p < PROGRAMMER_INVALID - 1) {
  1622. msg_ginfo(",");
  1623. remaining--;
  1624. } else {
  1625. if (paren)
  1626. msg_ginfo(")");
  1627. }
  1628. }
  1629. }
  1630. void print_sysinfo(void)
  1631. {
  1632. #if IS_WINDOWS
  1633. SYSTEM_INFO si;
  1634. OSVERSIONINFOEX osvi;
  1635. memset(&si, 0, sizeof(SYSTEM_INFO));
  1636. memset(&osvi, 0, sizeof(OSVERSIONINFOEX));
  1637. msg_ginfo(" on Windows");
  1638. /* Tell Windows which version of the structure we want. */
  1639. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
  1640. if (GetVersionEx((OSVERSIONINFO*) &osvi))
  1641. msg_ginfo(" %lu.%lu", osvi.dwMajorVersion, osvi.dwMinorVersion);
  1642. else
  1643. msg_ginfo(" unknown version");
  1644. GetSystemInfo(&si);
  1645. switch (si.wProcessorArchitecture) {
  1646. case PROCESSOR_ARCHITECTURE_AMD64:
  1647. msg_ginfo(" (x86_64)");
  1648. break;
  1649. case PROCESSOR_ARCHITECTURE_INTEL:
  1650. msg_ginfo(" (x86)");
  1651. break;
  1652. default:
  1653. msg_ginfo(" (unknown arch)");
  1654. break;
  1655. }
  1656. #elif HAVE_UTSNAME == 1
  1657. struct utsname osinfo;
  1658. uname(&osinfo);
  1659. msg_ginfo(" on %s %s (%s)", osinfo.sysname, osinfo.release,
  1660. osinfo.machine);
  1661. #else
  1662. msg_ginfo(" on unknown machine");
  1663. #endif
  1664. }
  1665. void print_buildinfo(void)
  1666. {
  1667. msg_gdbg("flashrom was built with");
  1668. #if NEED_PCI == 1
  1669. #ifdef PCILIB_VERSION
  1670. msg_gdbg(" libpci %s,", PCILIB_VERSION);
  1671. #else
  1672. msg_gdbg(" unknown PCI library,");
  1673. #endif
  1674. #endif
  1675. #ifdef __clang__
  1676. msg_gdbg(" LLVM Clang");
  1677. #ifdef __clang_version__
  1678. msg_gdbg(" %s,", __clang_version__);
  1679. #else
  1680. msg_gdbg(" unknown version (before r102686),");
  1681. #endif
  1682. #elif defined(__GNUC__)
  1683. msg_gdbg(" GCC");
  1684. #ifdef __VERSION__
  1685. msg_gdbg(" %s,", __VERSION__);
  1686. #else
  1687. msg_gdbg(" unknown version,");
  1688. #endif
  1689. #else
  1690. msg_gdbg(" unknown compiler,");
  1691. #endif
  1692. #if defined (__FLASHROM_LITTLE_ENDIAN__)
  1693. msg_gdbg(" little endian");
  1694. #elif defined (__FLASHROM_BIG_ENDIAN__)
  1695. msg_gdbg(" big endian");
  1696. #else
  1697. #error Endianness could not be determined
  1698. #endif
  1699. msg_gdbg("\n");
  1700. }
  1701. void print_version(void)
  1702. {
  1703. msg_ginfo("flashrom %s", flashrom_version);
  1704. print_sysinfo();
  1705. msg_ginfo("\n");
  1706. }
  1707. void print_banner(void)
  1708. {
  1709. msg_ginfo("flashrom is free software, get the source code at "
  1710. "https://flashrom.org\n");
  1711. msg_ginfo("\n");
  1712. }
  1713. int selfcheck(void)
  1714. {
  1715. unsigned int i;
  1716. int ret = 0;
  1717. /* Safety check. Instead of aborting after the first error, check
  1718. * if more errors exist.
  1719. */
  1720. if (ARRAY_SIZE(programmer_table) - 1 != PROGRAMMER_INVALID) {
  1721. msg_gerr("Programmer table miscompilation!\n");
  1722. ret = 1;
  1723. }
  1724. for (i = 0; i < PROGRAMMER_INVALID; i++) {
  1725. const struct programmer_entry p = programmer_table[i];
  1726. if (p.name == NULL) {
  1727. msg_gerr("All programmers need a valid name, but the one with index %d does not!\n", i);
  1728. ret = 1;
  1729. /* This might hide other problems with this programmer, but allows for better error
  1730. * messages below without jumping through hoops. */
  1731. continue;
  1732. }
  1733. switch (p.type) {
  1734. case USB:
  1735. case PCI:
  1736. case OTHER:
  1737. if (p.devs.note == NULL) {
  1738. if (strcmp("internal", p.name) == 0)
  1739. break; /* This one has its device list stored separately. */
  1740. msg_gerr("Programmer %s has neither a device list nor a textual description!\n",
  1741. p.name);
  1742. ret = 1;
  1743. }
  1744. break;
  1745. default:
  1746. msg_gerr("Programmer %s does not have a valid type set!\n", p.name);
  1747. ret = 1;
  1748. break;
  1749. }
  1750. if (p.init == NULL) {
  1751. msg_gerr("Programmer %s does not have a valid init function!\n", p.name);
  1752. ret = 1;
  1753. }
  1754. if (p.delay == NULL) {
  1755. msg_gerr("Programmer %s does not have a valid delay function!\n", p.name);
  1756. ret = 1;
  1757. }
  1758. if (p.map_flash_region == NULL) {
  1759. msg_gerr("Programmer %s does not have a valid map_flash_region function!\n", p.name);
  1760. ret = 1;
  1761. }
  1762. if (p.unmap_flash_region == NULL) {
  1763. msg_gerr("Programmer %s does not have a valid unmap_flash_region function!\n", p.name);
  1764. ret = 1;
  1765. }
  1766. }
  1767. /* It would be favorable if we could check for the correct layout (especially termination) of various
  1768. * constant arrays: flashchips, chipset_enables, board_matches, boards_known, laptops_known.
  1769. * They are all defined as externs in this compilation unit so we don't know their sizes which vary
  1770. * depending on compiler flags, e.g. the target architecture, and can sometimes be 0.
  1771. * For 'flashchips' we export the size explicitly to work around this and to be able to implement the
  1772. * checks below. */
  1773. if (flashchips_size <= 1 || flashchips[flashchips_size - 1].name != NULL) {
  1774. msg_gerr("Flashchips table miscompilation!\n");
  1775. ret = 1;
  1776. } else {
  1777. for (i = 0; i < flashchips_size - 1; i++) {
  1778. const struct flashchip *chip = &flashchips[i];
  1779. if (chip->vendor == NULL || chip->name == NULL || chip->bustype == BUS_NONE) {
  1780. ret = 1;
  1781. msg_gerr("ERROR: Some field of flash chip #%d (%s) is misconfigured.\n"
  1782. "Please report a bug at flashrom@flashrom.org\n", i,
  1783. chip->name == NULL ? "unnamed" : chip->name);
  1784. }
  1785. if (selfcheck_eraseblocks(chip)) {
  1786. ret = 1;
  1787. }
  1788. }
  1789. }
  1790. #if CONFIG_INTERNAL == 1
  1791. ret |= selfcheck_board_enables();
  1792. #endif
  1793. /* TODO: implement similar sanity checks for other arrays where deemed necessary. */
  1794. return ret;
  1795. }
  1796. /* FIXME: This function signature needs to be improved once doit() has a better
  1797. * function signature.
  1798. */
  1799. int chip_safety_check(const struct flashctx *flash, int force, int read_it, int write_it, int erase_it,
  1800. int verify_it)
  1801. {
  1802. const struct flashchip *chip = flash->chip;
  1803. if (!programmer_may_write && (write_it || erase_it)) {
  1804. msg_perr("Write/erase is not working yet on your programmer in "
  1805. "its current configuration.\n");
  1806. /* --force is the wrong approach, but it's the best we can do
  1807. * until the generic programmer parameter parser is merged.
  1808. */
  1809. if (!force)
  1810. return 1;
  1811. msg_cerr("Continuing anyway.\n");
  1812. }
  1813. if (read_it || erase_it || write_it || verify_it) {
  1814. /* Everything needs read. */
  1815. if (chip->tested.read == BAD) {
  1816. msg_cerr("Read is not working on this chip. ");
  1817. if (!force)
  1818. return 1;
  1819. msg_cerr("Continuing anyway.\n");
  1820. }
  1821. if (!chip->read) {
  1822. msg_cerr("flashrom has no read function for this "
  1823. "flash chip.\n");
  1824. return 1;
  1825. }
  1826. }
  1827. if (erase_it || write_it) {
  1828. /* Write needs erase. */
  1829. if (chip->tested.erase == NA) {
  1830. msg_cerr("Erase is not possible on this chip.\n");
  1831. return 1;
  1832. }
  1833. if (chip->tested.erase == BAD) {
  1834. msg_cerr("Erase is not working on this chip. ");
  1835. if (!force)
  1836. return 1;
  1837. msg_cerr("Continuing anyway.\n");
  1838. }
  1839. if(count_usable_erasers(flash) == 0) {
  1840. msg_cerr("flashrom has no erase function for this "
  1841. "flash chip.\n");
  1842. return 1;
  1843. }
  1844. }
  1845. if (write_it) {
  1846. if (chip->tested.write == NA) {
  1847. msg_cerr("Write is not possible on this chip.\n");
  1848. return 1;
  1849. }
  1850. if (chip->tested.write == BAD) {
  1851. msg_cerr("Write is not working on this chip. ");
  1852. if (!force)
  1853. return 1;
  1854. msg_cerr("Continuing anyway.\n");
  1855. }
  1856. if (!chip->write) {
  1857. msg_cerr("flashrom has no write function for this "
  1858. "flash chip.\n");
  1859. return 1;
  1860. }
  1861. }
  1862. return 0;
  1863. }
  1864. /* This function signature is horrible. We need to design a better interface,
  1865. * but right now it allows us to split off the CLI code.
  1866. * Besides that, the function itself is a textbook example of abysmal code flow.
  1867. */
  1868. int doit(struct flashctx *flash, int force, const char *filename, int read_it,
  1869. int write_it, int erase_it, int verify_it)
  1870. {
  1871. uint8_t *oldcontents;
  1872. uint8_t *newcontents;
  1873. int ret = 0;
  1874. unsigned long size = flash->chip->total_size * 1024;
  1875. int read_all_first = 1; /* FIXME: Make this configurable. */
  1876. if (chip_safety_check(flash, force, read_it, write_it, erase_it, verify_it)) {
  1877. msg_cerr("Aborting.\n");
  1878. return 1;
  1879. }
  1880. if (normalize_romentries(flash)) {
  1881. msg_cerr("Requested regions can not be handled. Aborting.\n");
  1882. return 1;
  1883. }
  1884. /* Given the existence of read locks, we want to unlock for read,
  1885. * erase and write.
  1886. */
  1887. if (flash->chip->unlock)
  1888. flash->chip->unlock(flash);
  1889. /* Switching to 4-Bytes Addressing mode if flash chip supports it */
  1890. if(flash->chip->feature_bits & FEATURE_4BA_SUPPORT) {
  1891. /* Do not switch if chip is already in 4-bytes addressing mode */
  1892. if (flash->chip->feature_bits & FEATURE_4BA_ONLY) {
  1893. msg_cdbg("Flash chip is already in 4-bytes addressing mode.\n");
  1894. }
  1895. /* Do not switch to 4-Bytes Addressing mode if using Extended Address Register */
  1896. else if(flash->chip->feature_bits & FEATURE_4BA_EXTENDED_ADDR_REG) {
  1897. msg_cdbg("Using 4-bytes addressing with extended address register.\n");
  1898. }
  1899. /* Go to 4-Bytes Addressing mode if selected
  1900. operation requires 4-Bytes Addressing mode
  1901. (no need if functions are direct-4BA) */
  1902. else if(((read_it || verify_it)
  1903. && (!(flash->chip->feature_bits & FEATURE_4BA_DIRECT_READ)))
  1904. || ((erase_it || write_it)
  1905. && ((flash->chip->feature_bits & FEATURE_4BA_ALL_DIRECT) != FEATURE_4BA_ALL_DIRECT))) {
  1906. if (!flash->chip->four_bytes_addr_funcs.enter_4ba) {
  1907. msg_cerr("No function for Enter 4-bytes addressing mode for this flash chip.\n"
  1908. "Please report to flashrom@flashrom.org\n");
  1909. return 1;
  1910. }
  1911. if(flash->chip->four_bytes_addr_funcs.enter_4ba(flash)) {
  1912. msg_cerr("Switching to 4-bytes addressing mode failed!\n");
  1913. return 1;
  1914. }
  1915. msg_cdbg("Switched to 4-bytes addressing mode.\n");
  1916. }
  1917. /* Do not switch to 4-Bytes Addressing mode if all instructions are direct-4BA
  1918. or if the flash chip is 4-Bytes Addressing Only and always in 4BA-mode */
  1919. else {
  1920. msg_cdbg2("No need to switch to 4-bytes addressing mode.\n");
  1921. }
  1922. }
  1923. if (read_it) {
  1924. return read_flash_to_file(flash, filename);
  1925. }
  1926. oldcontents = malloc(size);
  1927. if (!oldcontents) {
  1928. msg_gerr("Out of memory!\n");
  1929. exit(1);
  1930. }
  1931. /* Assume worst case: All bits are 0. */
  1932. memset(oldcontents, 0x00, size);
  1933. newcontents = malloc(size);
  1934. if (!newcontents) {
  1935. msg_gerr("Out of memory!\n");
  1936. exit(1);
  1937. }
  1938. /* Assume best case: All bits should be 1. */
  1939. memset(newcontents, 0xff, size);
  1940. /* Side effect of the assumptions above: Default write action is erase
  1941. * because newcontents looks like a completely erased chip, and
  1942. * oldcontents being completely 0x00 means we have to erase everything
  1943. * before we can write.
  1944. */
  1945. if (erase_it) {
  1946. /* FIXME: Do we really want the scary warning if erase failed?
  1947. * After all, after erase the chip is either blank or partially
  1948. * blank or it has the old contents. A blank chip won't boot,
  1949. * so if the user wanted erase and reboots afterwards, the user
  1950. * knows very well that booting won't work.
  1951. */
  1952. if (erase_and_write_flash(flash, oldcontents, newcontents)) {
  1953. emergency_help_message();
  1954. ret = 1;
  1955. }
  1956. goto out;
  1957. }
  1958. if (write_it || verify_it) {
  1959. if (read_buf_from_file(newcontents, size, filename)) {
  1960. ret = 1;
  1961. goto out;
  1962. }
  1963. #if CONFIG_INTERNAL == 1
  1964. if (programmer == PROGRAMMER_INTERNAL && cb_check_image(newcontents, size) < 0) {
  1965. if (force_boardmismatch) {
  1966. msg_pinfo("Proceeding anyway because user forced us to.\n");
  1967. } else {
  1968. msg_perr("Aborting. You can override this with "
  1969. "-p internal:boardmismatch=force.\n");
  1970. ret = 1;
  1971. goto out;
  1972. }
  1973. }
  1974. #endif
  1975. }
  1976. /* Read the whole chip to be able to check whether regions need to be
  1977. * erased and to give better diagnostics in case write fails.
  1978. * The alternative is to read only the regions which are to be
  1979. * preserved, but in that case we might perform unneeded erase which
  1980. * takes time as well.
  1981. */
  1982. if (read_all_first) {
  1983. msg_cinfo("Reading old flash chip contents... ");
  1984. if (flash->chip->read(flash, oldcontents, 0, size)) {
  1985. ret = 1;
  1986. msg_cinfo("FAILED.\n");
  1987. goto out;
  1988. }
  1989. }
  1990. msg_cinfo("done.\n");
  1991. /* Build a new image taking the given layout into account. */
  1992. if (build_new_image(flash, read_all_first, oldcontents, newcontents)) {
  1993. msg_gerr("Could not prepare the data to be written, aborting.\n");
  1994. ret = 1;
  1995. goto out;
  1996. }
  1997. // ////////////////////////////////////////////////////////////
  1998. if (write_it && erase_and_write_flash(flash, oldcontents, newcontents)) {
  1999. msg_cerr("Uh oh. Erase/write failed. ");
  2000. if (read_all_first) {
  2001. msg_cerr("Checking if anything has changed.\n");
  2002. msg_cinfo("Reading current flash chip contents... ");
  2003. if (!flash->chip->read(flash, newcontents, 0, size)) {
  2004. msg_cinfo("done.\n");
  2005. if (!memcmp(oldcontents, newcontents, size)) {
  2006. nonfatal_help_message();
  2007. ret = 1;
  2008. goto out;
  2009. }
  2010. msg_cerr("Apparently at least some data has changed.\n");
  2011. } else
  2012. msg_cerr("Can't even read anymore!\n");
  2013. emergency_help_message();
  2014. ret = 1;
  2015. goto out;
  2016. } else
  2017. msg_cerr("\n");
  2018. emergency_help_message();
  2019. ret = 1;
  2020. goto out;
  2021. }
  2022. /* Verify only if we either did not try to write (verify operation) or actually changed something. */
  2023. if (verify_it && (!write_it || !all_skipped)) {
  2024. msg_cinfo("Verifying flash... ");
  2025. if (write_it) {
  2026. /* Work around chips which need some time to calm down. */
  2027. programmer_delay(1000*1000);
  2028. ret = verify_range(flash, newcontents, 0, size);
  2029. /* If we tried to write, and verification now fails, we
  2030. * might have an emergency situation.
  2031. */
  2032. if (ret)
  2033. emergency_help_message();
  2034. } else {
  2035. ret = compare_range(newcontents, oldcontents, 0, size);
  2036. }
  2037. if (!ret)
  2038. msg_cinfo("VERIFIED.\n");
  2039. }
  2040. out:
  2041. free(oldcontents);
  2042. free(newcontents);
  2043. return ret;
  2044. }