+/* limitations:
+ * - bytes must be multiple of 64
+ * - bytes must be less than 16k
+ * - must perform even number of reads (firmware bug?) */
+static int read_rom_block(struct usb_dev_handle *dev, u32 addr, void *buffer, int bytes)
+{
+ dev_cmd_t cmd;
+ int ret;
+
+ prepare_cmd(&cmd, CMD_SEC_READ);
+ cmd.rom_rw.addrb2 = addr >> (16 + 1);
+ cmd.rom_rw.addrb1 = addr >> (8 + 1);
+ cmd.rom_rw.addrb0 = addr >> 1;
+ cmd.rom_rw.packets = bytes / 64;
+
+ ret = write_cmd(dev, &cmd);
+ if (ret < 0)
+ return ret;
+
+ bytes &= ~63;
+ ret = read_data(dev, buffer, bytes);
+ if (ret < 0)
+ return ret;
+ if (ret != bytes)
+ fprintf(stderr, "read_rom_block warning: read only %d/%d bytes\n", ret, bytes);
+
+ return ret;
+}
+
+#define READ_BLK_SIZE (0x2000) /* 8K */
+
+static int read_rom(struct usb_dev_handle *dev, u32 addr, void *buffer, int bytes)
+{
+ int total_bytes = bytes;
+ u8 *buff = buffer;
+ u8 dummy[64 * 4];
+ int count, ret;
+
+ if (addr & 1)
+ fprintf(stderr, "read_rom: can't handle odd address %06x, "
+ "LSb will be ignored\n", addr);
+ if (bytes & 63)
+ fprintf(stderr, "read_rom: byte count must be multiple of 64, "
+ "last %d bytes will not be read\n", bytes & 63);
+
+ printf("reading flash ROM...\n");
+
+ /* read in blocks */
+ for (count = 0; bytes >= READ_BLK_SIZE; count++) {
+ print_progress(buff - (u8 *)buffer, total_bytes);
+
+ ret = read_rom_block(dev, addr, buff, READ_BLK_SIZE);
+ if (ret < 0)
+ return ret;
+ buff += READ_BLK_SIZE;
+ addr += READ_BLK_SIZE;
+ bytes -= READ_BLK_SIZE;
+ }
+ print_progress(buff - (u8 *)buffer, total_bytes);
+
+ ret = 0;
+ if (bytes != 0) {
+ ret = read_rom_block(dev, addr, buff, bytes);
+ count++;
+ print_progress(total_bytes, total_bytes);
+ }
+
+ if (count & 1)
+ /* work around read_rom_block() limitation 3 */
+ read_rom_block(dev, 0, dummy, sizeof(dummy));
+
+ printf("\n");
+ return ret;
+}
+