dediprog.c 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. /*
  2. * This file is part of the flashrom project.
  3. *
  4. * Copyright (C) 2010 Carl-Daniel Hailfinger
  5. * Copyright (C) 2015 Simon Glass
  6. * Copyright (C) 2015 Stefan Tauner
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; version 2 of the License.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "platform.h"
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include <limits.h>
  26. #include <errno.h>
  27. #include <libusb.h>
  28. #include "flash.h"
  29. #include "chipdrivers.h"
  30. #include "programmer.h"
  31. #include "spi.h"
  32. /* LIBUSB_CALL ensures the right calling conventions on libusb callbacks.
  33. * However, the macro is not defined everywhere. m(
  34. */
  35. #ifndef LIBUSB_CALL
  36. #define LIBUSB_CALL
  37. #endif
  38. #define FIRMWARE_VERSION(x,y,z) ((x << 16) | (y << 8) | z)
  39. #define DEFAULT_TIMEOUT 3000
  40. #define DEDIPROG_ASYNC_TRANSFERS 8 /* at most 8 asynchronous transfers */
  41. #define REQTYPE_OTHER_OUT (LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_OTHER) /* 0x43 */
  42. #define REQTYPE_OTHER_IN (LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_OTHER) /* 0xC3 */
  43. #define REQTYPE_EP_OUT (LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_ENDPOINT) /* 0x42 */
  44. #define REQTYPE_EP_IN (LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_ENDPOINT) /* 0xC2 */
  45. struct libusb_context *usb_ctx;
  46. static libusb_device_handle *dediprog_handle;
  47. static int dediprog_in_endpoint;
  48. static int dediprog_out_endpoint;
  49. enum dediprog_devtype {
  50. DEV_UNKNOWN = 0,
  51. DEV_SF100 = 100,
  52. DEV_SF600 = 600,
  53. };
  54. enum dediprog_leds {
  55. LED_INVALID = -1,
  56. LED_NONE = 0,
  57. LED_PASS = 1 << 0,
  58. LED_BUSY = 1 << 1,
  59. LED_ERROR = 1 << 2,
  60. LED_ALL = 7,
  61. };
  62. /* IO bits for CMD_SET_IO_LED message */
  63. enum dediprog_ios {
  64. IO1 = 1 << 0,
  65. IO2 = 1 << 1,
  66. IO3 = 1 << 2,
  67. IO4 = 1 << 3,
  68. };
  69. enum dediprog_cmds {
  70. CMD_TRANSCEIVE = 0x01,
  71. CMD_POLL_STATUS_REG = 0x02,
  72. CMD_SET_VPP = 0x03,
  73. CMD_SET_TARGET = 0x04,
  74. CMD_READ_EEPROM = 0x05,
  75. CMD_WRITE_EEPROM = 0x06,
  76. CMD_SET_IO_LED = 0x07,
  77. CMD_READ_PROG_INFO = 0x08,
  78. CMD_SET_VCC = 0x09,
  79. CMD_SET_STANDALONE = 0x0A,
  80. CMD_SET_VOLTAGE = 0x0B, /* Only in firmware older than 6.0.0 */
  81. CMD_GET_BUTTON = 0x11,
  82. CMD_GET_UID = 0x12,
  83. CMD_SET_CS = 0x14,
  84. CMD_IO_MODE = 0x15,
  85. CMD_FW_UPDATE = 0x1A,
  86. CMD_FPGA_UPDATE = 0x1B,
  87. CMD_READ_FPGA_VERSION = 0x1C,
  88. CMD_SET_HOLD = 0x1D,
  89. CMD_READ = 0x20,
  90. CMD_WRITE = 0x30,
  91. CMD_WRITE_AT45DB = 0x31,
  92. CMD_NAND_WRITE = 0x32,
  93. CMD_NAND_READ = 0x33,
  94. CMD_SET_SPI_CLK = 0x61,
  95. CMD_CHECK_SOCKET = 0x62,
  96. CMD_DOWNLOAD_PRJ = 0x63,
  97. CMD_READ_PRJ_NAME = 0x64,
  98. // New protocol/firmware only
  99. CMD_CHECK_SDCARD = 0x65,
  100. CMD_READ_PRJ = 0x66,
  101. };
  102. enum dediprog_target {
  103. FLASH_TYPE_APPLICATION_FLASH_1 = 0,
  104. FLASH_TYPE_FLASH_CARD,
  105. FLASH_TYPE_APPLICATION_FLASH_2,
  106. FLASH_TYPE_SOCKET,
  107. };
  108. enum dediprog_readmode {
  109. READ_MODE_STD = 1,
  110. READ_MODE_FAST = 2,
  111. READ_MODE_ATMEL45 = 3,
  112. READ_MODE_4B_ADDR_FAST = 4,
  113. READ_MODE_4B_ADDR_FAST_0x0C = 5, /* New protocol only */
  114. };
  115. enum dediprog_writemode {
  116. WRITE_MODE_PAGE_PGM = 1,
  117. WRITE_MODE_PAGE_WRITE = 2,
  118. WRITE_MODE_1B_AAI = 3,
  119. WRITE_MODE_2B_AAI = 4,
  120. WRITE_MODE_128B_PAGE = 5,
  121. WRITE_MODE_PAGE_AT26DF041 = 6,
  122. WRITE_MODE_SILICON_BLUE_FPGA = 7,
  123. WRITE_MODE_64B_PAGE_NUMONYX_PCM = 8, /* unit of 512 bytes */
  124. WRITE_MODE_4B_ADDR_256B_PAGE_PGM = 9,
  125. WRITE_MODE_32B_PAGE_PGM_MXIC_512K = 10, /* unit of 512 bytes */
  126. WRITE_MODE_4B_ADDR_256B_PAGE_PGM_0x12 = 11,
  127. WRITE_MODE_4B_ADDR_256B_PAGE_PGM_FLAGS = 12,
  128. };
  129. enum dediprog_standalone_mode {
  130. ENTER_STANDALONE_MODE = 0,
  131. LEAVE_STANDALONE_MODE = 1,
  132. };
  133. const struct dev_entry devs_dediprog[] = {
  134. {0x0483, 0xDADA, OK, "Dediprog", "SF100/SF600"},
  135. {0},
  136. };
  137. static int dediprog_firmwareversion = FIRMWARE_VERSION(0, 0, 0);
  138. enum dediprog_devtype dediprog_devicetype = DEV_UNKNOWN;
  139. #if defined(LIBUSB_MAJOR) && defined(LIBUSB_MINOR) && defined(LIBUSB_MICRO) && \
  140. LIBUSB_MAJOR <= 1 && LIBUSB_MINOR == 0 && LIBUSB_MICRO < 9
  141. /* Quick and dirty replacement for missing libusb_error_name in libusb < 1.0.9 */
  142. const char * LIBUSB_CALL libusb_error_name(int error_code)
  143. {
  144. if (error_code >= INT16_MIN && error_code <= INT16_MAX) {
  145. /* 18 chars for text, rest for number (16 b should be enough), sign, nullbyte. */
  146. static char my_libusb_error[18 + 5 + 2];
  147. sprintf(my_libusb_error, "libusb error code %i", error_code);
  148. return my_libusb_error;
  149. } else {
  150. return "UNKNOWN";
  151. }
  152. }
  153. #endif
  154. /* Returns true if firmware (and thus hardware) supports the "new" protocol */
  155. static bool is_new_prot(void)
  156. {
  157. switch (dediprog_devicetype) {
  158. case DEV_SF100:
  159. return dediprog_firmwareversion >= FIRMWARE_VERSION(5, 5, 0);
  160. case DEV_SF600:
  161. return dediprog_firmwareversion >= FIRMWARE_VERSION(6, 9, 0);
  162. default:
  163. return 0;
  164. }
  165. }
  166. struct dediprog_transfer_status {
  167. int error; /* OK if 0, ERROR else */
  168. unsigned int queued_idx;
  169. unsigned int finished_idx;
  170. };
  171. static void LIBUSB_CALL dediprog_bulk_read_cb(struct libusb_transfer *const transfer)
  172. {
  173. struct dediprog_transfer_status *const status = (struct dediprog_transfer_status *)transfer->user_data;
  174. if (transfer->status != LIBUSB_TRANSFER_COMPLETED) {
  175. status->error = 1;
  176. msg_perr("SPI bulk read failed!\n");
  177. }
  178. ++status->finished_idx;
  179. }
  180. static int dediprog_bulk_read_poll(const struct dediprog_transfer_status *const status, const int finish)
  181. {
  182. if (status->finished_idx >= status->queued_idx)
  183. return 0;
  184. do {
  185. struct timeval timeout = { 10, 0 };
  186. const int ret = libusb_handle_events_timeout(usb_ctx, &timeout);
  187. if (ret < 0) {
  188. msg_perr("Polling read events failed: %i %s!\n", ret, libusb_error_name(ret));
  189. return 1;
  190. }
  191. } while (finish && (status->finished_idx < status->queued_idx));
  192. return 0;
  193. }
  194. static int dediprog_read(enum dediprog_cmds cmd, unsigned int value, unsigned int idx, uint8_t *bytes, size_t size)
  195. {
  196. return libusb_control_transfer(dediprog_handle, REQTYPE_EP_IN, cmd, value, idx,
  197. (unsigned char *)bytes, size, DEFAULT_TIMEOUT);
  198. }
  199. static int dediprog_write(enum dediprog_cmds cmd, unsigned int value, unsigned int idx, const uint8_t *bytes, size_t size)
  200. {
  201. return libusb_control_transfer(dediprog_handle, REQTYPE_EP_OUT, cmd, value, idx,
  202. (unsigned char *)bytes, size, DEFAULT_TIMEOUT);
  203. }
  204. /* Might be useful for other USB devices as well. static for now.
  205. * num parameter allows user to specify one device of multiple installed */
  206. static struct libusb_device_handle *get_device_by_vid_pid_number(uint16_t vid, uint16_t pid, unsigned int num)
  207. {
  208. struct libusb_device **list;
  209. ssize_t count = libusb_get_device_list(usb_ctx, &list);
  210. if (count < 0) {
  211. msg_perr("Getting the USB device list failed (%s)!\n", libusb_error_name(count));
  212. return NULL;
  213. }
  214. struct libusb_device_handle *handle = NULL;
  215. ssize_t i = 0;
  216. for (i = 0; i < count; i++) {
  217. struct libusb_device *dev = list[i];
  218. struct libusb_device_descriptor desc;
  219. int err = libusb_get_device_descriptor(dev, &desc);
  220. if (err != 0) {
  221. msg_perr("Reading the USB device descriptor failed (%s)!\n", libusb_error_name(err));
  222. libusb_free_device_list(list, 1);
  223. return NULL;
  224. }
  225. if ((desc.idVendor == vid) && (desc.idProduct == pid)) {
  226. msg_pdbg("Found USB device %04"PRIx16":%04"PRIx16" at address %d-%d.\n",
  227. desc.idVendor, desc.idProduct,
  228. libusb_get_bus_number(dev), libusb_get_device_address(dev));
  229. if (num == 0) {
  230. err = libusb_open(dev, &handle);
  231. if (err != 0) {
  232. msg_perr("Opening the USB device failed (%s)!\n",
  233. libusb_error_name(err));
  234. libusb_free_device_list(list, 1);
  235. return NULL;
  236. }
  237. break;
  238. }
  239. num--;
  240. }
  241. }
  242. libusb_free_device_list(list, 1);
  243. return handle;
  244. }
  245. /* This function sets the GPIOs connected to the LEDs as well as IO1-IO4. */
  246. static int dediprog_set_leds(int leds)
  247. {
  248. if (leds < LED_NONE || leds > LED_ALL)
  249. leds = LED_ALL;
  250. /* Older Dediprogs with 2.x.x and 3.x.x firmware only had two LEDs, assigned to different bits. So map
  251. * them around if we have an old device. On those devices the LEDs map as follows:
  252. * bit 2 == 0: green light is on.
  253. * bit 0 == 0: red light is on.
  254. *
  255. * Additionally, the command structure has changed with the "new" protocol.
  256. *
  257. * FIXME: take IO pins into account
  258. */
  259. int target_leds, ret;
  260. if (is_new_prot()) {
  261. target_leds = (leds ^ 7) << 8;
  262. ret = dediprog_write(CMD_SET_IO_LED, target_leds, 0, NULL, 0);
  263. } else {
  264. if (dediprog_firmwareversion < FIRMWARE_VERSION(5, 0, 0)) {
  265. target_leds = ((leds & LED_ERROR) >> 2) | ((leds & LED_PASS) << 2);
  266. } else {
  267. target_leds = leds;
  268. }
  269. target_leds ^= 7;
  270. ret = dediprog_write(CMD_SET_IO_LED, 0x9, target_leds, NULL, 0);
  271. }
  272. if (ret != 0x0) {
  273. msg_perr("Command Set LED 0x%x failed (%s)!\n", leds, libusb_error_name(ret));
  274. return 1;
  275. }
  276. return 0;
  277. }
  278. static int dediprog_set_spi_voltage(int millivolt)
  279. {
  280. int ret;
  281. uint16_t voltage_selector;
  282. switch (millivolt) {
  283. case 0:
  284. /* Admittedly this one is an assumption. */
  285. voltage_selector = 0x0;
  286. break;
  287. case 1800:
  288. voltage_selector = 0x12;
  289. break;
  290. case 2500:
  291. voltage_selector = 0x11;
  292. break;
  293. case 3500:
  294. voltage_selector = 0x10;
  295. break;
  296. default:
  297. msg_perr("Unknown voltage %i mV! Aborting.\n", millivolt);
  298. return 1;
  299. }
  300. msg_pdbg("Setting SPI voltage to %u.%03u V\n", millivolt / 1000,
  301. millivolt % 1000);
  302. if (voltage_selector == 0) {
  303. /* Wait some time as the original driver does. */
  304. programmer_delay(200 * 1000);
  305. }
  306. ret = dediprog_write(CMD_SET_VCC, voltage_selector, 0, NULL, 0);
  307. if (ret != 0x0) {
  308. msg_perr("Command Set SPI Voltage 0x%x failed!\n",
  309. voltage_selector);
  310. return 1;
  311. }
  312. if (voltage_selector != 0) {
  313. /* Wait some time as the original driver does. */
  314. programmer_delay(200 * 1000);
  315. }
  316. return 0;
  317. }
  318. struct dediprog_spispeeds {
  319. const char *const name;
  320. const int speed;
  321. };
  322. static const struct dediprog_spispeeds spispeeds[] = {
  323. { "24M", 0x0 },
  324. { "12M", 0x2 },
  325. { "8M", 0x1 },
  326. { "3M", 0x3 },
  327. { "2.18M", 0x4 },
  328. { "1.5M", 0x5 },
  329. { "750k", 0x6 },
  330. { "375k", 0x7 },
  331. { NULL, 0x0 },
  332. };
  333. static int dediprog_set_spi_speed(unsigned int spispeed_idx)
  334. {
  335. if (dediprog_firmwareversion < FIRMWARE_VERSION(5, 0, 0)) {
  336. msg_pwarn("Skipping to set SPI speed because firmware is too old.\n");
  337. return 0;
  338. }
  339. const struct dediprog_spispeeds *spispeed = &spispeeds[spispeed_idx];
  340. msg_pdbg("SPI speed is %sHz\n", spispeed->name);
  341. int ret = dediprog_write(CMD_SET_SPI_CLK, spispeed->speed, 0, NULL, 0);
  342. if (ret != 0x0) {
  343. msg_perr("Command Set SPI Speed 0x%x failed!\n", spispeed->speed);
  344. return 1;
  345. }
  346. return 0;
  347. }
  348. static void fill_rw_cmd_payload(uint8_t *data_packet, unsigned int count, uint8_t dedi_spi_cmd, unsigned int *value, unsigned int *idx, unsigned int start) {
  349. /* First 5 bytes are common in both generations. */
  350. data_packet[0] = count & 0xff;
  351. data_packet[1] = (count >> 8) & 0xff;
  352. data_packet[2] = 0; /* RFU */
  353. data_packet[3] = dedi_spi_cmd; /* Read/Write Mode (currently READ_MODE_STD, WRITE_MODE_PAGE_PGM or WRITE_MODE_2B_AAI) */
  354. data_packet[4] = 0; /* "Opcode". Specs imply necessity only for READ_MODE_4B_ADDR_FAST and WRITE_MODE_4B_ADDR_256B_PAGE_PGM */
  355. if (is_new_prot()) {
  356. *value = *idx = 0;
  357. data_packet[5] = 0; /* RFU */
  358. data_packet[6] = (start >> 0) & 0xff;
  359. data_packet[7] = (start >> 8) & 0xff;
  360. data_packet[8] = (start >> 16) & 0xff;
  361. data_packet[9] = (start >> 24) & 0xff;
  362. } else {
  363. *value = start % 0x10000;
  364. *idx = start / 0x10000;
  365. }
  366. }
  367. /* Bulk read interface, will read multiple 512 byte chunks aligned to 512 bytes.
  368. * @start start address
  369. * @len length
  370. * @return 0 on success, 1 on failure
  371. */
  372. static int dediprog_spi_bulk_read(struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len)
  373. {
  374. int err = 1;
  375. /* chunksize must be 512, other sizes will NOT work at all. */
  376. const unsigned int chunksize = 512;
  377. const unsigned int count = len / chunksize;
  378. struct dediprog_transfer_status status = { 0, 0, 0 };
  379. struct libusb_transfer *transfers[DEDIPROG_ASYNC_TRANSFERS] = { NULL, };
  380. struct libusb_transfer *transfer;
  381. if ((start % chunksize) || (len % chunksize)) {
  382. msg_perr("%s: Unaligned start=%i, len=%i! Please report a bug at flashrom@flashrom.org\n",
  383. __func__, start, len);
  384. return 1;
  385. }
  386. if (len == 0)
  387. return 0;
  388. /* Command packet size of protocols: new 10 B, old 5 B. */
  389. uint8_t data_packet[is_new_prot() ? 10 : 5];
  390. unsigned int value, idx;
  391. fill_rw_cmd_payload(data_packet, count, READ_MODE_STD, &value, &idx, start);
  392. int ret = dediprog_write(CMD_READ, value, idx, data_packet, sizeof(data_packet));
  393. if (ret != sizeof(data_packet)) {
  394. msg_perr("Command Read SPI Bulk failed, %i %s!\n", ret, libusb_error_name(ret));
  395. return 1;
  396. }
  397. /*
  398. * Ring buffer of bulk transfers.
  399. * Poll until at least one transfer is ready,
  400. * schedule next transfers until buffer is full.
  401. */
  402. /* Allocate bulk transfers. */
  403. unsigned int i;
  404. for (i = 0; i < min(DEDIPROG_ASYNC_TRANSFERS, count); ++i) {
  405. transfers[i] = libusb_alloc_transfer(0);
  406. if (!transfers[i]) {
  407. msg_perr("Allocating libusb transfer %i failed: %s!\n", i, libusb_error_name(ret));
  408. goto err_free;
  409. }
  410. }
  411. /* Now transfer requested chunks using libusb's asynchronous interface. */
  412. while (!status.error && (status.queued_idx < count)) {
  413. while ((status.queued_idx - status.finished_idx) < DEDIPROG_ASYNC_TRANSFERS) {
  414. transfer = transfers[status.queued_idx % DEDIPROG_ASYNC_TRANSFERS];
  415. libusb_fill_bulk_transfer(transfer, dediprog_handle, 0x80 | dediprog_in_endpoint,
  416. (unsigned char *)buf + status.queued_idx * chunksize, chunksize,
  417. dediprog_bulk_read_cb, &status, DEFAULT_TIMEOUT);
  418. transfer->flags |= LIBUSB_TRANSFER_SHORT_NOT_OK;
  419. ret = libusb_submit_transfer(transfer);
  420. if (ret < 0) {
  421. msg_perr("Submitting SPI bulk read %i failed: %s!\n",
  422. status.queued_idx, libusb_error_name(ret));
  423. goto err_free;
  424. }
  425. ++status.queued_idx;
  426. }
  427. if (dediprog_bulk_read_poll(&status, 0))
  428. goto err_free;
  429. }
  430. /* Wait for transfers to finish. */
  431. if (dediprog_bulk_read_poll(&status, 1))
  432. goto err_free;
  433. /* Check if everything has been transmitted. */
  434. if ((status.finished_idx < count) || status.error)
  435. goto err_free;
  436. err = 0;
  437. err_free:
  438. dediprog_bulk_read_poll(&status, 1);
  439. for (i = 0; i < DEDIPROG_ASYNC_TRANSFERS; ++i)
  440. if (transfers[i]) libusb_free_transfer(transfers[i]);
  441. return err;
  442. }
  443. static int dediprog_spi_read(struct flashctx *flash, uint8_t *buf, unsigned int start, unsigned int len)
  444. {
  445. int ret;
  446. /* chunksize must be 512, other sizes will NOT work at all. */
  447. const unsigned int chunksize = 0x200;
  448. unsigned int residue = start % chunksize ? chunksize - start % chunksize : 0;
  449. unsigned int bulklen;
  450. dediprog_set_leds(LED_BUSY);
  451. if (residue) {
  452. msg_pdbg("Slow read for partial block from 0x%x, length 0x%x\n",
  453. start, residue);
  454. ret = spi_read_chunked(flash, buf, start, residue, 16);
  455. if (ret)
  456. goto err;
  457. }
  458. /* Round down. */
  459. bulklen = (len - residue) / chunksize * chunksize;
  460. ret = dediprog_spi_bulk_read(flash, buf + residue, start + residue, bulklen);
  461. if (ret)
  462. goto err;
  463. len -= residue + bulklen;
  464. if (len != 0) {
  465. msg_pdbg("Slow read for partial block from 0x%x, length 0x%x\n",
  466. start, len);
  467. ret = spi_read_chunked(flash, buf + residue + bulklen,
  468. start + residue + bulklen, len, 16);
  469. if (ret)
  470. goto err;
  471. }
  472. dediprog_set_leds(LED_PASS);
  473. return 0;
  474. err:
  475. dediprog_set_leds(LED_ERROR);
  476. return ret;
  477. }
  478. /* Bulk write interface, will write multiple chunksize byte chunks aligned to chunksize bytes.
  479. * @chunksize length of data chunks, only 256 supported by now
  480. * @start start address
  481. * @len length
  482. * @dedi_spi_cmd dediprog specific write command for spi bus
  483. * @return 0 on success, 1 on failure
  484. */
  485. static int dediprog_spi_bulk_write(struct flashctx *flash, const uint8_t *buf, unsigned int chunksize,
  486. unsigned int start, unsigned int len, uint8_t dedi_spi_cmd)
  487. {
  488. /* USB transfer size must be 512, other sizes will NOT work at all.
  489. * chunksize is the real data size per USB bulk transfer. The remaining
  490. * space in a USB bulk transfer must be filled with 0xff padding.
  491. */
  492. const unsigned int count = len / chunksize;
  493. /*
  494. * We should change this check to
  495. * chunksize > 512
  496. * once we know how to handle different chunk sizes.
  497. */
  498. if (chunksize != 256) {
  499. msg_perr("%s: Chunk sizes other than 256 bytes are unsupported, chunksize=%u!\n"
  500. "Please report a bug at flashrom@flashrom.org\n", __func__, chunksize);
  501. return 1;
  502. }
  503. if ((start % chunksize) || (len % chunksize)) {
  504. msg_perr("%s: Unaligned start=%i, len=%i! Please report a bug "
  505. "at flashrom@flashrom.org\n", __func__, start, len);
  506. return 1;
  507. }
  508. /* No idea if the hardware can handle empty writes, so chicken out. */
  509. if (len == 0)
  510. return 0;
  511. /* Command packet size of protocols: new 10 B, old 5 B. */
  512. uint8_t data_packet[is_new_prot() ? 10 : 5];
  513. unsigned int value, idx;
  514. fill_rw_cmd_payload(data_packet, count, dedi_spi_cmd, &value, &idx, start);
  515. int ret = dediprog_write(CMD_WRITE, value, idx, data_packet, sizeof(data_packet));
  516. if (ret != sizeof(data_packet)) {
  517. msg_perr("Command Write SPI Bulk failed, %s!\n", libusb_error_name(ret));
  518. return 1;
  519. }
  520. unsigned int i;
  521. for (i = 0; i < count; i++) {
  522. unsigned char usbbuf[512];
  523. memcpy(usbbuf, buf + i * chunksize, chunksize);
  524. memset(usbbuf + chunksize, 0xff, sizeof(usbbuf) - chunksize); // fill up with 0xFF
  525. int transferred;
  526. ret = libusb_bulk_transfer(dediprog_handle, dediprog_out_endpoint, usbbuf, 512, &transferred,
  527. DEFAULT_TIMEOUT);
  528. if ((ret < 0) || (transferred != 512)) {
  529. msg_perr("SPI bulk write failed, expected %i, got %s!\n", 512, libusb_error_name(ret));
  530. return 1;
  531. }
  532. }
  533. return 0;
  534. }
  535. static int dediprog_spi_write(struct flashctx *flash, const uint8_t *buf,
  536. unsigned int start, unsigned int len, uint8_t dedi_spi_cmd)
  537. {
  538. int ret;
  539. const unsigned int chunksize = flash->chip->page_size;
  540. unsigned int residue = start % chunksize ? chunksize - start % chunksize : 0;
  541. unsigned int bulklen;
  542. dediprog_set_leds(LED_BUSY);
  543. if (chunksize != 256) {
  544. msg_pdbg("Page sizes other than 256 bytes are unsupported as "
  545. "we don't know how dediprog\nhandles them.\n");
  546. /* Write everything like it was residue. */
  547. residue = len;
  548. }
  549. if (residue) {
  550. msg_pdbg("Slow write for partial block from 0x%x, length 0x%x\n",
  551. start, residue);
  552. /* No idea about the real limit. Maybe 12, maybe more. */
  553. ret = spi_write_chunked(flash, buf, start, residue, 12);
  554. if (ret) {
  555. dediprog_set_leds(LED_ERROR);
  556. return ret;
  557. }
  558. }
  559. /* Round down. */
  560. bulklen = (len - residue) / chunksize * chunksize;
  561. ret = dediprog_spi_bulk_write(flash, buf + residue, chunksize, start + residue, bulklen, dedi_spi_cmd);
  562. if (ret) {
  563. dediprog_set_leds(LED_ERROR);
  564. return ret;
  565. }
  566. len -= residue + bulklen;
  567. if (len) {
  568. msg_pdbg("Slow write for partial block from 0x%x, length 0x%x\n",
  569. start, len);
  570. ret = spi_write_chunked(flash, buf + residue + bulklen,
  571. start + residue + bulklen, len, 12);
  572. if (ret) {
  573. dediprog_set_leds(LED_ERROR);
  574. return ret;
  575. }
  576. }
  577. dediprog_set_leds(LED_PASS);
  578. return 0;
  579. }
  580. static int dediprog_spi_write_256(struct flashctx *flash, const uint8_t *buf, unsigned int start, unsigned int len)
  581. {
  582. return dediprog_spi_write(flash, buf, start, len, WRITE_MODE_PAGE_PGM);
  583. }
  584. static int dediprog_spi_write_aai(struct flashctx *flash, const uint8_t *buf, unsigned int start, unsigned int len)
  585. {
  586. return dediprog_spi_write(flash, buf, start, len, WRITE_MODE_2B_AAI);
  587. }
  588. static int dediprog_spi_send_command(struct flashctx *flash,
  589. unsigned int writecnt,
  590. unsigned int readcnt,
  591. const unsigned char *writearr,
  592. unsigned char *readarr)
  593. {
  594. int ret;
  595. msg_pspew("%s, writecnt=%i, readcnt=%i\n", __func__, writecnt, readcnt);
  596. if (writecnt > flash->mst->spi.max_data_write) {
  597. msg_perr("Invalid writecnt=%i, aborting.\n", writecnt);
  598. return 1;
  599. }
  600. if (readcnt > flash->mst->spi.max_data_read) {
  601. msg_perr("Invalid readcnt=%i, aborting.\n", readcnt);
  602. return 1;
  603. }
  604. unsigned int idx, value;
  605. /* New protocol has options and timeout combined as value while the old one used the value field for
  606. * timeout and the index field for options. */
  607. if (is_new_prot()) {
  608. idx = 0;
  609. value = readcnt ? 0x1 : 0x0; // Indicate if we require a read
  610. } else {
  611. idx = readcnt ? 0x1 : 0x0; // Indicate if we require a read
  612. value = 0;
  613. }
  614. ret = dediprog_write(CMD_TRANSCEIVE, value, idx, writearr, writecnt);
  615. if (ret != writecnt) {
  616. msg_perr("Send SPI failed, expected %i, got %i %s!\n",
  617. writecnt, ret, libusb_error_name(ret));
  618. return 1;
  619. }
  620. if (readcnt == 0) // If we don't require a response, we are done here
  621. return 0;
  622. /* The specifications do state the possibility to set a timeout for transceive transactions.
  623. * Apparently the "timeout" is a delay, and you can use long delays to accelerate writing - in case you
  624. * can predict the time needed by the previous command or so (untested). In any case, using this
  625. * "feature" to set sane-looking timouts for the read below will completely trash performance with
  626. * SF600 and/or firmwares >= 6.0 while they seem to be benign on SF100 with firmwares <= 5.5.2. *shrug*
  627. *
  628. * The specification also uses only 0 in its examples, so the lesson to learn here:
  629. * "Never trust the description of an interface in the documentation but use the example code and pray."
  630. const uint8_t read_timeout = 10 + readcnt/512;
  631. if (is_new_prot()) {
  632. idx = 0;
  633. value = min(read_timeout, 0xFF) | (0 << 8) ; // Timeout in lower byte, option in upper byte
  634. } else {
  635. idx = (0 & 0xFF); // Lower byte is option (0x01 = require SR, 0x02 keep CS low)
  636. value = min(read_timeout, 0xFF); // Possibly two bytes but we play safe here
  637. }
  638. ret = dediprog_read(CMD_TRANSCEIVE, value, idx, readarr, readcnt);
  639. */
  640. ret = dediprog_read(CMD_TRANSCEIVE, 0, 0, readarr, readcnt);
  641. if (ret != readcnt) {
  642. msg_perr("Receive SPI failed, expected %i, got %i %s!\n", readcnt, ret, libusb_error_name(ret));
  643. return 1;
  644. }
  645. return 0;
  646. }
  647. static int dediprog_check_devicestring(void)
  648. {
  649. int ret;
  650. char buf[0x11];
  651. /* Command Receive Device String. */
  652. ret = dediprog_read(CMD_READ_PROG_INFO, 0, 0, (uint8_t *)buf, 0x10);
  653. if (ret != 0x10) {
  654. msg_perr("Incomplete/failed Command Receive Device String!\n");
  655. return 1;
  656. }
  657. buf[0x10] = '\0';
  658. msg_pdbg("Found a %s\n", buf);
  659. if (memcmp(buf, "SF100", 0x5) == 0)
  660. dediprog_devicetype = DEV_SF100;
  661. else if (memcmp(buf, "SF600", 0x5) == 0)
  662. dediprog_devicetype = DEV_SF600;
  663. else {
  664. msg_perr("Device not a SF100 or SF600!\n");
  665. return 1;
  666. }
  667. int sfnum;
  668. int fw[3];
  669. if (sscanf(buf, "SF%d V:%d.%d.%d ", &sfnum, &fw[0], &fw[1], &fw[2]) != 4 ||
  670. sfnum != dediprog_devicetype) {
  671. msg_perr("Unexpected firmware version string '%s'\n", buf);
  672. return 1;
  673. }
  674. /* Only these major versions were tested. */
  675. if (fw[0] < 2 || fw[0] > 7) {
  676. msg_perr("Unexpected firmware version %d.%d.%d!\n", fw[0], fw[1], fw[2]);
  677. return 1;
  678. }
  679. dediprog_firmwareversion = FIRMWARE_VERSION(fw[0], fw[1], fw[2]);
  680. return 0;
  681. }
  682. /*
  683. * This command presumably sets the voltage for the SF100 itself (not the
  684. * SPI flash). Only use this command with firmware older than V6.0.0. Newer
  685. * (including all SF600s) do not support it.
  686. */
  687. /* This command presumably sets the voltage for the SF100 itself (not the SPI flash).
  688. * Only use dediprog_set_voltage on SF100 programmers with firmware older
  689. * than V6.0.0. Newer programmers (including all SF600s) do not support it. */
  690. static int dediprog_set_voltage(void)
  691. {
  692. unsigned char buf[1] = {0};
  693. int ret = libusb_control_transfer(dediprog_handle, REQTYPE_OTHER_IN, CMD_SET_VOLTAGE, 0x0, 0x0,
  694. buf, 0x1, DEFAULT_TIMEOUT);
  695. if (ret < 0) {
  696. msg_perr("Command Set Voltage failed (%s)!\n", libusb_error_name(ret));
  697. return 1;
  698. }
  699. if ((ret != 1) || (buf[0] != 0x6f)) {
  700. msg_perr("Unexpected response to init!\n");
  701. return 1;
  702. }
  703. return 0;
  704. }
  705. static int dediprog_standalone_mode(void)
  706. {
  707. int ret;
  708. if (dediprog_devicetype != DEV_SF600)
  709. return 0;
  710. msg_pdbg2("Disabling standalone mode.\n");
  711. ret = dediprog_write(CMD_SET_STANDALONE, LEAVE_STANDALONE_MODE, 0, NULL, 0);
  712. if (ret) {
  713. msg_perr("Failed to disable standalone mode: %s\n", libusb_error_name(ret));
  714. return 1;
  715. }
  716. return 0;
  717. }
  718. #if 0
  719. /* Something.
  720. * Present in eng_detect_blink.log with firmware 3.1.8
  721. * Always preceded by Command Receive Device String
  722. */
  723. static int dediprog_command_b(void)
  724. {
  725. int ret;
  726. char buf[0x3];
  727. ret = usb_control_msg(dediprog_handle, REQTYPE_OTHER_IN, 0x7, 0x0, 0xef00,
  728. buf, 0x3, DEFAULT_TIMEOUT);
  729. if (ret < 0) {
  730. msg_perr("Command B failed (%s)!\n", libusb_error_name(ret));
  731. return 1;
  732. }
  733. if ((ret != 0x3) || (buf[0] != 0xff) || (buf[1] != 0xff) ||
  734. (buf[2] != 0xff)) {
  735. msg_perr("Unexpected response to Command B!\n");
  736. return 1;
  737. }
  738. return 0;
  739. }
  740. #endif
  741. static int set_target_flash(enum dediprog_target target)
  742. {
  743. int ret = dediprog_write(CMD_SET_TARGET, target, 0, NULL, 0);
  744. if (ret != 0) {
  745. msg_perr("set_target_flash failed (%s)!\n", libusb_error_name(ret));
  746. return 1;
  747. }
  748. return 0;
  749. }
  750. #if 0
  751. /* Returns true if the button is currently pressed. */
  752. static bool dediprog_get_button(void)
  753. {
  754. char buf[1];
  755. int ret = usb_control_msg(dediprog_handle, REQTYPE_EP_IN, CMD_GET_BUTTON, 0, 0,
  756. buf, 0x1, DEFAULT_TIMEOUT);
  757. if (ret != 0) {
  758. msg_perr("Could not get button state (%s)!\n", libusb_error_name(ret));
  759. return 1;
  760. }
  761. return buf[0] != 1;
  762. }
  763. #endif
  764. static int parse_voltage(char *voltage)
  765. {
  766. char *tmp = NULL;
  767. int i;
  768. int millivolt = 0, fraction = 0;
  769. if (!voltage || !strlen(voltage)) {
  770. msg_perr("Empty voltage= specified.\n");
  771. return -1;
  772. }
  773. millivolt = (int)strtol(voltage, &tmp, 0);
  774. voltage = tmp;
  775. /* Handle "," and "." as decimal point. Everything after it is assumed
  776. * to be in decimal notation.
  777. */
  778. if ((*voltage == '.') || (*voltage == ',')) {
  779. voltage++;
  780. for (i = 0; i < 3; i++) {
  781. fraction *= 10;
  782. /* Don't advance if the current character is invalid,
  783. * but continue multiplying.
  784. */
  785. if ((*voltage < '0') || (*voltage > '9'))
  786. continue;
  787. fraction += *voltage - '0';
  788. voltage++;
  789. }
  790. /* Throw away remaining digits. */
  791. voltage += strspn(voltage, "0123456789");
  792. }
  793. /* The remaining string must be empty or "mV" or "V". */
  794. tolower_string(voltage);
  795. /* No unit or "V". */
  796. if ((*voltage == '\0') || !strncmp(voltage, "v", 1)) {
  797. millivolt *= 1000;
  798. millivolt += fraction;
  799. } else if (!strncmp(voltage, "mv", 2) ||
  800. !strncmp(voltage, "milliv", 6)) {
  801. /* No adjustment. fraction is discarded. */
  802. } else {
  803. /* Garbage at the end of the string. */
  804. msg_perr("Garbage voltage= specified.\n");
  805. return -1;
  806. }
  807. return millivolt;
  808. }
  809. static const struct spi_master spi_master_dediprog = {
  810. .type = SPI_CONTROLLER_DEDIPROG,
  811. .max_data_read = 16, /* 18 seems to work fine as well, but 19 times out sometimes with FW 5.15. */
  812. .max_data_write = 16,
  813. .command = dediprog_spi_send_command,
  814. .multicommand = default_spi_send_multicommand,
  815. .read = dediprog_spi_read,
  816. .write_256 = dediprog_spi_write_256,
  817. .write_aai = dediprog_spi_write_aai,
  818. };
  819. static int dediprog_shutdown(void *data)
  820. {
  821. dediprog_firmwareversion = FIRMWARE_VERSION(0, 0, 0);
  822. dediprog_devicetype = DEV_UNKNOWN;
  823. /* URB 28. Command Set SPI Voltage to 0. */
  824. if (dediprog_set_spi_voltage(0x0))
  825. return 1;
  826. if (libusb_release_interface(dediprog_handle, 0)) {
  827. msg_perr("Could not release USB interface!\n");
  828. return 1;
  829. }
  830. libusb_close(dediprog_handle);
  831. libusb_exit(usb_ctx);
  832. return 0;
  833. }
  834. int dediprog_init(void)
  835. {
  836. char *voltage, *device, *spispeed, *target_str;
  837. int spispeed_idx = 1;
  838. int millivolt = 3500;
  839. long usedevice = 0;
  840. long target = 1;
  841. int i, ret;
  842. spispeed = extract_programmer_param("spispeed");
  843. if (spispeed) {
  844. for (i = 0; spispeeds[i].name; ++i) {
  845. if (!strcasecmp(spispeeds[i].name, spispeed)) {
  846. spispeed_idx = i;
  847. break;
  848. }
  849. }
  850. if (!spispeeds[i].name) {
  851. msg_perr("Error: Invalid spispeed value: '%s'.\n", spispeed);
  852. free(spispeed);
  853. return 1;
  854. }
  855. free(spispeed);
  856. }
  857. voltage = extract_programmer_param("voltage");
  858. if (voltage) {
  859. millivolt = parse_voltage(voltage);
  860. free(voltage);
  861. if (millivolt < 0)
  862. return 1;
  863. msg_pinfo("Setting voltage to %i mV\n", millivolt);
  864. }
  865. device = extract_programmer_param("device");
  866. if (device) {
  867. char *dev_suffix;
  868. errno = 0;
  869. usedevice = strtol(device, &dev_suffix, 10);
  870. if (errno != 0 || device == dev_suffix) {
  871. msg_perr("Error: Could not convert 'device'.\n");
  872. free(device);
  873. return 1;
  874. }
  875. if (usedevice < 0 || usedevice > UINT_MAX) {
  876. msg_perr("Error: Value for 'device' is out of range.\n");
  877. free(device);
  878. return 1;
  879. }
  880. if (strlen(dev_suffix) > 0) {
  881. msg_perr("Error: Garbage following 'device' value.\n");
  882. free(device);
  883. return 1;
  884. }
  885. msg_pinfo("Using device %li.\n", usedevice);
  886. }
  887. free(device);
  888. target_str = extract_programmer_param("target");
  889. if (target_str) {
  890. char *target_suffix;
  891. errno = 0;
  892. target = strtol(target_str, &target_suffix, 10);
  893. if (errno != 0 || target_str == target_suffix) {
  894. msg_perr("Error: Could not convert 'target'.\n");
  895. free(target_str);
  896. return 1;
  897. }
  898. if (target < 1 || target > 2) {
  899. msg_perr("Error: Value for 'target' is out of range.\n");
  900. free(target_str);
  901. return 1;
  902. }
  903. if (strlen(target_suffix) > 0) {
  904. msg_perr("Error: Garbage following 'target' value.\n");
  905. free(target_str);
  906. return 1;
  907. }
  908. msg_pinfo("Using target %li.\n", target);
  909. }
  910. free(target_str);
  911. /* Here comes the USB stuff. */
  912. libusb_init(&usb_ctx);
  913. if (!usb_ctx) {
  914. msg_perr("Could not initialize libusb!\n");
  915. return 1;
  916. }
  917. const uint16_t vid = devs_dediprog[0].vendor_id;
  918. const uint16_t pid = devs_dediprog[0].device_id;
  919. dediprog_handle = get_device_by_vid_pid_number(vid, pid, (unsigned int) usedevice);
  920. if (!dediprog_handle) {
  921. msg_perr("Could not find a Dediprog programmer on USB.\n");
  922. libusb_exit(usb_ctx);
  923. return 1;
  924. }
  925. ret = libusb_set_configuration(dediprog_handle, 1);
  926. if (ret != 0) {
  927. msg_perr("Could not set USB device configuration: %i %s\n", ret, libusb_error_name(ret));
  928. libusb_close(dediprog_handle);
  929. libusb_exit(usb_ctx);
  930. return 1;
  931. }
  932. ret = libusb_claim_interface(dediprog_handle, 0);
  933. if (ret < 0) {
  934. msg_perr("Could not claim USB device interface %i: %i %s\n", 0, ret, libusb_error_name(ret));
  935. libusb_close(dediprog_handle);
  936. libusb_exit(usb_ctx);
  937. return 1;
  938. }
  939. if (register_shutdown(dediprog_shutdown, NULL))
  940. return 1;
  941. /* Try reading the devicestring. If that fails and the device is old (FW < 6.0.0, which we can not know)
  942. * then we need to try the "set voltage" command and then attempt to read the devicestring again. */
  943. if (dediprog_check_devicestring()) {
  944. if (dediprog_set_voltage())
  945. return 1;
  946. if (dediprog_check_devicestring())
  947. return 1;
  948. }
  949. /* SF100 only has 1 endpoint for in/out, SF600 uses two separate endpoints instead. */
  950. dediprog_in_endpoint = 2;
  951. if (dediprog_devicetype == DEV_SF100)
  952. dediprog_out_endpoint = 2;
  953. else
  954. dediprog_out_endpoint = 1;
  955. /* Set all possible LEDs as soon as possible to indicate activity.
  956. * Because knowing the firmware version is required to set the LEDs correctly we need to this after
  957. * dediprog_check_devicestring() has queried the device and set dediprog_firmwareversion. */
  958. dediprog_set_leds(LED_ALL);
  959. /* Select target/socket, frequency and VCC. */
  960. if (set_target_flash(FLASH_TYPE_APPLICATION_FLASH_1) ||
  961. dediprog_set_spi_speed(spispeed_idx) ||
  962. dediprog_set_spi_voltage(millivolt)) {
  963. dediprog_set_leds(LED_ERROR);
  964. return 1;
  965. }
  966. if (dediprog_standalone_mode())
  967. return 1;
  968. if (register_spi_master(&spi_master_dediprog) || dediprog_set_leds(LED_NONE))
  969. return 1;
  970. return 0;
  971. }