├── .gitignore ├── COPYRIGHT ├── Cargo.toml ├── LICENSE ├── README.md ├── ec.py ├── examples ├── flash.rs ├── isp.rs ├── read.rs └── tcpc.rs └── src ├── file.rs ├── flash.rs ├── flasher.rs ├── io.rs ├── lib.rs └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | Cargo.lock 2 | target 3 | -------------------------------------------------------------------------------- /COPYRIGHT: -------------------------------------------------------------------------------- 1 | ecflash - Flashing and querying System76 Embedded Controllers 2 | Copyright (C) 2017 System76 3 | 4 | This library is free software; you can redistribute it and/or 5 | modify it under the terms of the GNU Lesser General Public 6 | License as published by the Free Software Foundation; either 7 | version 2.1 of the License, or (at your option) any later version. 8 | 9 | This library is distributed in the hope that it will be useful, 10 | but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | Lesser General Public License for more details. 13 | 14 | You should have received a copy of the GNU Lesser General Public 15 | License along with this library; if not, write to the Free Software 16 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "system76_ecflash" 3 | version = "0.1.3" 4 | edition = "2024" 5 | description = "Flashing and querying with System76 Embedded Controllers" 6 | license = "LGPL-2.1-or-later" 7 | authors = ["Jeremy Soller "] 8 | repository = "https://github.com/system76/ecflash" 9 | 10 | [lib] 11 | name = "ecflash" 12 | 13 | [dev-dependencies] 14 | libc = "0.2.121" 15 | redox_hwio = "0.1.5" 16 | serialport = "4.1.0" 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 489 | 490 | Also add information on how to contact you by electronic and paper mail. 491 | 492 | You should also get your employer (if you work as a programmer) or your 493 | school, if any, to sign a "copyright disclaimer" for the library, if 494 | necessary. Here is a sample; alter the names: 495 | 496 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 497 | library `Frob' (a library for tweaking knobs) written by James Random Hacker. 498 | 499 | , 1 April 1990 500 | Ty Coon, President of Vice 501 | 502 | That's all there is to it! 503 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ecflash 2 | 3 | Flashing and querying with System76 Embedded Controllers 4 | -------------------------------------------------------------------------------- /ec.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | 6 | class Ec: 7 | def __init__(self): 8 | self.fd = os.open("/dev/port", os.O_RDWR) 9 | 10 | self.data_port = 0x62 11 | self.cmd_port = 0x66 12 | 13 | chip_id = self.id() 14 | if chip_id != 0x8587 and chip_id != 0x5570: 15 | raise Exception("EC: Unknown ID: 0x{:04X}".format(chip_id)) 16 | 17 | def close(self): 18 | os.close(self.fd) 19 | 20 | # Read one byte from a port 21 | def inb(self, port): 22 | os.lseek(self.fd, port, os.SEEK_SET) 23 | data = os.read(self.fd, 1) 24 | return data[0] 25 | 26 | # Write one byte to a port 27 | def outb(self, port, data): 28 | os.lseek(self.fd, port, os.SEEK_SET) 29 | os.write(self.fd, bytearray([data])) 30 | 31 | # Get the Super I/O chip ID 32 | def id(self): 33 | self.outb(0x2e, 0x20); 34 | a = self.inb(0x2f); 35 | self.outb(0x2e, 0x21); 36 | b = self.inb(0x2f); 37 | return (a << 8) | b 38 | 39 | # Write a one byte command to the EC 40 | def cmd(self, data): 41 | i = 1000000 42 | while self.inb(self.cmd_port) & 0x2 == 0x2 and i > 0: 43 | i -= 1 44 | 45 | if i == 0: 46 | raise Exception("EC: Failed to send command {:02X}".format(data)) 47 | else: 48 | self.outb(self.cmd_port, data) 49 | 50 | # Read one byte from the EC 51 | def read(self): 52 | i = 1000000 53 | while self.inb(self.cmd_port) & 0x1 == 0 and i > 0: 54 | i -= 1 55 | 56 | if i == 0: 57 | raise Exception("EC: Failed to read") 58 | else: 59 | return self.inb(self.data_port) 60 | 61 | # Write one data byte to the EC 62 | def write(self, data): 63 | i = 1000000 64 | while self.inb(self.cmd_port) & 0x2 == 0x2 and i > 0: 65 | i -= 1 66 | 67 | if i == 0: 68 | raise Exception("EC: Failed to write {:02X}".format(data)) 69 | else: 70 | self.outb(self.data_port, data) 71 | 72 | # Empty the EC data buffer 73 | def flush(self): 74 | while self.inb(self.cmd_port) & 0x1 == 0x1: 75 | self.inb(self.data_port) 76 | 77 | # Get an EC parameter 78 | def get_param(self, param): 79 | self.cmd(0x80) 80 | self.write(param) 81 | return self.read() 82 | 83 | # Set an EC parameter 84 | def set_param(self, param, data): 85 | self.cmd(0x81) 86 | self.write(param) 87 | self.write(data) 88 | 89 | # Read a string from the EC 90 | def get_str(self, index): 91 | string = "" 92 | 93 | self.cmd(index) 94 | for i in range(0, 256): 95 | byte = chr(self.read()) 96 | if byte == '$': 97 | break 98 | else: 99 | string += byte 100 | 101 | return string 102 | 103 | # Get the EC size 104 | def size(self): 105 | self.flush() 106 | if self.get_param(0xE5) == 0x80: 107 | return 128 * 1024 108 | else: 109 | return 64 * 1024 110 | 111 | # Get the EC project 112 | def project(self): 113 | self.flush() 114 | return self.get_str(0x92) 115 | 116 | # Get the EC version 117 | def version(self): 118 | self.flush() 119 | return "1." + self.get_str(0x93) 120 | 121 | if os.geteuid() != 0: 122 | sys.stderr.write("EC: You must be running as root\n") 123 | exit(1) 124 | 125 | ec = Ec() 126 | print('EC Project:', ec.project()) 127 | print('EC Version:', ec.version()) 128 | print('EC Size:', ec.size()) 129 | ec.close() 130 | -------------------------------------------------------------------------------- /examples/flash.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::needless_range_loop)] 2 | 3 | extern crate ecflash; 4 | 5 | use ecflash::{EcFlash, Flasher}; 6 | use std::{env, fs, io, process, thread, time}; 7 | 8 | fn main() { 9 | unsafe extern "C" { 10 | fn iopl(level: isize) -> isize; 11 | } 12 | 13 | let path = env::args().nth(1).expect("no path argument"); 14 | 15 | let mut data = fs::read(path).expect("Failed to open rom"); 16 | 17 | // Wait for any key releases 18 | eprintln!("Waiting for all keys to be released"); 19 | thread::sleep(time::Duration::new(1, 0)); 20 | 21 | eprintln!("Sync"); 22 | process::Command::new("sync") 23 | .status() 24 | .expect("failed to run sync"); 25 | 26 | // Get I/O Permission 27 | unsafe { 28 | if iopl(3) < 0 { 29 | eprintln!( 30 | "Failed to get I/O permission: {}", 31 | io::Error::last_os_error() 32 | ); 33 | process::exit(1); 34 | } 35 | 36 | let ec = EcFlash::new(true).expect("Failed to find EC"); 37 | 38 | let mut flasher = Flasher::new(ec); 39 | 40 | while data.len() < flasher.size { 41 | data.push(0xFF); 42 | } 43 | 44 | if flasher.start() == Ok(51) { 45 | let mut success = false; 46 | 47 | if let Ok(_original) = flasher.read(|x| eprint!("\rRead: {} KB", x / 1024)) { 48 | eprintln!(); 49 | 50 | if flasher 51 | .erase(|x| eprint!("\rErase: {} KB", x / 1024)) 52 | .is_ok() 53 | { 54 | eprintln!(); 55 | 56 | if let Ok(erased) = flasher.read(|x| eprint!("\rRead: {} KB", x / 1024)) { 57 | eprintln!(); 58 | 59 | //TODO: retry erase on fail 60 | for i in 0..erased.len() { 61 | if erased[i] != 0xFF { 62 | println!("0x{:X}: 0x{:02X} != 0xFF", i, erased[i]); 63 | } 64 | } 65 | 66 | if flasher 67 | .write(&data, |x| eprint!("\rWrite {} KB", x / 1024)) 68 | .is_ok() 69 | { 70 | eprintln!(); 71 | 72 | if let Ok(written) = 73 | flasher.read(|x| eprint!("\rRead: {} KB", x / 1024)) 74 | { 75 | eprintln!(); 76 | 77 | success = true; 78 | for i in 0..written.len() { 79 | if written[i] != data[i] { 80 | println!( 81 | "0x{:X}: 0x{:02X} != 0x{:02X}", 82 | i, written[i], data[i] 83 | ); 84 | success = false; 85 | } 86 | } 87 | } else { 88 | eprintln!("Failed to read written data"); 89 | } 90 | } else { 91 | eprintln!("Failed to write data"); 92 | } 93 | } else { 94 | eprintln!("Failed to read erased data"); 95 | } 96 | } else { 97 | eprintln!("Failed to erase data"); 98 | } 99 | } else { 100 | eprintln!("Failed to read original data"); 101 | } 102 | 103 | eprintln!("Sync"); 104 | process::Command::new("sync") 105 | .status() 106 | .expect("failed to run sync"); 107 | 108 | // Will currently power off system 109 | let _ = flasher.stop(); 110 | 111 | if success { 112 | eprintln!("Successfully flashed EC"); 113 | 114 | // Shut down 115 | process::Command::new("shutdown") 116 | .status() 117 | .expect("failed to run shutdown"); 118 | } else { 119 | eprintln!("Failed to flash EC"); 120 | } 121 | } else { 122 | eprintln!("Failed to start flasher"); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /examples/isp.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code)] 2 | #![allow(clippy::missing_safety_doc)] 3 | #![allow(clippy::needless_range_loop)] 4 | 5 | use hwio::{Io, Pio}; 6 | use serialport::{Error, ErrorKind, Result, TTYPort}; 7 | use std::any::Any; 8 | use std::env; 9 | use std::fs; 10 | use std::io::{self, Read, Write}; 11 | use std::process; 12 | use std::thread; 13 | use std::time::Duration; 14 | 15 | use ecflash::EcFlash; 16 | 17 | const EC_KNOWN_IDS: &[u16] = &[0x5570, 0x8587]; 18 | 19 | #[repr(u8)] 20 | pub enum Address { 21 | CHIPID0 = 0, 22 | CHIPID1 = 1, 23 | CHIPVER = 2, 24 | INDAR0 = 4, 25 | INDAR1 = 5, 26 | INDAR2 = 6, 27 | INDAR3 = 7, 28 | INDDR = 8, 29 | ECMSADDR0 = 0x2E, 30 | ECMSADDR1 = 0x2F, 31 | ECMSDATA = 0x30, 32 | } 33 | 34 | pub trait Debugger { 35 | /// Set the debugger address 36 | fn address(&mut self, address: u8) -> Result<()>; 37 | /// Read data from the debugger port 38 | fn read(&mut self, data: &mut [u8]) -> Result; 39 | /// Write data to the debugger port 40 | fn write(&mut self, data: &[u8]) -> Result; 41 | 42 | /// Read data at a debugger address 43 | fn read_at(&mut self, address: Address, data: &mut [u8]) -> Result { 44 | self.address(address as u8)?; 45 | self.read(data) 46 | } 47 | 48 | /// Write data at a debugger address 49 | fn write_at(&mut self, address: Address, data: &[u8]) -> Result { 50 | self.address(address as u8)?; 51 | self.write(data) 52 | } 53 | 54 | /// Set EC memory snoop address 55 | fn ecms_address(&mut self, address: u16) -> Result<()> { 56 | self.write_at(Address::ECMSADDR1, &[(address >> 8) as u8])?; 57 | self.write_at(Address::ECMSADDR0, &[(address) as u8])?; 58 | 59 | Ok(()) 60 | } 61 | 62 | /// Read data from memory using EC-indirect mode 63 | fn ecms_read(&mut self, data: &mut [u8]) -> Result { 64 | self.read_at(Address::ECMSDATA, data) 65 | } 66 | 67 | /// Write data to memory using EC memory snoop 68 | fn ecms_write(&mut self, data: &[u8]) -> Result { 69 | self.write_at(Address::ECMSDATA, data) 70 | } 71 | 72 | /// Read data from memory at address using EC memory snoop 73 | fn ecms_read_at(&mut self, address: u16, data: &mut [u8]) -> Result { 74 | self.ecms_address(address)?; 75 | self.ecms_read(data) 76 | } 77 | 78 | /// Write data to memory at address using EC memory snoop 79 | fn ecms_write_at(&mut self, address: u16, data: &[u8]) -> Result { 80 | self.ecms_address(address)?; 81 | self.ecms_write(data) 82 | } 83 | } 84 | 85 | pub trait Smfi { 86 | /// Set indar1 register (special case for follow mode) 87 | fn flash_indar1(&mut self, data: u8) -> Result<()>; 88 | 89 | /// Set EC-indirect flash address 90 | fn flash_address(&mut self, address: u32) -> Result<()>; 91 | 92 | /// Read data from flash using EC-indirect mode 93 | fn flash_read(&mut self, data: &mut [u8]) -> Result; 94 | 95 | /// Write data to flash using EC-indirect mode 96 | fn flash_write(&mut self, data: &[u8]) -> Result; 97 | 98 | /// Read data from flash at address using EC-indirect mode 99 | fn flash_read_at(&mut self, address: u32, data: &mut [u8]) -> Result { 100 | self.flash_address(address)?; 101 | self.flash_read(data) 102 | } 103 | 104 | /// Write data to flash at address using EC-indirect mode 105 | fn flash_write_at(&mut self, address: u32, data: &[u8]) -> Result { 106 | self.flash_address(address)?; 107 | self.flash_write(data) 108 | } 109 | } 110 | 111 | impl Smfi for T 112 | where 113 | T: Debugger, 114 | { 115 | /// Set indar1 register (special case for follow mode) 116 | fn flash_indar1(&mut self, data: u8) -> Result<()> { 117 | self.write_at(Address::INDAR1, &[data])?; 118 | Ok(()) 119 | } 120 | 121 | /// Set EC-indirect flash address 122 | fn flash_address(&mut self, address: u32) -> Result<()> { 123 | self.write_at(Address::INDAR3, &[(address >> 24) as u8])?; 124 | self.write_at(Address::INDAR2, &[(address >> 16) as u8])?; 125 | self.write_at(Address::INDAR1, &[(address >> 8) as u8])?; 126 | self.write_at(Address::INDAR0, &[(address) as u8])?; 127 | Ok(()) 128 | } 129 | 130 | /// Read data from flash using EC-indirect mode 131 | fn flash_read(&mut self, data: &mut [u8]) -> Result { 132 | self.read_at(Address::INDDR, data) 133 | } 134 | 135 | /// Write data to flash using EC-indirect mode 136 | fn flash_write(&mut self, data: &[u8]) -> Result { 137 | self.write_at(Address::INDDR, data) 138 | } 139 | } 140 | 141 | pub struct SpiBus<'a, T: Smfi> { 142 | port: &'a mut T, 143 | data: bool, 144 | } 145 | 146 | impl<'a, T: Smfi> SpiBus<'a, T> { 147 | pub fn new(port: &'a mut T, eflash: bool) -> Result { 148 | port.flash_address(if eflash { 0x7FFF_FE00 } else { 0xFFFF_FE00 })?; 149 | 150 | let mut spi = Self { port, data: false }; 151 | spi.reset()?; 152 | Ok(spi) 153 | } 154 | 155 | /// Disable SPI chip - should be done before and after each transaction 156 | pub fn reset(&mut self) -> Result<()> { 157 | if self.data { 158 | self.port.flash_indar1(0xFE)?; 159 | self.data = false; 160 | } 161 | self.port.flash_write(&[0])?; 162 | Ok(()) 163 | } 164 | 165 | /// Read from SPI chip directly using follow mode 166 | pub fn read(&mut self, data: &mut [u8]) -> Result { 167 | if !self.data { 168 | self.port.flash_indar1(0xFD)?; 169 | self.data = true; 170 | } 171 | self.port.flash_read(data) 172 | } 173 | 174 | /// Write to SPI chip directly using follow mode 175 | pub fn write(&mut self, data: &[u8]) -> Result { 176 | if !self.data { 177 | self.port.flash_indar1(0xFD)?; 178 | self.data = true; 179 | } 180 | self.port.flash_write(data) 181 | } 182 | } 183 | 184 | impl Drop for SpiBus<'_, T> { 185 | fn drop(&mut self) { 186 | let _ = self.reset(); 187 | } 188 | } 189 | 190 | struct SpiRom<'a, 't, T: Smfi> { 191 | bus: &'a mut SpiBus<'t, T>, 192 | } 193 | 194 | impl<'a, 't, T: Smfi> SpiRom<'a, 't, T> { 195 | pub fn new(bus: &'a mut SpiBus<'t, T>) -> Self { 196 | Self { bus } 197 | } 198 | 199 | pub fn status(&mut self) -> Result { 200 | let mut status = [0]; 201 | 202 | self.bus.reset()?; 203 | self.bus.write(&[0x05])?; 204 | self.bus.read(&mut status)?; 205 | 206 | Ok(status[0]) 207 | } 208 | 209 | pub fn write_disable(&mut self) -> Result<()> { 210 | self.bus.reset()?; 211 | self.bus.write(&[0x04])?; 212 | 213 | // Poll status for busy and write enable flags 214 | //TODO: timeout 215 | while self.status()? & 3 != 0 {} 216 | 217 | Ok(()) 218 | } 219 | 220 | pub fn write_enable(&mut self) -> Result<()> { 221 | self.bus.reset()?; 222 | self.bus.write(&[0x06])?; 223 | 224 | // Poll status for busy and write enable flags 225 | //TODO: timeout 226 | while self.status()? & 3 != 2 {} 227 | 228 | Ok(()) 229 | } 230 | 231 | pub fn erase_chip(&mut self) -> Result<()> { 232 | self.write_enable()?; 233 | 234 | self.bus.reset()?; 235 | self.bus.write(&[0x60])?; 236 | 237 | // Poll status for busy flag 238 | //TODO: timeout 239 | while self.status()? & 1 != 0 {} 240 | 241 | self.write_disable()?; 242 | 243 | Ok(()) 244 | } 245 | 246 | pub fn erase_sector(&mut self, address: u32) -> Result { 247 | if (address & 0xFF00_0000) > 0 { 248 | return Err(Error::new( 249 | ErrorKind::InvalidInput, 250 | format!("address {:X} exceeds 24 bits", address), 251 | )); 252 | } 253 | 254 | self.write_enable()?; 255 | 256 | self.bus.reset()?; 257 | self.bus.write(&[ 258 | 0xD7, 259 | (address >> 16) as u8, 260 | (address >> 8) as u8, 261 | address as u8, 262 | ])?; 263 | 264 | // Poll status for busy flag 265 | //TODO: timeout 266 | while self.status()? & 1 != 0 {} 267 | 268 | self.write_disable()?; 269 | 270 | Ok(1024) 271 | } 272 | 273 | pub fn read_at(&mut self, address: u32, data: &mut [u8]) -> Result { 274 | if (address & 0xFF00_0000) > 0 { 275 | return Err(Error::new( 276 | ErrorKind::InvalidInput, 277 | format!("address {:X} exceeds 24 bits", address), 278 | )); 279 | } 280 | 281 | self.bus.reset()?; 282 | self.bus.write(&[ 283 | 0x0B, 284 | (address >> 16) as u8, 285 | (address >> 8) as u8, 286 | address as u8, 287 | 0, 288 | ])?; 289 | self.bus.read(data) 290 | } 291 | 292 | pub fn write_at(&mut self, address: u32, data: &[u8]) -> Result { 293 | if (address & 0xFF00_0000) > 0 { 294 | return Err(Error::new( 295 | ErrorKind::InvalidInput, 296 | format!("address {:X} exceeds 24 bits", address), 297 | )); 298 | } 299 | 300 | //TODO: Support programming with any length 301 | if (data.len() % 2) != 0 { 302 | return Err(Error::new( 303 | ErrorKind::InvalidInput, 304 | format!("length {} is not a multiple of 2", data.len()), 305 | )); 306 | } 307 | 308 | self.write_enable()?; 309 | 310 | for (i, word) in data.chunks_exact(2).enumerate() { 311 | self.bus.reset()?; 312 | if i == 0 { 313 | self.bus.write(&[ 314 | 0xAD, 315 | (address >> 16) as u8, 316 | (address >> 8) as u8, 317 | address as u8, 318 | word[0], 319 | word[1], 320 | ])?; 321 | } else { 322 | self.bus.write(&[0xAD, word[0], word[1]])?; 323 | } 324 | 325 | // Poll status for busy flag 326 | //TODO: timeout 327 | while self.status()? & 1 != 0 {} 328 | } 329 | 330 | self.write_disable()?; 331 | 332 | Ok(data.len()) 333 | } 334 | } 335 | 336 | impl Drop for SpiRom<'_, '_, T> { 337 | fn drop(&mut self) { 338 | let _ = self.write_disable(); 339 | } 340 | } 341 | 342 | pub struct ParallelArduino { 343 | tty: TTYPort, 344 | buffer_size: usize, 345 | } 346 | 347 | impl ParallelArduino { 348 | /// Connect to parallel port arduino using provided port 349 | pub fn new>(path: S) -> Result { 350 | let tty = serialport::new(path.as_ref(), 1_000_000) 351 | .data_bits(serialport::DataBits::Eight) 352 | .flow_control(serialport::FlowControl::None) 353 | .parity(serialport::Parity::None) 354 | .stop_bits(serialport::StopBits::One) 355 | .timeout(Duration::new(1, 0)) 356 | .open_native()?; 357 | 358 | let mut port = Self { 359 | tty, 360 | buffer_size: 0, 361 | }; 362 | // Wait until programmer is ready 363 | thread::sleep(Duration::new(1, 0)); 364 | // Check that programmer is ready 365 | port.echo()?; 366 | // Read buffer size 367 | port.update_buffer_size()?; 368 | 369 | Ok(port) 370 | } 371 | 372 | fn echo(&mut self) -> Result<()> { 373 | self.tty.write_all(&[b'E', 0, 0x76])?; 374 | 375 | let mut b = [0]; 376 | self.tty.read_exact(&mut b)?; 377 | if b[0] != 0x76 { 378 | return Err(Error::new( 379 | ErrorKind::InvalidInput, 380 | format!("received echo of {:02X} instead of {:02X}", b[0], 0x76), 381 | )); 382 | } 383 | Ok(()) 384 | } 385 | 386 | fn update_buffer_size(&mut self) -> Result<()> { 387 | self.tty.write_all(&[b'B', 0])?; 388 | 389 | let mut b = [0; 1]; 390 | self.tty.read_exact(&mut b)?; 391 | // Size is recieved data + 1 392 | self.buffer_size = (b[0] as usize) + 1; 393 | 394 | eprintln!("Buffer size: {}", self.buffer_size); 395 | Ok(()) 396 | } 397 | } 398 | 399 | impl Debugger for ParallelArduino { 400 | fn address(&mut self, address: u8) -> Result<()> { 401 | self.tty.write_all(&[b'A', address])?; 402 | 403 | Ok(()) 404 | } 405 | 406 | fn read(&mut self, data: &mut [u8]) -> Result { 407 | for chunk in data.chunks_mut(self.buffer_size) { 408 | let param = (chunk.len() - 1) as u8; 409 | self.tty.write_all(&[b'R', param])?; 410 | self.tty.read_exact(chunk)?; 411 | } 412 | 413 | Ok(data.len()) 414 | } 415 | 416 | fn write(&mut self, data: &[u8]) -> Result { 417 | for chunk in data.chunks(self.buffer_size) { 418 | let param = (chunk.len() - 1) as u8; 419 | self.tty.write_all(&[b'W', param])?; 420 | self.tty.write_all(chunk)?; 421 | 422 | let mut b = [0]; 423 | self.tty.read_exact(&mut b)?; 424 | if b[0] != param { 425 | return Err(Error::new( 426 | ErrorKind::InvalidInput, 427 | format!("received ack of {:02X} instead of {:02X}", b[0], param), 428 | )); 429 | } 430 | } 431 | 432 | Ok(data.len()) 433 | } 434 | } 435 | 436 | pub struct I2EC { 437 | address: Pio, 438 | data: Pio, 439 | } 440 | 441 | impl I2EC { 442 | pub fn new() -> Result { 443 | //TODO: check EC ID using super i/o 444 | if unsafe { libc::iopl(3) } != 0 { 445 | return Err(Error::from(io::Error::last_os_error())); 446 | } 447 | 448 | Ok(Self { 449 | address: Pio::new(0x2E), 450 | data: Pio::new(0x2F), 451 | }) 452 | } 453 | 454 | fn super_io_read(&mut self, reg: u8) -> u8 { 455 | self.address.write(reg); 456 | self.data.read() 457 | } 458 | 459 | fn super_io_write(&mut self, reg: u8, value: u8) { 460 | self.address.write(reg); 461 | self.data.write(value); 462 | } 463 | 464 | fn d2_read(&mut self, reg: u8) -> u8 { 465 | self.super_io_write(0x2E, reg); 466 | self.super_io_read(0x2F) 467 | } 468 | 469 | fn d2_write(&mut self, reg: u8, value: u8) { 470 | self.super_io_write(0x2E, reg); 471 | self.super_io_write(0x2F, value); 472 | } 473 | 474 | fn i2ec_read(&mut self, addr: u16) -> u8 { 475 | self.d2_write(0x11, (addr >> 8) as u8); 476 | self.d2_write(0x10, addr as u8); 477 | self.d2_read(0x12) 478 | } 479 | 480 | fn i2ec_write(&mut self, addr: u16, value: u8) { 481 | self.d2_write(0x11, (addr >> 8) as u8); 482 | self.d2_write(0x10, addr as u8); 483 | self.d2_write(0x12, value); 484 | } 485 | } 486 | 487 | pub struct Pmc { 488 | data: Pio, 489 | cmd: Pio, 490 | } 491 | 492 | impl Pmc { 493 | pub fn new(base: u16) -> Self { 494 | Self { 495 | data: Pio::new(base), 496 | cmd: Pio::new(base + 4), 497 | } 498 | } 499 | 500 | pub unsafe fn can_read(&mut self) -> bool { 501 | self.cmd.read() & 1 == 1 502 | } 503 | 504 | pub unsafe fn can_write(&mut self) -> bool { 505 | self.cmd.read() & 2 == 0 506 | } 507 | 508 | pub unsafe fn command(&mut self, data: u8) { 509 | //eprintln!("PMC command {:02X}", data); 510 | unsafe { while !self.can_write() {} } 511 | self.cmd.write(data); 512 | } 513 | 514 | pub unsafe fn read(&mut self) -> u8 { 515 | //eprintln!("PMC read"); 516 | unsafe { while !self.can_read() {} } 517 | self.data.read() 518 | } 519 | 520 | pub unsafe fn write(&mut self, data: u8) { 521 | //eprintln!("PMC write {:02X}", data); 522 | unsafe { while !self.can_write() {} } 523 | self.data.write(data); 524 | } 525 | 526 | pub unsafe fn acpi_read(&mut self, address: u8) -> u8 { 527 | unsafe { 528 | self.command(0x80); 529 | self.write(address); 530 | self.read() 531 | } 532 | } 533 | 534 | pub unsafe fn acpi_write(&mut self, address: u8, data: u8) { 535 | unsafe { 536 | self.command(0x81); 537 | self.write(address); 538 | self.write(data); 539 | } 540 | } 541 | } 542 | 543 | impl Smfi for Pmc { 544 | /// Set indar1 register (special case for follow mode) 545 | fn flash_indar1(&mut self, data: u8) -> Result<()> { 546 | unsafe { 547 | self.acpi_write(Address::INDAR1 as u8, data); 548 | } 549 | Ok(()) 550 | } 551 | 552 | /// Set EC-indirect flash address 553 | fn flash_address(&mut self, address: u32) -> Result<()> { 554 | unsafe { 555 | self.acpi_write(Address::INDAR3 as u8, (address >> 24) as u8); 556 | self.acpi_write(Address::INDAR2 as u8, (address >> 16) as u8); 557 | self.acpi_write(Address::INDAR1 as u8, (address >> 8) as u8); 558 | self.acpi_write(Address::INDAR0 as u8, (address) as u8); 559 | } 560 | Ok(()) 561 | } 562 | 563 | /// Read data from flash using EC-indirect mode 564 | fn flash_read(&mut self, data: &mut [u8]) -> Result { 565 | for b in data.iter_mut() { 566 | unsafe { 567 | *b = self.acpi_read(Address::INDDR as u8); 568 | } 569 | } 570 | Ok(data.len()) 571 | } 572 | 573 | /// Write data to flash using EC-indirect mode 574 | fn flash_write(&mut self, data: &[u8]) -> Result { 575 | for b in data.iter() { 576 | unsafe { 577 | self.acpi_write(Address::INDDR as u8, *b); 578 | } 579 | } 580 | Ok(data.len()) 581 | } 582 | } 583 | 584 | fn isp_inner(port: &mut T, firmware: &[u8]) -> Result<()> { 585 | // There are two supported ROM sizes, 128KiB and 256KiB 586 | let rom_size = if firmware.len() > 128 * 1024 { 587 | 256 * 1024 588 | } else { 589 | 128 * 1024 590 | }; 591 | 592 | if firmware.len() > rom_size { 593 | return Err(Error::new( 594 | ErrorKind::InvalidInput, 595 | format!( 596 | "firmware size {} exceeds rom size {}", 597 | firmware.len(), 598 | rom_size 599 | ), 600 | )); 601 | } 602 | 603 | let mut spi_bus = SpiBus::new(port, true)?; 604 | let mut spi = SpiRom::new(&mut spi_bus); 605 | 606 | let mut rom = vec![0; rom_size]; 607 | { 608 | // Read entire ROM 609 | eprintln!("SPI read"); 610 | spi.read_at(0, &mut rom)?; 611 | } 612 | 613 | eprintln!("Saving ROM to backup.rom"); 614 | fs::write("backup.rom", &rom)?; 615 | 616 | let mut matches = true; 617 | for i in 0..rom.len() { 618 | if &rom[i] != firmware.get(i).unwrap_or(&0xFF) { 619 | matches = false; 620 | break; 621 | } 622 | } 623 | 624 | if matches { 625 | eprintln!("ROM matches specified firmware"); 626 | return Ok(()); 627 | } 628 | 629 | { 630 | // Chip erase 631 | // eprintln!("SPI chip erase"); 632 | // spi.erase_chip()?; 633 | 634 | // Sector erase 635 | let mut address = 0; 636 | while address < rom_size { 637 | let mut erased = true; 638 | for &b in &rom[address..address + 1024] { 639 | if b != 0xFF { 640 | erased = false; 641 | break; 642 | } 643 | } 644 | 645 | if erased { 646 | eprintln!("SPI sector already erased {:06X}", address); 647 | address += 1024; 648 | } else { 649 | eprintln!("SPI sector erase {:06X}", address); 650 | address += spi.erase_sector(address as u32)?; 651 | } 652 | } 653 | 654 | // Read entire ROM 655 | eprintln!("SPI read"); 656 | spi.read_at(0, &mut rom)?; 657 | } 658 | 659 | // Verify chip erase 660 | for i in 0..rom.len() { 661 | if rom[i] != 0xFF { 662 | return Err(Error::new( 663 | ErrorKind::InvalidInput, 664 | format!( 665 | "Failed to erase: {:X} is {:X} instead of {:X}", 666 | i, rom[i], 0xFF 667 | ), 668 | )); 669 | } 670 | } 671 | 672 | //TODO: Set write disable on error 673 | // Program 674 | { 675 | // Auto address increment word program 676 | if (spi.bus.port as &mut dyn Any).is::() { 677 | spi.write_enable()?; 678 | 679 | { 680 | eprintln!("SPI AAI word program (accelerated)"); 681 | let port = (spi.bus.port as &mut dyn Any) 682 | .downcast_mut::() 683 | .unwrap(); 684 | for (i, chunk) in firmware.chunks(port.buffer_size).enumerate() { 685 | eprint!(" program {} / {}\r", i * port.buffer_size, firmware.len()); 686 | 687 | let param = (chunk.len() - 1) as u8; 688 | port.tty.write_all(&[b'P', param])?; 689 | port.tty.write_all(chunk)?; 690 | 691 | let mut b = [0]; 692 | port.tty.read_exact(&mut b)?; 693 | if b[0] != param { 694 | return Err(Error::new( 695 | ErrorKind::InvalidInput, 696 | format!("received ack of {:02X} instead of {:02X}", b[0], param), 697 | )); 698 | } 699 | } 700 | eprintln!(" program {} / {}", firmware.len(), firmware.len()); 701 | } 702 | 703 | spi.write_disable()?; 704 | } else { 705 | eprintln!("SPI AAI word program"); 706 | spi.write_at(0, firmware)?; 707 | } 708 | 709 | // Read entire ROM 710 | eprintln!("SPI read"); 711 | spi.read_at(0, &mut rom)?; 712 | } 713 | 714 | // Verify program 715 | for i in 0..rom.len() { 716 | if &rom[i] != firmware.get(i).unwrap_or(&0xFF) { 717 | return Err(Error::new( 718 | ErrorKind::InvalidInput, 719 | format!( 720 | "Failed to program: {:X} is {:X} instead of {:X}", 721 | i, rom[i], firmware[i] 722 | ), 723 | )); 724 | } 725 | } 726 | 727 | eprintln!("Successfully programmed SPI ROM"); 728 | 729 | Ok(()) 730 | } 731 | 732 | fn isp(internal: bool, file: &str) -> Result<()> { 733 | // Read firmware data 734 | let firmware = { 735 | let mut firmware = fs::read(file)?; 736 | 737 | // Truncate 0xFF bytes 738 | while firmware.last() == Some(&0xFF) { 739 | firmware.pop(); 740 | } 741 | 742 | // Make sure firmware length is a multiple of word size 743 | while firmware.len() % 2 != 0 { 744 | firmware.push(0xFF); 745 | } 746 | 747 | firmware 748 | }; 749 | 750 | if internal { 751 | unsafe { 752 | if libc::iopl(3) < 0 { 753 | eprintln!( 754 | "Failed to get I/O permission: {}", 755 | io::Error::last_os_error() 756 | ); 757 | process::exit(1); 758 | } 759 | 760 | //TODO: return error 761 | let _ec = EcFlash::new(true).expect("Failed to find EC"); 762 | 763 | // Wait for any key releases 764 | eprintln!("Waiting 5 seconds for all keys to be released"); 765 | thread::sleep(Duration::new(5, 0)); 766 | 767 | eprintln!("Sync"); 768 | let _ = process::Command::new("sync").status(); 769 | 770 | let mut pmc1 = Pmc::new(0x62); 771 | let mut pmc3 = Pmc::new(0x6A); 772 | // Enter scratch rom 773 | pmc1.command(0xEC); 774 | if pmc1.read() == 0x76 { 775 | eprintln!("Entered scratch ROM"); 776 | 777 | let res = isp_inner(&mut pmc3, &firmware); 778 | 779 | eprintln!("Sync"); 780 | let _ = process::Command::new("sync").status(); 781 | 782 | eprintln!("System will shut off in 5 seconds"); 783 | thread::sleep(Duration::new(5, 0)); 784 | 785 | eprintln!("Sync"); 786 | let _ = process::Command::new("sync").status(); 787 | 788 | // Will currently power off system 789 | pmc3.command(0xEC); 790 | 791 | match res { 792 | Ok(()) => { 793 | eprintln!("Successfully flashed EC"); 794 | 795 | // Shut down 796 | process::Command::new("shutdown") 797 | .status() 798 | .expect("failed to run shutdown"); 799 | 800 | Ok(()) 801 | } 802 | Err(err) => { 803 | eprintln!("Failed to flash EC: {}", err); 804 | Err(err) 805 | } 806 | } 807 | } else { 808 | //TODO: return error 809 | panic!("Failed to enter scratch ROM") 810 | } 811 | } 812 | } else { 813 | // Open arduino console 814 | let mut port = ParallelArduino::new("/dev/ttyACM0")?; 815 | 816 | // Read ID 817 | let mut id = [0; 3]; 818 | port.address(0)?; 819 | port.read(&mut id[0..1])?; 820 | port.address(1)?; 821 | port.read(&mut id[1..2])?; 822 | port.address(2)?; 823 | port.read(&mut id[2..3])?; 824 | 825 | let ecid = ((id[0] as u16) << 8) | (id[1] as u16); 826 | 827 | eprintln!("ID: {:04X} VER: {}", ecid, id[2]); 828 | assert!(EC_KNOWN_IDS.contains(&ecid), "Unknown ID: {:04X}", ecid); 829 | 830 | isp_inner(&mut port, &firmware) 831 | } 832 | } 833 | 834 | fn main() { 835 | let mut file_opt = None; 836 | let mut internal = false; 837 | for arg in env::args().skip(1) { 838 | if arg == "--internal" { 839 | internal = true; 840 | } else { 841 | file_opt = Some(arg); 842 | } 843 | } 844 | //TODO: better errors 845 | let file = file_opt.expect("no firmware file provided"); 846 | isp(internal, &file).expect("failed to flash"); 847 | } 848 | -------------------------------------------------------------------------------- /examples/read.rs: -------------------------------------------------------------------------------- 1 | extern crate ecflash; 2 | 3 | use ecflash::{EcFlash, Flasher}; 4 | use std::{fs, io, process}; 5 | 6 | fn main() { 7 | unsafe extern "C" { 8 | fn iopl(level: isize) -> isize; 9 | } 10 | 11 | // Get I/O Permission 12 | unsafe { 13 | if iopl(3) < 0 { 14 | eprintln!( 15 | "Failed to get I/O permission: {}", 16 | io::Error::last_os_error() 17 | ); 18 | process::exit(1); 19 | } 20 | 21 | let ec = EcFlash::new(true).expect("Failed to find EC"); 22 | 23 | let mut flasher = Flasher::new(ec); 24 | 25 | if flasher.start() == Ok(51) { 26 | if let Ok(data) = flasher.read(|x| eprint!("\r{} KB", x / 1024)) { 27 | eprintln!(); 28 | let _ = fs::write("read.rom", data); 29 | } else { 30 | eprintln!("Failed to read data"); 31 | } 32 | 33 | let _ = flasher.stop(); 34 | } else { 35 | eprintln!("Failed to start flasher"); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /examples/tcpc.rs: -------------------------------------------------------------------------------- 1 | extern crate ecflash; 2 | 3 | use ecflash::EcFlash; 4 | use std::{io, process}; 5 | 6 | fn tcpc_read(ec: &mut EcFlash, command: u8) -> Result { 7 | let mut buf = [0x2c, command, 0x00, 0x00]; 8 | 9 | unsafe { 10 | ec.fcommand(0x76, 0x10, &mut buf)?; 11 | } 12 | 13 | Ok((buf[2] as u16) | ((buf[3] as u16) << 8)) 14 | } 15 | 16 | fn tcpc_test() -> Result<(), ()> { 17 | let mut ec = EcFlash::new(true).map_err(|_| ())?; 18 | 19 | let mut i = 0; 20 | while i < 256 { 21 | if i % 16 == 0 { 22 | if i == 0 { 23 | print!(" "); 24 | for j in 0..16 { 25 | print!(" _{:01X}", j); 26 | } 27 | } 28 | println!(); 29 | print!("{:02X}:", i); 30 | } 31 | 32 | let word = tcpc_read(&mut ec, i as u8)?; 33 | 34 | print!(" {:02X}", word as u8); 35 | print!(" {:02X}", (word >> 8) as u8); 36 | 37 | i += 2; 38 | } 39 | println!(); 40 | 41 | Ok(()) 42 | } 43 | 44 | fn main() { 45 | unsafe extern "C" { 46 | fn iopl(level: isize) -> isize; 47 | } 48 | 49 | // Get I/O Permission 50 | unsafe { 51 | if iopl(3) < 0 { 52 | eprintln!( 53 | "Failed to get I/O permission: {}", 54 | io::Error::last_os_error() 55 | ); 56 | process::exit(1); 57 | } 58 | } 59 | 60 | tcpc_test().expect("Failed to run TCPM test"); 61 | } 62 | -------------------------------------------------------------------------------- /src/file.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::missing_safety_doc)] 2 | 3 | use alloc::string::String; 4 | use alloc::vec::Vec; 5 | 6 | use super::Ec; 7 | 8 | pub struct EcFile(Vec); 9 | 10 | impl EcFile { 11 | pub unsafe fn get_str(&mut self, key: &[u8]) -> String { 12 | let mut string = String::new(); 13 | 14 | let mut i = 0; 15 | let bytes = self.0.iter(); 16 | for &byte in bytes { 17 | loop { 18 | if i < key.len() { 19 | if byte == key[i] { 20 | i += 1; 21 | break; 22 | } else if i == 0 { 23 | break; 24 | } else { 25 | i = 0; 26 | } 27 | } else if byte == b'$' { 28 | return string; 29 | } else { 30 | string.push(byte as char); 31 | break; 32 | } 33 | } 34 | } 35 | 36 | string 37 | } 38 | 39 | pub fn new(data: Vec) -> Self { 40 | EcFile(data) 41 | } 42 | } 43 | 44 | impl Ec for EcFile { 45 | fn size(&mut self) -> usize { 46 | self.0.len() 47 | } 48 | 49 | fn project(&mut self) -> String { 50 | unsafe { self.get_str(b"PRJ:") } 51 | } 52 | 53 | fn version(&mut self) -> String { 54 | let mut version = unsafe { self.get_str(b"VER:") }; 55 | while version.starts_with(' ') { 56 | version.remove(0); 57 | } 58 | version 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/flash.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::missing_safety_doc)] 2 | // TODO: Use real errors 3 | #![allow(clippy::result_unit_err)] 4 | 5 | use alloc::string::String; 6 | 7 | use super::Ec; 8 | use super::io::{inb, outb}; 9 | 10 | const TIMEOUT: usize = 100000; 11 | 12 | pub struct EcFlash { 13 | primary: bool, 14 | data_port: u16, 15 | cmd_port: u16, 16 | } 17 | 18 | impl EcFlash { 19 | pub unsafe fn sts(&mut self) -> u8 { 20 | unsafe { inb(self.cmd_port) } 21 | } 22 | 23 | pub unsafe fn can_read(&mut self) -> bool { 24 | unsafe { self.sts() & 1 == 1 } 25 | } 26 | 27 | pub unsafe fn wait_read(&mut self, mut timeout: usize) -> Result<(), ()> { 28 | while !unsafe { self.can_read() } && timeout > 0 { 29 | timeout -= 1; 30 | } 31 | 32 | if timeout == 0 { Err(()) } else { Ok(()) } 33 | } 34 | 35 | pub unsafe fn can_write(&mut self) -> bool { 36 | unsafe { self.sts() & 2 == 0 } 37 | } 38 | 39 | pub unsafe fn wait_write(&mut self, mut timeout: usize) -> Result<(), ()> { 40 | while !unsafe { self.can_write() } && timeout > 0 { 41 | timeout -= 1; 42 | } 43 | 44 | if timeout == 0 { Err(()) } else { Ok(()) } 45 | } 46 | 47 | pub unsafe fn flush(&mut self) -> Result<(), ()> { 48 | let mut i = TIMEOUT; 49 | while unsafe { self.can_read() } && i > 0 { 50 | unsafe { inb(self.data_port) }; 51 | i -= 1; 52 | } 53 | 54 | if i == 0 { Err(()) } else { Ok(()) } 55 | } 56 | 57 | pub unsafe fn cmd(&mut self, data: u8) -> Result<(), ()> { 58 | unsafe { 59 | self.wait_write(TIMEOUT)?; 60 | outb(self.cmd_port, data); 61 | self.wait_write(TIMEOUT) 62 | } 63 | } 64 | 65 | pub unsafe fn read(&mut self) -> Result { 66 | unsafe { 67 | self.wait_read(TIMEOUT)?; 68 | Ok(inb(self.data_port)) 69 | } 70 | } 71 | 72 | pub unsafe fn write(&mut self, data: u8) -> Result<(), ()> { 73 | unsafe { 74 | self.wait_write(TIMEOUT)?; 75 | outb(self.data_port, data); 76 | self.wait_write(TIMEOUT) 77 | } 78 | } 79 | 80 | pub unsafe fn get_param(&mut self, param: u8) -> Result { 81 | unsafe { 82 | self.cmd(0x80)?; 83 | self.write(param)?; 84 | self.read() 85 | } 86 | } 87 | 88 | pub unsafe fn set_param(&mut self, param: u8, data: u8) -> Result<(), ()> { 89 | unsafe { 90 | self.cmd(0x81)?; 91 | self.write(param)?; 92 | self.write(data) 93 | } 94 | } 95 | 96 | pub unsafe fn fcommand(&mut self, cmd: u8, dat: u8, buf: &mut [u8; 4]) -> Result<(), ()> { 97 | unsafe { 98 | self.set_param(0xF9, dat)?; 99 | self.set_param(0xFA, buf[0])?; 100 | self.set_param(0xFB, buf[1])?; 101 | self.set_param(0xFC, buf[2])?; 102 | self.set_param(0xFD, buf[3])?; 103 | 104 | self.set_param(0xF8, cmd)?; 105 | 106 | buf[0] = self.get_param(0xFA)?; 107 | buf[1] = self.get_param(0xFB)?; 108 | buf[2] = self.get_param(0xFC)?; 109 | buf[3] = self.get_param(0xFD)?; 110 | 111 | self.set_param(0xF8, 0x00) 112 | } 113 | } 114 | 115 | pub unsafe fn get_str(&mut self, index: u8) -> Result { 116 | let mut string = String::new(); 117 | 118 | unsafe { self.cmd(index)? }; 119 | for _i in 0..16 { 120 | let byte = unsafe { self.read()? }; 121 | if byte == b'$' { 122 | break; 123 | } else { 124 | string.push(byte as char); 125 | } 126 | } 127 | 128 | Ok(string) 129 | } 130 | 131 | pub fn new(primary: bool) -> Result { 132 | // Probe for Super I/O chip 133 | let id = unsafe { 134 | outb(0x2e, 0x20); 135 | let a = inb(0x2f); 136 | outb(0x2e, 0x21); 137 | let b = inb(0x2f); 138 | ((a as u16) << 8) | (b as u16) 139 | }; 140 | 141 | if id != 0x8587 && id != 0x5570 { 142 | return Err(format!("Unknown EC ID: 0x{:>04X}", id)); 143 | } 144 | 145 | let (data_port, cmd_port) = if primary { (0x62, 0x66) } else { (0x68, 0x6c) }; 146 | 147 | let ec = Self { 148 | primary, 149 | data_port, 150 | cmd_port, 151 | }; 152 | 153 | Ok(ec) 154 | } 155 | } 156 | 157 | impl Ec for EcFlash { 158 | fn size(&mut self) -> usize { 159 | let _ = unsafe { self.flush() }; 160 | 161 | if self.primary && unsafe { self.get_param(0xE5) } == Ok(0x80) { 162 | 128 * 1024 163 | } else { 164 | 64 * 1024 165 | } 166 | } 167 | 168 | fn project(&mut self) -> String { 169 | let _ = unsafe { self.flush() }; 170 | 171 | unsafe { self.get_str(0x92) }.unwrap_or_default() 172 | } 173 | 174 | fn version(&mut self) -> String { 175 | let _ = unsafe { self.flush() }; 176 | 177 | let mut version = unsafe { self.get_str(0x93) }.unwrap_or_default(); 178 | version.insert_str(0, "1."); 179 | version 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /src/flasher.rs: -------------------------------------------------------------------------------- 1 | #![allow(clippy::missing_safety_doc)] 2 | // TODO: Use real errors 3 | #![allow(clippy::result_unit_err)] 4 | 5 | use alloc::vec::Vec; 6 | 7 | use super::{Ec, EcFlash}; 8 | 9 | pub struct Flasher { 10 | ec: EcFlash, 11 | pub size: usize, 12 | } 13 | 14 | impl Flasher { 15 | pub fn new(mut ec: EcFlash) -> Self { 16 | let size = ec.size(); 17 | Self { ec, size } 18 | } 19 | 20 | unsafe fn enter_follow_mode(&mut self) -> Result<(), ()> { 21 | unsafe { self.ec.cmd(1) } 22 | } 23 | 24 | unsafe fn spi_cmd(&mut self, cmd: u8) -> Result<(), ()> { 25 | unsafe { 26 | self.ec.cmd(2)?; 27 | self.ec.cmd(cmd) 28 | } 29 | } 30 | 31 | unsafe fn spi_write(&mut self, value: u8) -> Result<(), ()> { 32 | unsafe { 33 | self.ec.cmd(3)?; 34 | self.ec.cmd(value) 35 | } 36 | } 37 | 38 | unsafe fn spi_read(&mut self) -> Result { 39 | unsafe { 40 | self.ec.cmd(4)?; 41 | self.ec.read() 42 | } 43 | } 44 | 45 | unsafe fn exit_follow_mode(&mut self) -> Result<(), ()> { 46 | unsafe { self.ec.cmd(5) } 47 | } 48 | 49 | unsafe fn spi_wait(&mut self) -> Result<(), ()> { 50 | unsafe { 51 | self.enter_follow_mode()?; 52 | self.spi_cmd(5)?; 53 | while self.spi_read()? & 1 > 0 {} 54 | self.exit_follow_mode() 55 | } 56 | } 57 | 58 | unsafe fn spi_write_enable(&mut self) -> Result<(), ()> { 59 | unsafe { 60 | self.spi_wait()?; 61 | self.enter_follow_mode()?; 62 | self.spi_cmd(6)?; 63 | //TODO: extra spi command 80 based on device id 0xbf 64 | self.enter_follow_mode()?; 65 | self.spi_cmd(5)?; 66 | while self.spi_read()? & 3 != 2 {} 67 | self.exit_follow_mode() 68 | } 69 | } 70 | 71 | unsafe fn spi_write_disable(&mut self) -> Result<(), ()> { 72 | unsafe { 73 | self.spi_wait()?; 74 | self.enter_follow_mode()?; 75 | self.spi_cmd(4)?; 76 | self.enter_follow_mode()?; 77 | self.spi_cmd(5)?; 78 | while self.spi_read()? & 2 > 0 {} 79 | self.exit_follow_mode() 80 | } 81 | } 82 | 83 | pub unsafe fn start(&mut self) -> Result { 84 | unsafe { 85 | self.ec.cmd(0xDC)?; 86 | self.ec.read() 87 | } 88 | } 89 | 90 | pub unsafe fn read(&mut self, callback: F) -> Result, ()> { 91 | let mut buf = Vec::with_capacity(self.size); 92 | 93 | unsafe { 94 | for sector in 0..self.size / 65536 { 95 | self.spi_write_disable()?; 96 | self.spi_wait()?; 97 | 98 | self.enter_follow_mode()?; 99 | 100 | self.spi_cmd(0x0B)?; 101 | self.spi_write(sector as u8)?; 102 | self.spi_write(0)?; 103 | self.spi_write(0)?; 104 | self.spi_write(0)?; 105 | 106 | for _block in 0..64 { 107 | for _ in 0..1024 { 108 | buf.push(self.spi_read()?); 109 | } 110 | callback(buf.len()); 111 | } 112 | 113 | self.spi_wait()?; 114 | } 115 | } 116 | 117 | Ok(buf) 118 | } 119 | 120 | pub unsafe fn erase(&mut self, callback: F) -> Result<(), ()> { 121 | for sector in 0..self.size / 65536 { 122 | for block in 0..64 { 123 | let index = sector * 65536 + block * 1024; 124 | 125 | unsafe { 126 | self.spi_write_enable()?; 127 | self.enter_follow_mode()?; 128 | self.spi_cmd(0xD7)?; 129 | self.spi_write(sector as u8)?; 130 | self.spi_write(block as u8)?; 131 | self.spi_write(0)?; 132 | self.exit_follow_mode()?; 133 | self.spi_wait()?; 134 | } 135 | 136 | callback(index + 1024); 137 | } 138 | } 139 | 140 | Ok(()) 141 | } 142 | 143 | pub unsafe fn write(&mut self, buf: &[u8], callback: F) -> Result<(), ()> { 144 | for sector in 0..self.size / 65536 { 145 | unsafe { 146 | self.spi_write_enable()?; 147 | 148 | for block in 0..64 { 149 | let index = sector * 65536 + block * 1024; 150 | 151 | for word in 0..512 { 152 | self.enter_follow_mode()?; 153 | self.spi_cmd(0xAD)?; 154 | if block == 0 && word == 0 { 155 | self.spi_write(sector as u8)?; 156 | self.spi_write((sector >> 8) as u8)?; 157 | self.spi_write((sector >> 16) as u8)?; 158 | } 159 | self.spi_write(buf.get(index + word * 2).map_or(0xFF, |x| *x))?; 160 | self.spi_write(buf.get(index + word * 2 + 1).map_or(0xFF, |x| *x))?; 161 | self.spi_wait()?; 162 | } 163 | 164 | callback(index + 1024); 165 | } 166 | 167 | self.spi_write_disable()?; 168 | self.spi_wait()?; 169 | } 170 | } 171 | 172 | Ok(()) 173 | } 174 | 175 | pub unsafe fn stop(&mut self) -> Result<(), ()> { 176 | unsafe { 177 | self.ec.cmd(0x95)?; 178 | self.ec.cmd(0xFC) 179 | } 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /src/io.rs: -------------------------------------------------------------------------------- 1 | #[inline(always)] 2 | pub unsafe fn inb(port: u16) -> u8 { 3 | let value: u8; 4 | unsafe { 5 | core::arch::asm!("in al, dx", out("al") value, in("dx") port, options(nostack)); 6 | } 7 | value 8 | } 9 | 10 | #[inline(always)] 11 | pub unsafe fn outb(port: u16, value: u8) { 12 | unsafe { 13 | core::arch::asm!("out dx, al", in("al") value, in("dx") port, options(nostack)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | #[macro_use] 4 | extern crate alloc; 5 | 6 | use alloc::string::String; 7 | 8 | pub use self::file::EcFile; 9 | pub use self::flash::EcFlash; 10 | pub use self::flasher::Flasher; 11 | 12 | mod file; 13 | mod flash; 14 | mod flasher; 15 | mod io; 16 | 17 | pub trait Ec { 18 | fn size(&mut self) -> usize; 19 | fn project(&mut self) -> String; 20 | fn version(&mut self) -> String; 21 | } 22 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate ecflash; 2 | 3 | use std::fmt::Display; 4 | use std::fs::File; 5 | use std::io::{BufWriter, Error, Read, Write, stderr, stdout}; 6 | use std::{env, process}; 7 | 8 | use ecflash::{Ec, EcFile, EcFlash}; 9 | 10 | fn validate T>(mut f: F, attempts: usize) -> Result { 11 | for _attempt_i in 0..attempts { 12 | let a = f(); 13 | let b = f(); 14 | if a == b { 15 | return Ok(a); 16 | } else { 17 | let _ = writeln!(stderr(), "Attempt {}: {} != {}", _attempt_i, a, b); 18 | } 19 | } 20 | Err(()) 21 | } 22 | 23 | fn main() { 24 | unsafe extern "C" { 25 | fn iopl(level: isize) -> isize; 26 | } 27 | 28 | // Get I/O Permission 29 | unsafe { 30 | if iopl(3) < 0 { 31 | let _ = writeln!( 32 | stderr(), 33 | "Failed to get I/O permission: {}", 34 | Error::last_os_error() 35 | ); 36 | process::exit(1); 37 | } 38 | } 39 | 40 | let mut ecs: Vec<(String, Box)> = Vec::new(); 41 | 42 | for arg in env::args().skip(1) { 43 | match arg.as_str() { 44 | "-1" => match EcFlash::new(true) { 45 | Ok(ec_flash) => { 46 | ecs.push((String::new(), Box::new(ec_flash))); 47 | } 48 | Err(err) => { 49 | let _ = writeln!(stderr(), "Failed to open EC flash 1: {}", err); 50 | process::exit(1); 51 | } 52 | }, 53 | "-2" => match EcFlash::new(false) { 54 | Ok(ec_flash) => { 55 | ecs.push((String::new(), Box::new(ec_flash))); 56 | } 57 | Err(err) => { 58 | let _ = writeln!(stderr(), "Failed to open EC flash 2: {}", err); 59 | process::exit(1); 60 | } 61 | }, 62 | _ => match File::open(&arg) { 63 | Ok(mut ec_file) => { 64 | let mut data = Vec::new(); 65 | match ec_file.read_to_end(&mut data) { 66 | Ok(_) => ecs.push((arg, Box::new(EcFile::new(data)))), 67 | Err(err) => { 68 | let _ = writeln!(stderr(), "Failed to read EC file '{}': {}", arg, err); 69 | process::exit(1); 70 | } 71 | } 72 | } 73 | Err(err) => { 74 | let _ = writeln!(stderr(), "Failed to open EC file '{}': {}", arg, err); 75 | process::exit(1); 76 | } 77 | }, 78 | } 79 | } 80 | 81 | let mut stdout = BufWriter::new(stdout()); 82 | 83 | for (name, mut ec) in ecs { 84 | if name.is_empty() { 85 | let _ = writeln!(stdout, "EC Flash"); 86 | } else { 87 | let _ = writeln!(stdout, "EC File {}:", name); 88 | } 89 | 90 | match validate(|| ec.project(), 8) { 91 | Ok(project) => { 92 | let _ = writeln!(stdout, " Project: {}", project); 93 | } 94 | Err(()) => { 95 | let _ = writeln!(stderr(), "Failed to read EC project"); 96 | process::exit(1); 97 | } 98 | } 99 | 100 | match validate(|| ec.version(), 8) { 101 | Ok(version) => { 102 | let _ = writeln!(stdout, " Version: {}", version); 103 | } 104 | Err(()) => { 105 | let _ = writeln!(stderr(), "Failed to read EC version"); 106 | process::exit(1); 107 | } 108 | } 109 | 110 | match validate(|| ec.size(), 8) { 111 | Ok(size) => { 112 | let _ = writeln!(stdout, " Size: {} KB", size / 1024); 113 | } 114 | Err(()) => { 115 | let _ = writeln!(stderr(), "Failed to read EC size"); 116 | process::exit(1); 117 | } 118 | } 119 | } 120 | 121 | let _ = stdout.flush(); 122 | } 123 | --------------------------------------------------------------------------------