95f4e97f639dfb7f1a044eaec07401d09e4f7dd9
[gps-watch.git] / src / bootloader / bootloader.rs
1 /*
2  * Copyright (c) 2019 Tilman Sauerbeck (tilman at code-monkey de)
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22  */
23
24 use common::buffer::Buffer;
25 use common::crc32::Crc32;
26 use flash;
27
28 const COMMAND_ERASE     : u32 = 0x49e89a20;
29 const COMMAND_PROGRAM   : u32 = 0x37f7dc8d;
30 const COMMAND_VERIFY    : u32 = 0x4a213efb;
31 const COMMAND_LOADCHUNK : u32 = 0x1b329768;
32
33 pub struct Bootloader {
34     command: u32,
35     command_bytes: u32,
36     sector_data: [u8; flash::SECTOR_SIZE],
37
38     // The number of bytes in sector_data.
39     // This is always 32 bit aligned and never greater than flash::SECTOR_SIZE.
40     sector_data_length: usize,
41 }
42
43 #[derive(Copy,Clone)]
44 enum Error {
45     UnknownCommand = 1,
46     InvalidArgument,
47     ChecksumMismatch,
48 }
49
50 extern {
51     fn usb_serial_read(c: *mut u8) -> bool;
52
53     static mut cdc_tx_buf: Buffer;
54 }
55
56 fn try_read_u8() -> Option<u8> {
57     unsafe {
58         let mut c = b'\0';
59
60         if usb_serial_read(&mut c) {
61             Some(c)
62         } else {
63             None
64         }
65     }
66 }
67
68 fn read_u8() -> u8 {
69     let mut b = b'\0';
70
71     unsafe {
72         while !usb_serial_read(&mut b) {
73         }
74     }
75
76     b
77 }
78
79 fn read_u32_le() -> u32 {
80     let mut b = [0u8; 4];
81
82     for i in 0..4 {
83         b[i] = read_u8();
84     }
85
86     u32::from_le_bytes(b)
87 }
88
89 fn write_u8(b: u8) {
90     unsafe {
91         cdc_tx_buf.write(&[b]);
92         cdc_tx_buf.flush();
93     }
94 }
95
96 fn write_u32_le(u: u32) {
97     let b = u.to_le_bytes();
98
99     unsafe {
100         cdc_tx_buf.write(&b);
101         cdc_tx_buf.flush();
102     }
103 }
104
105 fn write_ack() {
106     write_u8(0u8);
107 }
108
109 fn write_nak(e: Error) {
110     write_u8(e as u8);
111 }
112
113 impl Bootloader {
114     pub fn new() -> Bootloader {
115         Bootloader {
116             command: 0,
117             command_bytes: 0,
118             sector_data: [0u8; flash::SECTOR_SIZE],
119             sector_data_length: 0,
120         }
121     }
122
123     pub fn run(&mut self) {
124         if self.command_bytes < 4 {
125             if let Some(b) = try_read_u8() {
126                 self.command >>= 8;
127                 self.command |= (b as u32) << 24;
128
129                 self.command_bytes += 1;
130             }
131         }
132
133         if self.command_bytes == 4 {
134             self.command_bytes = 0;
135
136             self.process_command();
137         }
138     }
139
140     fn process_command(&mut self) {
141         match self.command {
142             COMMAND_ERASE => {
143                 if let Err(e) = self.exec_erase() {
144                     write_nak(e);
145                 } else {
146                     write_ack();
147                 }
148             },
149             COMMAND_LOADCHUNK => {
150                 if let Err(e) = self.exec_load_sector_data() {
151                     write_nak(e);
152                 } else {
153                     write_ack();
154                 }
155             },
156             COMMAND_VERIFY => {
157                 let result = self.exec_verify();
158
159                 if let Err(e) = result {
160                     write_nak(e);
161                 } else if let Ok((a, b)) = result {
162                     write_ack();
163
164                     write_u32_le(a);
165                     write_u32_le(b);
166                 }
167             },
168             COMMAND_PROGRAM => {
169                 if let Err(e) = self.exec_program() {
170                     write_nak(e);
171                 } else {
172                     write_ack();
173                 }
174             },
175             _ => {
176                 write_nak(Error::UnknownCommand);
177             }
178         };
179     }
180
181     fn exec_erase(&mut self) -> Result<(), Error> {
182         let sector = read_u32_le();
183
184         if sector > 0xff {
185             Err(Error::InvalidArgument)
186         } else {
187             flash::erase(sector);
188
189             Ok(())
190         }
191     }
192
193     fn exec_load_sector_data(&mut self) -> Result<(), Error> {
194         let num_bytes = read_u32_le() as usize;
195
196         if num_bytes < 1 {
197             Err(Error::InvalidArgument)
198         } else if num_bytes > flash::SECTOR_SIZE {
199             Err(Error::InvalidArgument)
200         } else if (num_bytes & 3) != 0 {
201             Err(Error::InvalidArgument)
202         } else {
203             write_ack();
204
205             self.sector_data_length = num_bytes;
206
207             for i in 0..num_bytes {
208                 self.sector_data[i] = read_u8();
209             }
210
211             let expected_crc32 = read_u32_le();
212
213             let chunk = &self.sector_data[0..self.sector_data_length];
214
215             let mut actual_crc32 = Crc32::new();
216             actual_crc32.update(chunk);
217
218             if actual_crc32.finish() != expected_crc32 {
219                 Err(Error::ChecksumMismatch)
220             } else {
221                 Ok(())
222             }
223         }
224     }
225
226     fn exec_verify(&mut self) -> Result<(u32, u32), Error> {
227         let sector = read_u32_le();
228
229         if sector > 0xff {
230             Err(Error::InvalidArgument)
231         } else if self.sector_data_length == 0 {
232             Err(Error::InvalidArgument)
233         } else {
234             let chunk = &self.sector_data[0..self.sector_data_length];
235
236             Ok(flash::verify(sector, chunk))
237         }
238     }
239
240     fn exec_program(&mut self) -> Result<(), Error> {
241         let sector = read_u32_le();
242
243         if sector > 0xff {
244             Err(Error::InvalidArgument)
245         } else if self.sector_data_length == 0 {
246             Err(Error::InvalidArgument)
247         } else {
248             let chunk = &self.sector_data[0..self.sector_data_length];
249
250             Ok(flash::program(sector, chunk))
251         }
252     }
253 }