3 /* (C) 2010 by Harald Welte <laforge@gnumonks.org>
4 * (C) 2010 by Holger Hans Peter Freyther <zecke@selfish.org>
5 * (C) 2010 by Steve Markgraf <steve@steve-m.de>
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.
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.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
34 #include <sys/ioctl.h>
35 #include <sys/types.h>
36 #include <sys/socket.h>
42 #include <osmocore/linuxlist.h>
43 #include <osmocore/select.h>
44 #include <osmocore/talloc.h>
45 #include <osmocore/timer.h>
47 #include <arpa/inet.h>
49 #define MODEM_BAUDRATE B115200
50 #define MAX_DNLOAD_SIZE 0xFFFF
51 #define MAX_HDR_SIZE 128
52 #define MAGIC_OFFSET 0x3be2
54 #define BEACON_INTERVAL 50000
55 #define ROMLOAD_INIT_BAUDRATE B19200
56 #define ROMLOAD_DL_BAUDRATE B115200
57 #define ROMLOAD_BLOCK_HDR_LEN 10
58 #define ROMLOAD_ADDRESS 0x820000
60 #define MTK_INIT_BAUDRATE B19200
61 #define MTK_ADDRESS 0x40001400
62 #define MTK_BLOCK_SIZE 1024
64 struct tool_server *tool_server_for_dlci[256];
67 * a connection from some other tool
69 struct tool_connection {
70 struct tool_server *server;
71 struct llist_head entry;
81 struct llist_head connections;
92 WAITING_IDENTIFICATION,
112 MTK_WAIT_BRANCH_CMD_ACK,
113 MTK_WAIT_BRANCH_ADDR_ACK,
128 enum dnload_state state;
129 enum romload_state romload_state;
130 enum mtk_state mtk_state;
131 enum dnload_mode mode;
132 struct bsc_fd serial_fd;
134 char *chainload_filename;
141 /* data to be downloaded */
147 /* romload: block to be downloaded */
150 uint8_t block_number;
151 uint16_t block_payload_size;
152 int romload_dl_checksum;
154 uint8_t load_address[4];
156 uint8_t mtk_send_size[4];
160 struct tool_server layer2_server;
161 struct tool_server loader_server;
165 static struct dnload dnload;
166 static struct timer_list tick_timer;
168 /* Compal ramloader specific */
169 static const uint8_t phone_prompt1[] = { 0x1b, 0xf6, 0x02, 0x00, 0x41, 0x01, 0x40 };
170 static const uint8_t dnload_cmd[] = { 0x1b, 0xf6, 0x02, 0x00, 0x52, 0x01, 0x53 };
171 static const uint8_t phone_prompt2[] = { 0x1b, 0xf6, 0x02, 0x00, 0x41, 0x02, 0x43 };
172 static const uint8_t phone_ack[] = { 0x1b, 0xf6, 0x02, 0x00, 0x41, 0x03, 0x42 };
173 static const uint8_t phone_nack_magic[]= { 0x1b, 0xf6, 0x02, 0x00, 0x41, 0x03, 0x57 };
174 static const uint8_t phone_nack[] = { 0x1b, 0xf6, 0x02, 0x00, 0x45, 0x53, 0x16 };
175 static const uint8_t ftmtool[] = { 0x66, 0x74, 0x6d, 0x74, 0x6f, 0x6f, 0x6c };
176 static const uint8_t phone_magic[] = { 0x31, 0x30, 0x30, 0x33 }; /* "1003" */
178 /* The C123 has a hard-coded check inside the ramloader that requires the
179 * following bytes to be always the first four bytes of the image */
180 static const uint8_t data_hdr_c123[] = { 0xee, 0x4c, 0x9f, 0x63 };
182 /* The C155 doesn't have some strange restriction on what the first four bytes
183 * have to be, but it starts the ramloader in THUMB mode. We use the following
184 * four bytes to switch back to ARM mode:
186 800102: 46c0 nop ; (mov r8, r8)
188 static const uint8_t data_hdr_c155[] = { 0x78, 0x47, 0xc0, 0x46 };
190 /* Calypso romloader specific */
191 static const uint8_t romload_ident_cmd[] = { 0x3c, 0x69 }; /* <i */
192 static const uint8_t romload_abort_cmd[] = { 0x3c, 0x61 }; /* <a */
193 static const uint8_t romload_write_cmd[] = { 0x3c, 0x77 }; /* <w */
194 static const uint8_t romload_checksum_cmd[] = { 0x3c, 0x63 }; /* <c */
195 static const uint8_t romload_branch_cmd[] = { 0x3c, 0x62 }; /* <b */
196 static const uint8_t romload_ident_ack[] = { 0x3e, 0x69 }; /* >i */
197 static const uint8_t romload_param_ack[] = { 0x3e, 0x70 }; /* >p */
198 static const uint8_t romload_param_nack[] = { 0x3e, 0x50 }; /* >P */
199 static const uint8_t romload_block_ack[] = { 0x3e, 0x77 }; /* >w */
200 static const uint8_t romload_block_nack[] = { 0x3e, 0x57 }; /* >W */
201 static const uint8_t romload_checksum_ack[] = { 0x3e, 0x63 }; /* >c */
202 static const uint8_t romload_checksum_nack[] = { 0x3e, 0x43 }; /* >C */
203 static const uint8_t romload_branch_ack[] = { 0x3e, 0x62 }; /* >b */
204 static const uint8_t romload_branch_nack[] = { 0x3e, 0x42 }; /* >B */
206 /* romload_param: {"<p", uint8_t baudrate, uint8_t dpll, uint16_t memory_config,
207 * uint8_t strobe_af, uint32_t uart_timeout} */
209 static const uint8_t romload_param[] = { 0x3c, 0x70, 0x00, 0x00, 0x00, 0x04,
210 0x00, 0x00, 0x00, 0x00, 0x00 };
212 /* MTK romloader specific */
213 static const uint8_t mtk_init_cmd[] = { 0xa0, 0x0a, 0x50, 0x05 };
214 static const uint8_t mtk_init_resp[] = { 0x5f, 0xf5, 0xaf, 0xfa };
215 static const uint8_t mtk_command[] = { 0xa1, 0xa2, 0xa4, 0xa8 };
217 /* FIXME: this routine is more or less what openbsc/src/rs232:rs232_setup()
218 * does, we should move it to libosmocore at some point */
219 static int serial_init(const char *serial_port)
221 int rc, serial_fd, v24;
224 serial_fd = open(serial_port, O_RDWR | O_NOCTTY | O_NDELAY);
226 perror("cannot open serial port");
230 //fcntl(serial_fd, F_SETFL, 0);
232 /* Configure serial interface */
233 rc = tcgetattr(serial_fd, &tio);
235 perror("tcgetattr()");
238 cfsetispeed(&tio, MODEM_BAUDRATE);
239 cfsetospeed(&tio, MODEM_BAUDRATE);
240 tio.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
241 tio.c_cflag |= (CREAD | CLOCAL | CS8);
242 tio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
243 tio.c_iflag |= (INPCK | ISTRIP);
244 tio.c_iflag &= ~(ISTRIP | IXON | IXOFF | IGNBRK | INLCR | ICRNL | IGNCR);
245 tio.c_oflag &= ~(OPOST | ONLCR);
246 rc = tcsetattr(serial_fd, TCSANOW, &tio);
248 perror("tcsetattr()");
252 /* set ready to read/write */
253 v24 = TIOCM_DTR | TIOCM_RTS;
254 rc = ioctl(serial_fd, TIOCMBIS, &v24);
256 perror("ioctl(TIOCMBIS)");
263 static int serial_set_baudrate(speed_t baudrate)
268 rc = tcgetattr(dnload.serial_fd.fd, &tio);
270 perror("tcgetattr()");
273 cfsetispeed(&tio, baudrate);
274 cfsetospeed(&tio, baudrate);
276 rc = tcsetattr(dnload.serial_fd.fd, TCSANOW, &tio);
280 static void beacon_timer_cb(void *p)
284 if (dnload.romload_state == WAITING_IDENTIFICATION) {
285 printf("Sending Calypso romloader beacon...\n");
286 rc = write(dnload.serial_fd.fd, romload_ident_cmd,
287 sizeof(romload_ident_cmd));
289 if (!(rc == sizeof(romload_ident_cmd)))
290 printf("Error sending identification beacon\n");
292 bsc_schedule_timer(p, 0, BEACON_INTERVAL);
296 static void mtk_timer_cb(void *p)
300 if (dnload.mtk_state == MTK_INIT_1) {
301 printf("Sending MTK romloader beacon...\n");
302 rc = write(dnload.serial_fd.fd, &mtk_init_cmd[0], 1);
305 printf("Error sending identification beacon\n");
307 bsc_schedule_timer(p, 0, BEACON_INTERVAL);
311 /* Read the to-be-downloaded file, prepend header and length, append XOR sum */
312 int read_file(const char *filename)
316 const uint8_t *hdr = NULL;
322 uint8_t running_xor = 0x02;
324 fd = open(filename, O_RDONLY);
326 perror("opening file");
331 if (st.st_size > MAX_DNLOAD_SIZE) {
332 fprintf(stderr, "The maximum file size is 64kBytes (%u bytes)\n",
342 if (dnload.mode == MODE_C140 || dnload.mode == MODE_C140xor) {
343 if (st.st_size < (MAGIC_OFFSET + sizeof(phone_magic)))
344 payload_size = MAGIC_OFFSET + sizeof(phone_magic);
346 printf("\nThe filesize is larger than 15kb, code on "
347 "the magic address will be overwritten!\nUse "
348 "loader.bin and upload the application with "
349 "osmoload instead!\n\n");
350 payload_size = st.st_size;
353 payload_size = st.st_size;
355 dnload.data = malloc(MAX_HDR_SIZE + payload_size);
359 fprintf(stderr, "No memory\n");
363 /* copy in the header, if any */
364 switch (dnload.mode) {
367 hdr_len = sizeof(data_hdr_c155);
374 hdr_len = sizeof(data_hdr_c123);
383 memcpy(dnload.data, hdr, hdr_len);
385 /* 2 bytes for length + header */
386 file_data = dnload.data + 2 + hdr_len;
388 /* write the length, keep running XOR */
389 tot_len = hdr_len + payload_size;
390 nibble = tot_len >> 8;
391 dnload.data[0] = nibble;
392 running_xor ^= nibble;
393 nibble = tot_len & 0xff;
394 dnload.data[1] = nibble;
395 running_xor ^= nibble;
397 if (hdr_len && hdr) {
398 memcpy(dnload.data+2, hdr, hdr_len);
400 for (i = 0; i < hdr_len; i++)
401 running_xor ^= hdr[i];
404 rc = read(fd, file_data, st.st_size);
406 perror("error reading file\n");
412 if (rc < st.st_size) {
416 fprintf(stderr, "Short read of file (%d < %d)\n",
417 rc, (int)st.st_size);
423 dnload.data_len = (file_data+payload_size) - dnload.data;
425 /* fill memory between data end and magic, add magic */
426 if(dnload.mode == MODE_C140 || dnload.mode == MODE_C140xor) {
427 if (st.st_size < MAGIC_OFFSET)
428 memset(file_data + st.st_size, 0x00,
429 payload_size - st.st_size);
430 memcpy(dnload.data + MAGIC_OFFSET, phone_magic,
431 sizeof(phone_magic));
434 /* calculate XOR sum */
435 for (i = 0; i < payload_size; i++)
436 running_xor ^= file_data[i];
438 dnload.data[dnload.data_len++] = running_xor;
440 /* initialize write pointer to start of data */
441 dnload.write_ptr = dnload.data;
443 printf("read_file(%s): file_size=%u, hdr_len=%u, dnload_len=%u\n",
444 filename, (int)st.st_size, hdr_len, dnload.data_len);
449 static void hexdump(const uint8_t *data, unsigned int len)
453 for (n=0; n < len; n++)
454 printf("%02x ", data[n]);
456 for (n=0; n < len; n++)
457 if (isprint(data[n]))
464 static int romload_prepare_block(void)
468 int block_checksum = 5;
472 uint32_t block_address;
474 dnload.block_len = ROMLOAD_BLOCK_HDR_LEN + dnload.block_payload_size;
476 /* if first block, allocate memory */
477 if (!dnload.block_number) {
478 dnload.block = malloc(dnload.block_len);
480 fprintf(stderr, "No memory\n");
483 dnload.romload_dl_checksum = 0;
484 /* initialize write pointer to start of data */
485 dnload.write_ptr = dnload.data;
488 block_address = ROMLOAD_ADDRESS +
489 (dnload.block_number * dnload.block_payload_size);
491 /* prepare our block header (10 bytes) */
492 memcpy(dnload.block, romload_write_cmd, sizeof(romload_write_cmd));
493 dnload.block[2] = 0x01; /* block index */
494 /* should normally be the block number, but hangs when sending !0x01 */
495 dnload.block[3] = 0x01; /* dnload.block_number+1 */
496 dnload.block[4] = (dnload.block_payload_size >> 8) & 0xff;
497 dnload.block[5] = dnload.block_payload_size & 0xff;
498 dnload.block[6] = (block_address >> 24) & 0xff;
499 dnload.block[7] = (block_address >> 16) & 0xff;
500 dnload.block[8] = (block_address >> 8) & 0xff;
501 dnload.block[9] = block_address & 0xff;
503 block_data = dnload.block + ROMLOAD_BLOCK_HDR_LEN;
504 dnload.write_ptr = dnload.data + 2 +
505 (dnload.block_payload_size * dnload.block_number);
507 remaining_bytes = dnload.data_len - 3 -
508 (dnload.block_payload_size * dnload.block_number);
510 memcpy(block_data, dnload.write_ptr, dnload.block_payload_size);
512 if (remaining_bytes <= dnload.block_payload_size) {
513 fill_bytes = (dnload.block_payload_size - remaining_bytes);
514 printf("Preparing the last block, filling %i bytes,",
516 memset(block_data + remaining_bytes, 0x00, fill_bytes);
517 dnload.romload_state = SENDING_LAST_BLOCK;
519 dnload.romload_state = SENDING_BLOCKS;
520 printf("Preparing block %i,", dnload.block_number+1);
523 /* block checksum is lsb of ~(5 + block_size_lsb + all bytes of
524 * block_address + all data bytes) */
525 for (i = 5; i < ROMLOAD_BLOCK_HDR_LEN + dnload.block_payload_size; i++)
526 block_checksum += dnload.block[i];
528 /* checksum is lsb of ~(sum of LSBs of all block checksums) */
529 printf(" block checksum is 0x%02x \n", ~(block_checksum) & 0xff);
530 dnload.romload_dl_checksum += ~(block_checksum) & 0xff;
532 /* initialize block pointer to start of block */
533 dnload.block_ptr = dnload.block;
535 dnload.block_number++;
536 dnload.serial_fd.when = BSC_FD_READ | BSC_FD_WRITE;
540 static int mtk_prepare_block(void)
547 uint8_t tmp_byteswap;
550 dnload.block_len = MTK_BLOCK_SIZE;
551 dnload.echo_bytecount = 0;
553 /* if first block, allocate memory */
554 if (!dnload.block_number) {
555 dnload.block = malloc(dnload.block_len);
557 fprintf(stderr, "No memory\n");
561 /* calculate the number of blocks we need to send */
562 dnload.block_count = (dnload.data_len-3) / MTK_BLOCK_SIZE;
563 /* add one more block if no multiple of blocksize */
564 if((dnload.data_len-3) % MTK_BLOCK_SIZE)
565 dnload.block_count++;
567 /* divide by 2, since we have to tell the mtk loader the size
568 * as count of uint16 (odd transfer sizes are not possible) */
569 tmp_size = (dnload.block_count * MTK_BLOCK_SIZE)/2;
570 dnload.mtk_send_size[0] = (tmp_size >> 24) & 0xff;
571 dnload.mtk_send_size[1] = (tmp_size >> 16) & 0xff;
572 dnload.mtk_send_size[2] = (tmp_size >> 8) & 0xff;
573 dnload.mtk_send_size[3] = tmp_size & 0xff;
575 /* initialize write pointer to start of data */
576 dnload.write_ptr = dnload.data;
579 block_data = dnload.block;
580 dnload.write_ptr = dnload.data + 2 +
581 (dnload.block_len * dnload.block_number);
583 remaining_bytes = dnload.data_len - 3 -
584 (dnload.block_len * dnload.block_number);
586 memcpy(block_data, dnload.write_ptr, MTK_BLOCK_SIZE);
588 if (remaining_bytes <= MTK_BLOCK_SIZE) {
589 fill_bytes = (MTK_BLOCK_SIZE - remaining_bytes);
590 printf("Preparing the last block, filling %i bytes\n",
592 memset(block_data + remaining_bytes, 0x00, fill_bytes);
593 dnload.romload_state = SENDING_LAST_BLOCK;
595 dnload.romload_state = SENDING_BLOCKS;
596 printf("Preparing block %i\n", dnload.block_number+1);
599 /* for the mtk romloader we need to swap MSB <-> LSB */
600 for (i = 0; i < dnload.block_len; i += 2) {
601 tmp_byteswap = dnload.block[i];
602 dnload.block[i] = dnload.block[i+1];
603 dnload.block[i+1] = tmp_byteswap;
606 /* initialize block pointer to start of block */
607 dnload.block_ptr = dnload.block;
609 dnload.block_number++;
613 static int handle_write_block(void)
615 int bytes_left, write_len, rc;
617 printf("handle_write_block(): ");
619 if (dnload.block_ptr >= dnload.block + dnload.block_len) {
620 printf("Block %i finished\n", dnload.block_number);
621 dnload.write_ptr = dnload.data;
622 dnload.serial_fd.when &= ~BSC_FD_WRITE;
623 if (dnload.romload_state == SENDING_LAST_BLOCK) {
624 dnload.romload_state = LAST_BLOCK_SENT;
625 printf("Finished, sent %i blocks in total\n",
626 dnload.block_number);
628 dnload.romload_state = WAITING_BLOCK_ACK;
634 /* try to write a maximum of block_len bytes */
635 bytes_left = (dnload.block + dnload.block_len) - dnload.block_ptr;
636 write_len = dnload.block_len;
637 if (bytes_left < dnload.block_len)
638 write_len = bytes_left;
640 rc = write(dnload.serial_fd.fd, dnload.block_ptr, write_len);
642 perror("Error during write");
646 dnload.block_ptr += rc;
648 printf("%u bytes (%tu/%u)\n", rc, dnload.block_ptr - dnload.block,
654 #define WRITE_BLOCK 4096
656 static int handle_write_dnload(void)
658 int bytes_left, write_len, rc;
659 uint8_t xor_init = 0x02;
661 printf("handle_write(): ");
662 if (dnload.write_ptr == dnload.data) {
663 /* no bytes have been transferred yet */
664 switch (dnload.mode) {
668 rc = write(dnload.serial_fd.fd, &xor_init, 1);
673 } else if (dnload.write_ptr >= dnload.data + dnload.data_len) {
674 printf("finished\n");
675 dnload.write_ptr = dnload.data;
676 dnload.serial_fd.when &= ~BSC_FD_WRITE;
680 /* try to write a maximum of WRITE_BLOCK bytes */
681 bytes_left = (dnload.data + dnload.data_len) - dnload.write_ptr;
682 write_len = WRITE_BLOCK;
683 if (bytes_left < WRITE_BLOCK)
684 write_len = bytes_left;
686 rc = write(dnload.serial_fd.fd, dnload.write_ptr, write_len);
688 perror("Error during write");
692 dnload.write_ptr += rc;
694 printf("%u bytes (%tu/%u)\n", rc, dnload.write_ptr - dnload.data,
700 static int handle_sercomm_write(void)
704 if (sercomm_drv_pull(&c) != 0) {
705 if (write(dnload.serial_fd.fd, &c, 1) != 1)
706 perror("short write");
708 dnload.serial_fd.when &= ~BSC_FD_WRITE;
713 static int handle_write(void)
715 /* TODO: simplify this again (global state: downloading, sercomm) */
716 switch (dnload.mode) {
718 switch (dnload.romload_state) {
720 case SENDING_LAST_BLOCK:
721 return handle_write_block();
723 return handle_sercomm_write();
727 switch (dnload.mtk_state) {
728 case MTK_SENDING_BLOCKS:
729 return handle_write_block();
731 return handle_sercomm_write();
735 switch (dnload.state) {
737 return handle_write_dnload();
739 return handle_sercomm_write();
746 static uint8_t buffer[sizeof(phone_prompt1)];
747 static uint8_t *bufptr = buffer;
749 static void hdlc_send_to_phone(uint8_t dlci, uint8_t *data, int len)
755 printf("hdlc_send(dlci=%u): ", dlci);
760 fprintf(stderr, "Too much data to send. %u\n", len);
764 /* push the message into the stack */
765 msg = sercomm_alloc_msgb(512);
767 fprintf(stderr, "Failed to create data for the frame.\n");
772 dest = msgb_put(msg, len);
773 memcpy(dest, data, len);
775 sercomm_sendmsg(dlci, msg);
777 dnload.serial_fd.when |= BSC_FD_WRITE;
780 static void hdlc_console_cb(uint8_t dlci, struct msgb *msg)
784 rc = write(1, msg->data, msg->len);
788 static void hdlc_tool_cb(uint8_t dlci, struct msgb *msg)
790 struct tool_server *srv = tool_server_for_dlci[dlci];
793 printf("hdlc_recv(dlci=%u): ", dlci);
794 hexdump(msg->data, msg->len);
798 struct tool_connection *con;
801 len = (uint16_t *) msgb_push(msg, 2);
802 *len = htons(msg->len - sizeof(*len));
804 llist_for_each_entry(con, &srv->connections, entry) {
805 if (write(con->fd.fd, msg->data, msg->len) != msg->len) {
807 "Failed to write msg to the socket..\n");
816 static int handle_buffer(int buf_used_len)
818 int nbytes, buf_left, i;
820 buf_left = buf_used_len - (bufptr - buffer);
822 memmove(buffer, buffer+1, buf_used_len-1);
827 nbytes = read(dnload.serial_fd.fd, bufptr, buf_left);
831 if (!dnload.expect_hdlc) {
832 printf("got %i bytes from modem, ", nbytes);
833 printf("data looks like: ");
834 hexdump(bufptr, nbytes);
836 for (i = 0; i < nbytes; ++i)
837 if (sercomm_drv_rx_char(bufptr[i]) == 0)
838 printf("Dropping sample '%c'\n", bufptr[i]);
844 /* Compal ramloader */
845 static int handle_read(void)
849 nbytes = handle_buffer(sizeof(buffer));
853 if (!memcmp(buffer, phone_prompt1, sizeof(phone_prompt1))) {
854 printf("Received PROMPT1 from phone, responding with CMD\n");
855 dnload.expect_hdlc = 0;
856 dnload.state = WAITING_PROMPT2;
857 if(dnload.filename) {
858 rc = write(dnload.serial_fd.fd, dnload_cmd, sizeof(dnload_cmd));
861 rc = read_file(dnload.filename);
863 fprintf(stderr, "read_file(%s) failed with %d\n",
864 dnload.filename, rc);
868 } else if (!memcmp(buffer, phone_prompt2, sizeof(phone_prompt2))) {
869 printf("Received PROMPT2 from phone, starting download\n");
870 dnload.serial_fd.when = BSC_FD_READ | BSC_FD_WRITE;
871 dnload.state = DOWNLOADING;
872 } else if (!memcmp(buffer, phone_ack, sizeof(phone_ack))) {
873 printf("Received DOWNLOAD ACK from phone, your code is"
875 dnload.serial_fd.when = BSC_FD_READ;
876 dnload.state = WAITING_PROMPT1;
877 dnload.write_ptr = dnload.data;
878 dnload.expect_hdlc = 1;
880 /* check for romloader chainloading mode used as a workaround
881 * for the magic on the C139/C140 and J100i */
882 if (dnload.chainload_filename != NULL) {
883 printf("Enabled Compal ramloader -> Calypso romloader"
884 " chainloading mode\n");
886 dnload.filename = dnload.chainload_filename;
887 dnload.mode = MODE_ROMLOAD;
888 serial_set_baudrate(ROMLOAD_INIT_BAUDRATE);
889 tick_timer.cb = &beacon_timer_cb;
890 tick_timer.data = &tick_timer;
891 bsc_schedule_timer(&tick_timer, 0, BEACON_INTERVAL);
893 } else if (!memcmp(buffer, phone_nack, sizeof(phone_nack))) {
894 printf("Received DOWNLOAD NACK from phone, something went"
896 dnload.serial_fd.when = BSC_FD_READ;
897 dnload.state = WAITING_PROMPT1;
898 dnload.write_ptr = dnload.data;
899 } else if (!memcmp(buffer, phone_nack_magic, sizeof(phone_nack_magic))) {
900 printf("Received MAGIC NACK from phone, you need to"
901 " have \"1003\" at 0x803ce0\n");
902 dnload.serial_fd.when = BSC_FD_READ;
903 dnload.state = WAITING_PROMPT1;
904 dnload.write_ptr = dnload.data;
905 } else if (!memcmp(buffer, ftmtool, sizeof(ftmtool))) {
906 printf("Received FTMTOOL from phone, ramloader has aborted\n");
907 dnload.serial_fd.when = BSC_FD_READ;
908 dnload.state = WAITING_PROMPT1;
909 dnload.write_ptr = dnload.data;
916 /* "Calypso non-secure romloader" */
917 static int handle_read_romload(void)
919 int rc, nbytes, buf_used_len;
921 /* virtually limit buffer length for romloader, since responses
922 * are shorter and vary in length */
924 switch (dnload.romload_state) {
925 case WAITING_PARAM_ACK:
926 buf_used_len = 4; /* ">p" + uint16_t len */
928 case WAITING_CHECKSUM_ACK:
929 buf_used_len = 3; /* ">c" + uint8_t checksum */
932 buf_used_len = sizeof(buffer);
935 buf_used_len = 2; /* ">*" */
938 nbytes = handle_buffer(buf_used_len);
942 switch (dnload.romload_state) {
943 case WAITING_IDENTIFICATION:
944 if (memcmp(buffer, romload_ident_ack,
945 sizeof(romload_ident_ack)))
948 printf("Received ident ack from phone, sending "
949 "parameter sequence\n");
950 dnload.expect_hdlc = 1;
951 dnload.romload_state = WAITING_PARAM_ACK;
952 rc = write(dnload.serial_fd.fd, romload_param,
953 sizeof(romload_param));
955 rc = read_file(dnload.filename);
957 fprintf(stderr, "read_file(%s) failed with %d\n",
958 dnload.filename, rc);
962 case WAITING_PARAM_ACK:
963 if (memcmp(buffer, romload_param_ack,
964 sizeof(romload_param_ack)))
967 printf("Received parameter ack from phone, "
968 "starting download\n");
969 serial_set_baudrate(ROMLOAD_DL_BAUDRATE);
971 /* using the max blocksize the phone tells us */
972 dnload.block_payload_size = ((buffer[3] << 8) + buffer[2]);
973 printf("Used blocksize for download is %i bytes\n",
974 dnload.block_payload_size);
975 dnload.block_payload_size -= ROMLOAD_BLOCK_HDR_LEN;
976 dnload.romload_state = SENDING_BLOCKS;
977 dnload.block_number = 0;
978 romload_prepare_block();
981 case WAITING_BLOCK_ACK:
982 case LAST_BLOCK_SENT:
983 if (!memcmp(buffer, romload_block_ack,
984 sizeof(romload_block_ack))) {
985 printf("Received block ack from phone\n");
986 if (dnload.romload_state == LAST_BLOCK_SENT) {
987 /* send the checksum */
988 uint8_t final_checksum =
989 (~(dnload.romload_dl_checksum) & 0xff);
990 printf("Sending checksum: 0x%02x \n",
992 rc = write(dnload.serial_fd.fd,
993 romload_checksum_cmd,
994 sizeof(romload_checksum_cmd));
995 rc = write(dnload.serial_fd.fd,
997 dnload.romload_state = WAITING_CHECKSUM_ACK;
999 romload_prepare_block();
1000 } else if (!memcmp(buffer, romload_block_nack,
1001 sizeof(romload_block_nack))) {
1002 printf("Received block nack from phone, "
1003 "something went wrong, aborting\n");
1004 serial_set_baudrate(ROMLOAD_INIT_BAUDRATE);
1005 dnload.romload_state = WAITING_IDENTIFICATION;
1006 bsc_schedule_timer(&tick_timer, 0, BEACON_INTERVAL);
1009 case WAITING_CHECKSUM_ACK:
1010 if (!memcmp(buffer, romload_checksum_ack,
1011 sizeof(romload_checksum_ack))) {
1012 printf("Checksum on phone side matches, "
1013 "let's branch to your code\n");
1014 printf("Branching to 0x%08x\n", ROMLOAD_ADDRESS);
1016 rc = write(dnload.serial_fd.fd, romload_branch_cmd,
1017 sizeof(romload_branch_cmd));
1018 rc = write(dnload.serial_fd.fd, &dnload.load_address,
1019 sizeof(dnload.load_address));
1020 dnload.romload_state = WAITING_BRANCH_ACK;
1022 } else if (!memcmp(buffer, romload_checksum_nack,
1023 sizeof(romload_checksum_nack))) {
1024 printf("Checksum on phone side (0x%02x) doesn't "
1025 "match ours, aborting\n", ~buffer[2]);
1026 serial_set_baudrate(ROMLOAD_INIT_BAUDRATE);
1027 dnload.romload_state = WAITING_IDENTIFICATION;
1028 bsc_schedule_timer(&tick_timer, 0, BEACON_INTERVAL);
1032 case WAITING_BRANCH_ACK:
1033 if (!memcmp(buffer, romload_branch_ack,
1034 sizeof(romload_branch_ack))) {
1035 printf("Received branch ack, your code is running now!\n");
1036 dnload.serial_fd.when = BSC_FD_READ;
1037 dnload.romload_state = FINISHED;
1038 dnload.write_ptr = dnload.data;
1039 dnload.expect_hdlc = 1;
1040 } else if (!memcmp(buffer, romload_branch_nack,
1041 sizeof(romload_branch_nack))) {
1042 printf("Received branch nack, aborting\n");
1043 serial_set_baudrate(ROMLOAD_INIT_BAUDRATE);
1044 dnload.romload_state = WAITING_IDENTIFICATION;
1045 bsc_schedule_timer(&tick_timer, 0, BEACON_INTERVAL);
1057 static int handle_read_mtk(void)
1059 int rc, nbytes, buf_used_len;
1061 switch (dnload.mtk_state) {
1062 case MTK_WAIT_ADDR_ACK:
1063 case MTK_WAIT_SIZE_ACK:
1064 case MTK_WAIT_BRANCH_ADDR_ACK:
1068 buf_used_len = sizeof(buffer);
1074 nbytes = handle_buffer(buf_used_len);
1078 switch (dnload.mtk_state) {
1080 if (!(buffer[0] == mtk_init_resp[0]))
1082 dnload.mtk_state = MTK_INIT_2;
1083 printf("Received init magic byte 1\n");
1084 rc = write(dnload.serial_fd.fd, &mtk_init_cmd[1], 1);
1087 if (!(buffer[0] == mtk_init_resp[1]))
1089 dnload.mtk_state = MTK_INIT_3;
1090 printf("Received init magic byte 2\n");
1091 rc = write(dnload.serial_fd.fd, &mtk_init_cmd[2], 1);
1094 if (!(buffer[0] == mtk_init_resp[2]))
1096 dnload.mtk_state = MTK_INIT_4;
1097 printf("Received init magic byte 3\n");
1098 rc = write(dnload.serial_fd.fd, &mtk_init_cmd[3], 1);
1101 if (!(buffer[0] == mtk_init_resp[3]))
1103 dnload.mtk_state = MTK_WAIT_WRITE_ACK;
1104 printf("Received init magic byte 4, requesting write\n");
1105 rc = write(dnload.serial_fd.fd, &mtk_command[0], 1);
1107 case MTK_WAIT_WRITE_ACK:
1108 if (!(buffer[0] == mtk_command[0]))
1110 dnload.mtk_state = MTK_WAIT_ADDR_ACK;
1111 printf("Received write ack, sending load address\n");
1113 rc = write(dnload.serial_fd.fd, &dnload.load_address,
1114 sizeof(dnload.load_address));
1116 case MTK_WAIT_ADDR_ACK:
1117 if (memcmp(buffer, dnload.load_address,
1118 sizeof(dnload.load_address)))
1120 printf("Received address ack from phone, sending loadsize\n");
1122 rc = read_file(dnload.filename);
1124 fprintf(stderr, "read_file(%s) failed with %d\n",
1125 dnload.filename, rc);
1128 dnload.block_number = 0;
1129 mtk_prepare_block();
1130 dnload.mtk_state = MTK_WAIT_SIZE_ACK;
1131 rc = write(dnload.serial_fd.fd, &dnload.mtk_send_size,
1132 sizeof(dnload.mtk_send_size));
1134 case MTK_WAIT_SIZE_ACK:
1135 if (memcmp(buffer, dnload.mtk_send_size,
1136 sizeof(dnload.mtk_send_size)))
1138 printf("Received size ack\n");
1139 dnload.expect_hdlc = 1;
1140 dnload.mtk_state = MTK_SENDING_BLOCKS;
1141 dnload.serial_fd.when = BSC_FD_READ | BSC_FD_WRITE;
1144 case MTK_SENDING_BLOCKS:
1145 if (!(buffer[0] == dnload.block[dnload.echo_bytecount]))
1146 printf("Warning: Byte %i of Block %i doesn't match,"
1147 " check your serial connection!\n",
1148 dnload.echo_bytecount, dnload.block_number);
1149 dnload.echo_bytecount++;
1151 if ((dnload.echo_bytecount+1) > MTK_BLOCK_SIZE) {
1152 if ( dnload.block_number == dnload.block_count) {
1153 rc = write(dnload.serial_fd.fd,
1154 &mtk_command[3], 1);
1155 printf("Sending branch command\n");
1156 dnload.expect_hdlc = 0;
1157 dnload.mtk_state = MTK_WAIT_BRANCH_CMD_ACK;
1160 printf("Received Block %i preparing next block\n",
1161 dnload.block_number);
1162 mtk_prepare_block();
1163 dnload.serial_fd.when = BSC_FD_READ | BSC_FD_WRITE;
1166 case MTK_WAIT_BRANCH_CMD_ACK:
1167 if (!(buffer[0] == mtk_command[3]))
1169 dnload.mtk_state = MTK_WAIT_BRANCH_ADDR_ACK;
1170 printf("Received branch command ack, sending address\n");
1172 rc = write(dnload.serial_fd.fd, &dnload.load_address,
1173 sizeof(dnload.load_address));
1175 case MTK_WAIT_BRANCH_ADDR_ACK:
1176 if (memcmp(buffer, dnload.load_address,
1177 sizeof(dnload.load_address)))
1179 printf("Received branch address ack, code should run now\n");
1180 serial_set_baudrate(MODEM_BAUDRATE);
1181 dnload.serial_fd.when = BSC_FD_READ;
1182 dnload.mtk_state = MTK_FINISHED;
1183 dnload.write_ptr = dnload.data;
1184 dnload.expect_hdlc = 1;
1194 static int serial_read(struct bsc_fd *fd, unsigned int flags)
1197 if (flags & BSC_FD_READ) {
1198 switch (dnload.mode) {
1200 rc = handle_read_romload();
1203 rc = handle_read_mtk();
1213 if (flags & BSC_FD_WRITE) {
1214 rc = handle_write();
1216 dnload.state = WAITING_PROMPT1;
1221 static int parse_mode(const char *arg)
1223 if (!strcasecmp(arg, "c123"))
1225 else if (!strcasecmp(arg, "c123xor"))
1226 return MODE_C123xor;
1227 else if (!strcasecmp(arg, "c140"))
1229 else if (!strcasecmp(arg, "c140xor"))
1230 return MODE_C140xor;
1231 else if (!strcasecmp(arg, "c155"))
1233 else if (!strcasecmp(arg, "romload"))
1234 return MODE_ROMLOAD;
1235 else if (!strcasecmp(arg, "mtk"))
1242 "[ -v | -h ] [ -d [t][r] ] [ -p /dev/ttyXXXX ]\n" \
1243 "\t\t [ -s /tmp/osmocom_l2 ]\n" \
1244 "\t\t [ -l /tmp/osmocom_loader ]\n" \
1245 "\t\t [ -m {c123,c123xor,c140,c140xor,c155,romload,mtk} ]\n" \
1246 "\t\t [ -c /to-be-chainloaded-file.bin ]\n" \
1247 "\t\t file.bin\n\n" \
1248 "* Open serial port /dev/ttyXXXX (connected to your phone)\n" \
1249 "* Perform handshaking with the ramloader in the phone\n" \
1250 "* Download file.bin to the attached phone (base address 0x00800100)\n"
1252 static int usage(const char *name)
1254 printf("Usage: %s ", name);
1259 static int version(const char *name)
1261 printf("%s version %s\n", name, PACKAGE_VERSION);
1265 static int un_tool_read(struct bsc_fd *fd, unsigned int flags)
1268 uint16_t length = 0xffff;
1270 struct tool_connection *con = (struct tool_connection *)fd->data;
1274 rc = read(fd->fd, &buf + c, 2 - c);
1280 if(errno == EAGAIN) {
1283 fprintf(stderr, "Err from socket: %s\n", strerror(errno));
1289 length = ntohs(*(uint16_t*)buf);
1293 rc = read(fd->fd, &buf + c, length - c);
1299 if(errno == EAGAIN) {
1302 fprintf(stderr, "Err from socket: %s\n", strerror(errno));
1308 hdlc_send_to_phone(con->server->dlci, buf, length);
1314 bsc_unregister_fd(fd);
1315 llist_del(&con->entry);
1320 /* accept a new connection */
1321 static int tool_accept(struct bsc_fd *fd, unsigned int flags)
1323 struct tool_server *srv = (struct tool_server *)fd->data;
1324 struct tool_connection *con;
1325 struct sockaddr_un un_addr;
1329 len = sizeof(un_addr);
1330 rc = accept(fd->fd, (struct sockaddr *) &un_addr, &len);
1332 fprintf(stderr, "Failed to accept a new connection.\n");
1336 con = talloc_zero(NULL, struct tool_connection);
1338 fprintf(stderr, "Failed to create tool connection.\n");
1345 con->fd.when = BSC_FD_READ;
1346 con->fd.cb = un_tool_read;
1348 if (bsc_register_fd(&con->fd) != 0) {
1349 fprintf(stderr, "Failed to register the fd.\n");
1353 llist_add(&con->entry, &srv->connections);
1358 * Register and start a tool server
1360 static int register_tool_server(struct tool_server *ts,
1364 struct bsc_fd *bfd = &ts->bfd;
1365 struct sockaddr_un local;
1366 unsigned int namelen;
1369 bfd->fd = socket(AF_UNIX, SOCK_STREAM, 0);
1372 fprintf(stderr, "Failed to create Unix Domain Socket.\n");
1376 local.sun_family = AF_UNIX;
1377 strncpy(local.sun_path, path, sizeof(local.sun_path));
1378 local.sun_path[sizeof(local.sun_path) - 1] = '\0';
1379 unlink(local.sun_path);
1381 /* we use the same magic that X11 uses in Xtranssock.c for
1382 * calculating the proper length of the sockaddr */
1383 #if defined(BSD44SOCKETS) || defined(__UNIXWARE__)
1384 local.sun_len = strlen(local.sun_path);
1386 #if defined(BSD44SOCKETS) || defined(SUN_LEN)
1387 namelen = SUN_LEN(&local);
1389 namelen = strlen(local.sun_path) +
1390 offsetof(struct sockaddr_un, sun_path);
1393 rc = bind(bfd->fd, (struct sockaddr *) &local, namelen);
1395 fprintf(stderr, "Failed to bind the unix domain socket. '%s'\n",
1400 if (listen(bfd->fd, 0) != 0) {
1401 fprintf(stderr, "Failed to listen.\n");
1405 bfd->when = BSC_FD_READ;
1406 bfd->cb = tool_accept;
1410 INIT_LLIST_HEAD(&ts->connections);
1412 tool_server_for_dlci[dlci] = ts;
1414 sercomm_register_rx_cb(dlci, hdlc_tool_cb);
1416 if (bsc_register_fd(bfd) != 0) {
1417 fprintf(stderr, "Failed to register the bfd.\n");
1424 extern void hdlc_tpudbg_cb(uint8_t dlci, struct msgb *msg);
1426 void parse_debug(const char *str)
1437 printf("Unknown debug flag %c\n", *str);
1445 int main(int argc, char **argv)
1448 uint32_t tmp_load_address = ROMLOAD_ADDRESS;
1449 const char *serial_dev = "/dev/ttyUSB1";
1450 const char *layer2_un_path = "/tmp/osmocom_l2";
1451 const char *loader_un_path = "/tmp/osmocom_loader";
1453 dnload.mode = MODE_C123;
1454 dnload.chainload_filename = NULL;
1456 while ((opt = getopt(argc, argv, "d:hl:p:m:c:s:v")) != -1) {
1459 serial_dev = optarg;
1462 dnload.mode = parse_mode(optarg);
1463 if (dnload.mode < 0)
1467 layer2_un_path = optarg;
1470 loader_un_path = optarg;
1476 parse_debug(optarg);
1479 dnload.chainload_filename = optarg;
1488 if (argc <= optind) {
1489 dnload.filename = NULL;
1491 dnload.filename = argv[optind];
1494 dnload.serial_fd.fd = serial_init(serial_dev);
1495 if (dnload.serial_fd.fd < 0) {
1496 fprintf(stderr, "Cannot open serial device %s\n", serial_dev);
1500 if (bsc_register_fd(&dnload.serial_fd) != 0) {
1501 fprintf(stderr, "Failed to register the serial.\n");
1505 /* Set serial socket to non-blocking mode of operation */
1506 flags = fcntl(dnload.serial_fd.fd, F_GETFL);
1507 flags |= O_NONBLOCK;
1508 fcntl(dnload.serial_fd.fd, F_SETFL, flags);
1510 dnload.serial_fd.when = BSC_FD_READ;
1511 dnload.serial_fd.cb = serial_read;
1513 /* initialize the HDLC layer */
1515 sercomm_register_rx_cb(SC_DLCI_CONSOLE, hdlc_console_cb);
1516 sercomm_register_rx_cb(SC_DLCI_DEBUG, hdlc_tpudbg_cb);
1518 /* unix domain socket handling */
1519 if (register_tool_server(&dnload.layer2_server, layer2_un_path,
1520 SC_DLCI_L1A_L23) != 0)
1523 if (register_tool_server(&dnload.loader_server, loader_un_path,
1524 SC_DLCI_LOADER) != 0)
1527 /* if in romload mode, start our beacon timer */
1528 if (dnload.mode == MODE_ROMLOAD) {
1529 tmp_load_address = ROMLOAD_ADDRESS;
1530 serial_set_baudrate(ROMLOAD_INIT_BAUDRATE);
1531 tick_timer.cb = &beacon_timer_cb;
1532 tick_timer.data = &tick_timer;
1533 bsc_schedule_timer(&tick_timer, 0, BEACON_INTERVAL);
1535 else if (dnload.mode == MODE_MTK) {
1536 tmp_load_address = MTK_ADDRESS;
1537 serial_set_baudrate(MTK_INIT_BAUDRATE);
1538 tick_timer.cb = &mtk_timer_cb;
1539 tick_timer.data = &tick_timer;
1540 bsc_schedule_timer(&tick_timer, 0, BEACON_INTERVAL);
1543 dnload.load_address[0] = (tmp_load_address >> 24) & 0xff;
1544 dnload.load_address[1] = (tmp_load_address >> 16) & 0xff;
1545 dnload.load_address[2] = (tmp_load_address >> 8) & 0xff;
1546 dnload.load_address[3] = tmp_load_address & 0xff;
1551 close(dnload.serial_fd.fd);