flashrom.c 58 KB

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