[GSoC] Multiple status registers, block protection and OTP support, wrap-up (1/2)

Hello! 🙂

GSoC 2016 coding period has come to an end and mentor’s evaluating students this week. It has been an enriching 13 weeks of reading datasheets, designing structures, coding, learning and hanging out over IRC! 😛 I’d like to take this opportunity to present my work and details on how to use it. 🙂

Firstly, to offer context to the work, here is a list of public mails and blog posts. These should give an idea as to how the discussions and work evolved. A lot of the discussions have happened over IRC, but #flashrom does not keep any logs.

The patch sets that I sent to the mailing list can be found at –

  1. Multiple status register and access protection infrastructure
  2. OTP/Security registers infrastructure
  3. Dummy chips

You can also find these over at flashrom’s patchwork. The mailing list is where the review happens (although a better alternative, IMHO, is Gerrit which coreboot uses). The patches aren’t currently merged and are under review. In any case, you are most welcome to join review (which will likely be very helpful for me). 🙂 If you’d like to look at something more on the bleeding edge, then I invite you to my GitHub.

Now, moving on how to use the work. The most exhaustive documentation on how to use it is the code itself :P, but in the following list I attempt to list scenarios –

  • For SPI chips that have multiple status registers, flashrom’s verbose output will print the status register bits and there values. Most bits are named, i.e., the datasheet refers to the bit by an abbreviation, for instance, WEL for Write Enable Latch, WIP for Work In Progress, BP for Block Protect, LB for Lock Bit and so on. The verbose output will print these names, both in abbreviated and long forms, for most chips (and these abbreviations tend to be generic across many manufacturers). However, the process for adding new chips that leverage this, and adding new bits, is a fairly easy task (I would invite you to have a look at the code 😉 for more details). The verbose output also prints the write protection mode for status register(s) in effect (software protected, hardware protected, power cycle lock down and so on).
  • In case you want to disable or enable (a particular type) write protection for status register, you can use the --wp-disable or --wp-enable[=MODE] respectively (where MODE is either of software, hardware, power cycle or permanent – you are encouraged to have a look at the man page 🙂 for more details)
  • In case you want to protect a particular range of an SPI chip from writes or erases, you will need to alter the BP, TB or SEC bits. Currently, there is a CLI that will enable you to accomplish all that. 😛 First, you’ll want to look at the list of ranges your SPI chip supports – run flashrom with --wp-list. Take note of the start address and the length of the memory range you want to protect. Then again run flashrom with --wp-set-range start=0xfff000,len=4 (0xfff000 and 4 are for representational purpose only). By now the memory range is protected, but you can additionally enable status register write protection by following what the foregoing point described.
  • For SPI chips that support OTP, you can read, write and erase OTP regions (of course for supported chips :P). For OTP operations, you have at your disposal --print-otp-status, --read-otp [,reg=], --write-otp file=[,reg=], --erase-otp [reg=] and --lock-otp [reg=]. You can read the OTP memory to a file, or you can write to the OTP region from a file, very much like reading and writing from/to SPI chip. For more details, I would again like to point you to the man page. 🙂

Since this is a work-in-progress, the CLI may change (and is very likely). Currently around 10% of SPI chips use this new infrastructure. Models of a few manufacturers (and especially exotic ones like Atmel) are yet to be fully incorporated. You are most welcome to add support for new chips or update the existing ones to support new infrastructure. 🙂

I would like to sincerely thank my mentors Stefan and David for their support and help. I am indebted to them for this opportunity and I hope that we continue to share this relationship in the future while I continue to explore and contribute to flashrom. It has been a pleasure getting to know each of them. I’d also like to thank Urja for pitching in from time to time 🙂 It was fun hanging out over IRC and helping folks asking questions there. And I am looking forward to it for years to come. 😛

In the next and final part of this post, I will highlight how we intend to improve upon this work in the future, where it will be headed and what more we have in store, so please stay tuned. 😉 Phew, this was a long one, and rightly so as it attempts to summarise a great deal of experiences. If you have any feedback, questions or comments on the blogs or code, please feel to ping me on #flashrom where I am known as hatim. You can also email me at hatim@hatimak.me.

Thanks, and looking forward to hearing from you. 🙂 See you in the next and final part.

[GSoC] Better RISC-V support, wrap-up

In less than an hour, Google Summer of Code 2016 will be over (at least for us students). In this blog post, I will describe how you can use coreboot on RISC-V.

You can find the complete list of commits that I made during GSoC with this gerrit query.

The details

Compiling spike, the RISC-V instruction-set-level simulator

Spike, also known as riscv-isa-sim, is the reference implementation of RISC-V, and the only RISC-V platform that is currently known to work with coreboot (QEMU is nominally also supported, but the corresponding coreboot code has not been updated in a while).

First, you need to build and install libfesvr:

Then, you can compile and install spike:

  • Clone the spike git repository.
  • Apply the patch in this pull request to make console output possible.
  • Open riscv/processor.cc in a text editor and find processor_t::get_csr. Add a line that reads case CSR_MTIME: return 0;.
  • run ./configure --prefix="$HOME" --with-fesvr="$HOME" && make && make install

Compiling coreboot for RISC-V

  • Clone the coreboot git repository, if you haven’t already
  • Apply Iru Cai’s patch that updates the toolchain to GCC 6.1. You will currently have to fix a merge conflict when you apply this patch, but it’s an easy one.
  • Run make crossgcc-riscv
  • Run make menuconfig to configure coreboot. Select Emulation and SPIKE usb riscv in the Mainboard menu.
  • Run make
  • Run util/riscvtools/make-spike-elf.sh build/coreboot.rom build/coreboot.elf
  • Start coreboot by running spike build/coreboot.elf. You should see a few pages of output, ending in Payload not loaded.

Compiling and running Linux

  • Clone the riscv-linux git repository and check out the priv-1.9 branch
  • Apply this patch that allows linux to be started in machine-mode.
  • Download a copy linux 4.6.x from kernel.org, and unpack it. I’ll assume version 4.6.2 is used.
  • cd into linux-4.6.2/arch and symlink the arch/riscv directory from riscv-linux
  • Back in linux-4.6.2, run make O=build ARCH=riscv defconfig; cd into the newly created build directory.
  • Run make ARCH=riscv menuconfig. In the “General Setup” menu of the linux menuconfig, enter path/to/coreboot/util/crossgcc/xgcc/bin/riscv64-elf- as the cross-compiler tool prefix.
  • Run make ARCH=riscv vmlinux to compile linux.
  • Open vmlinux in a hex editor, such as hexer. Change the 8-byte number at 0x18 to 00 00 00 90 00 00 00 00; Add 00 00 00 90 00 00 00 00 to the numbers at 0x58 and 0x90, to load linux at physical addresses within RAM. It’s unfortunate that I have to recommend this step, but I did not come up with a better fix yet.

Next, you need to add vmlinux to coreboot:

  • Return to the coreboot directory.
  • Apply the remaining coreboot patches that are tagged riscv.
  • In the Payload menu, select An ELF executable payload. Instead of payload.elf, select the vmlinux file.
  • Run make and util/riscvtools/make-spike-elf.sh build/coreboot.rom build/coreboot.elf again.
  • Run spike build/coreboot.elf. You should now see a Linux boot, at least partially.

Future work

Even though my GSoC is over, coreboot’s support for RISC-V can still be improved, and I intend to fix at least some of the following things:

  • As you can see above, running coreboot and linux on RISC-V currently isn’t straight-forward, but involves a few manual steps.
  • There are other RISC-V platforms that I’d like to see coreboot on, such as lowRISC.
  • Linux does not completely boot, i.e. into userspace. There are still some bugs to be ironed out.
  • Automatic testing could be used to detect regressions.
  • I only tested coreboot on RISC-V with Linux; support for other operating systems or payloads is welcome.


I’d like to thank Ron Minnich and Furquan Shaikh for being good mentors, and everyone in the coreboot community for being helpful and friendly.

[GSoC] Better RISC-V Support, week #10

This past week, I worked on the virtual memory initialization code of coreboot on RISC-V. The first part of this was to update encoding.h a file that defines constants such as bit masks which are necessary for interacting with RISC-V’s Control and Status Registers. As a result, I also had to change a few files that relied on outdated constants. Then I wrote some code to walk the page table structures, and fixed one or two bugs in the page table setup code. Unfortunately my patches aren’t as finished as I would like them to be.

When I tested my changes with a Linux payload (which I had to edit the ELF headers of, because Linux uses virtual addresses, while cbfstool and the SELF loader use physical addresses), I stumbled upon another strange error: I get a store access fault in the instruction of the trap handler that saves the first register, even if I initialize the stack pointer to a value that’s within the RAM. When the trap handler runs again to handle this store access fault, it runs without any problems. This fault is especially confusing, because machine mode should always be able to access RAM through its physical addresses.

What’s next?

During the next week, I’ll be traveling and won’t be able to work on coreboot. When I return, I will rework my patches so they can be merged, and hopefully understand the aforementioned access fault problem. Properly set-up page tables should bring me a step closer to running Linux on coreboot/RISC-V (without bbl in the middle).

If time permits, I will start porting coreboot to the Nexys 4 DDR devboard.

[GSoC] Multiple status registers, block protection and OTP support, week #6, 7, 8 and 9

Hello! I have been away for some time now, so this is going to be a longer post. I hope you have missed hearing from me 😛 In this post I will talk about my work in the weeks post-midterm evaluations. After a discussion with my mentors in the midterm evaluations week, we decided to shift focus towards the first three phases of my GSoC proposal for the remainder of the duration. Work on the final phase will be done after GSoC along with the more long-term goals that have come up as I have been making progress.

I submitted patches (finally ;)) to the mailing list. The set of patches adds multiple status register, and block protection infrastructure. I have also added a command-line interface to expose the new functionality. Although I am not sure that the exact wording of the CLI is most optimum, but I did not spend a lot of time on that because IMO it is a rather subjective issue and altering it is not a difficult task. The set of patches also adds support for new infrastructure to around 90 existing chips. I am still waiting to receive feedback and review on them. (My mentors had been slightly busier then.) I am also investigating adding support for access protection to non-SPI chips. This isn’t on the highest priority (more like a long-term goal), but once the SPI infrastructure gets merged, I will begin writing code for that.

Based on the initial prototypes I built (here, here and here), we had decided to use pointers to new structs instead of fully embedding them in struct flashchip. This decision really started to show when I was adding support for existing chips – with only 25 unique struct definitions we were able to support those 90 chips! 😉 One of the problems I faced was that I needed to test the new infrastructure, but doing so on a physical chip would be cumbersome. So that problem was solved by adding a dummy chip to use with flashrom’s dummy programmer. (At that time the code was the dummy chip was messy and something I would be ashamed to put up publicly, but now I have improved upon it! :P)

Currently I am working on finalising the OTP/security register(s) patches – more specifically, adding support to existing chips, code cleanup and documentation. I will be able to send them to the mailing list in a few days. In my research on Eon, GigaDevice and Winbond chips, 2 distinct models for OTP were observed – the GigaDevice and Winbond model with security register(s), and the Eon model with a security sector.

The Security Register(s) model has 3 separate opcodes for read, program and erase – 0x48, 0x42 and 0x44 respectively. A chips can have multiple security registers (most commonly 3, but as high as 4) with each register being anywhere between 128 bytes to 1024 bytes in size (most commonly 512 bytes and then 256 bytes). Usually chips have a lock bit (LB1, LB2, …) in the status register that correspond to respective security registers. These one-time programmable bits are changed using the standard WRSR instruction. Some chips have a single lock bit that controls OTP status for all security registers.

The Security Sector model has a separate sector which can be operated in the OTP mode. OTP mode is entered with opcode 0x3A and exited by sending WRDI (0x04) instruction. While in the OTP mode, the sector behaves just like any other sector – normal read, program and erase instructions apply. The SRP/SRWD bit is served as OTP bit while in OTP mode. Issuing the WRSR command (irrespective of the data sent along with it) will cause the one-time programmable OTP bit to be set.

One of the recurrent issues (for the lack of a better word, I don’t think of it to be an issue really ;)) is that many chips I have based my research on, are not originally supported by flashrom (perhaps unfortunate siblings of the same family that didn’t find support in flashrom earlier xD). I don’t call it an issue per se because after I have submitted my patches flashrom will end up supporting even more chips, but since I have to write more code it might take slightly longer to submit the patches.

There is a third model which is dominantly followed by Spansion chips and a couple of AMIC chips (some AMIC chips follow one of the earlier models – it’s like AMIC couldn’t decide which one to stick to or they probably had different teams working on it! :P). Similar to the security sector design, these chips also have a separate OTP sector but instead of storing configuration in the register, a byte within the sector is allocated for storing the configuration data. I have planned to support this model in the next revision of patches, after the upcoming ones get reviewed and merged.

Thanks for your time, it was nice to get back in touch with you! 🙂
(Phew, that was long! :P)

[GSoC] Better RISC-V support, week #6/7/8/9

Since I haven’t posted an update of my coreboot-on-RISC-V work in a while, this will be a slightly longer post.

Week 6

In week 6, I started documenting how to build and boot coreboot on RISC-V, in the coreboot wiki.
It is now a bit outdated, because we’re moving away from using bbl to boot Linux.

Week 7

I wrote some patches: I removed code that used the old Host-Target Interface (HTIF), because it’s deprecated. I submitted an improved version of my workaround for the bug that causes Spike to only execute 5000 instructions in some cases. I informed the coreboot resource management subsystem about the position of the RAM in physical address space, so that the program loader wouldn’t refuse to load segments into RAM. I submitted two patches to fix compiler errors with the new toolchain.

Meanwhile, there were some good news in the RISC-V world:

Week 8

I submitted a few more patches and started to explore the Nexys4 board. The precompiled bitstream and kernel from the lowRISC version 0.3 tutorial worked without any problems, and after a few days and some help from the lowRISC mailing list, I was able to recompile the lowRISC bitstream.

This week

I discussed the choice of boot medium with the lowRISC developers, and they agreed that a memory-mapped flash would be useful. Once it is implemented, I
can start porting coreboot to lowRISC on the Nexys 4 DDR board. Luckily the Nexys4 already has large enough flash to use for this purpose.

My mentors and I agreed that the switch from machine mode to supervisor mode should be left completely to the payload.

What’s next?

I will continue to work on running coreboot on the Spike emulator. Currently I’m facing the following problems and tasks:

  • Linux, when compiled to an ELF file (vmlinux) specifies that it wants to be loaded at the physical address 0x0 and at the virtual address 0xffffffff80000000. Since coreboot’s ELF loading code only looks at the physical address, it refuses to load Linux, since RAM starts at 0x80000000 on RISC-V.
  • Low level platform information (most importantly the memory layout) is passed to the firmware (coreboot in this case) as a configuration string, which is dynamically generated by the emulator, in the case of Spike. I still need to implemented a parser for this format, so coreboot can know how much memory is available.
  • The RISC-V Privileged Architecture Specification 1.9 specifies that there shall be a page at the top of the virtual address space where the operating system can call a few functions exposed by the firmware (this is the Supervisor Binary Interface).

[GSoC] Better RISC-V support, week #4/5

Week 4

In week 4, I tracked down why coreboot halted after about one line of output. It turned out to be a spike bug, that I wrote up in this bug report, and affect any program that doesn’t have a tohost symbol. As a workaround, I extended my script that turns coreboot.rom into a ELF to also include this symbol.

After some more patches I could run coreboot in spike and get the familiar “Payload not loaded” line.

Week 5

I was now clearly moving towards being able to run linux on spike/coreboot. But there was a problem: The RISC-V linux port requires a working implementation of the Supervisor Binary Interface (SBI), which is a collection of functions that the supervisor (i.e. the linux kernel) can call in the system firmware.

Coreboot has an implementation of the SBI, but it’s probably outdated by now. To get an up-to-date SBI implementation, I decided to use bbl as a payload. When I built bbl with coreboot’s RISC-V toolchain, I noticed that it depends on a libc being installed in two ways:

  • The autoconf-generated configure script checks that the C compiler can compile and link a program, which only succeeds if it finds a linker script (riscv.ld) and a crt0.o in the right place.
  • bbl relies on the libc headers to declare some common functions and types (it doesn’t use any of the implementations in the libc, though).

The coreboot toolchain script doesn’t, however, install a libc, because coreboot doesn’t need one.

I tweaked the bbl source code until it didn’t need the libc headers, changed the implementation of mcall_console_putchar to use my 8250 UART, got the payload section of bbl (where linux is stored before it’s loaded) out of the way of the CBFS by moving it to 0x81000000 (bbl/bbl.lds is the relevant file for this change), and could finally observe Linux booting in spike, on top of coreboot and bbl. It stops with a kernel panic, though, because it doesn’t have a root filesystem.

Plans for this week

This week I will document my work on the Spike wiki page in the coreboot wiki, so others can run coreboot on spike, too.

[GSoC] Better RISC-V support, week #3

Last week, after updating GCC (by applying Iru Cai’s patch) and commenting out uses of outdated instructions and CSRs (most notably eret and the HTIF CSRs), I noticed that coreboot crashed when it tried to access any global variables. This was because the coreboot build system thought coreboot would live near the start of the address space.

I found spike-riscv/memlayout.ld, and adjusted the starting offset. But then I got a linker error:

build/bootblock/arch/riscv/rom_media.o: In function `boot_device_ro': [...]/src/arch/riscv/rom_media.c:26:(.text.boot_device_ro+0x0): relocation truncated to fit: _RISCV_HI20 against `.LANCHOR0'

I played around with the start address and noticed that addresses below 0x78000000 worked, but if I chose an address that was too close to 0x80000000, it broke. This is, in fact, because pointers to global variables were determined with an instruction sequence like lui a0, 0xNNNNN; addi a0, a0, 0xNNN. On 32-bit RISC-V, the LUI instruction loads its argument into the upper 20 bits of a register, and ADDI adds a 12-bit number. On a 64-bit RISC-V system, lui a0, 0x80000 loads 0xffffffff80000000 into a0, because the number is sign extended.

After disassembling some .o files of coreboot and the RISC-V proxy kernel, I finally noticed that I had to use the -mcmodel=medany compiler option, which makes data accesses pc-relative.

Now that coreboot finally ran and could access its data section, I finished debugging the UART block that I promised last week. Coreboot can now print stuff, but it stops running pretty soon.

Plans for this week

This week I will debug why coreboot hangs, and will hopefully get it to boot until the “Payload not found” line again, which worked with an older version of Spike.

Also, Ron Minnich will be giving a talk about coreboot on RISC-V at the coreboot convention in San Francisco, in a few hours.

[GSoC] Multiple status registers, block protection and OTP support, week #1 and #2

Hi, I am Hatim Kanchwala (hatim on IRC) from India. I am the GSoC student working with flashrom this year. Stefan Tauner (stefanct) and David Hendricks (dhendrix) will be mentoring me (thanks a lot for the opportunity). The pre-midterm phase of my project comprises three sub-projects – multiple status registers, block protection and OTP support. Each of these projects deals with SPI flashchips.

As of writing this post, flashrom supports over 300 SPI flashchips. Around 10% have multiple status registers (most have two but there is one with three). Almost all have some sort of block protection in place. Around 40% have some variation of OTP or security registers. A combination of BP (Block Protect, first status register) and SRP bits (usually first, but sometimes second status register as well) in the status register determine the range and type of protection in effect. A few have a TB bit (Top/Bottom) in addition to BP bits. Some also have a CMP bit (Complement Protect, second or third status register) to add more flexibility to range available. Few chips have a WPS bit (Write Protect Scheme, second or third status register) that define which scheme of access protection is in use. Chips with security registers have corresponding LB bits (Lock Bits, second status register) which are one-time programmable and, when set, render the corresponding security register read-only. Chips with a separate OTP sector(s) have opcodes to enter/exit OTP mode and, within OTP mode usual read, page program and sector erase opcodes can be used.

Previously, flashrom could only read/write the first status register. For writes, all block protect bits were unset (this configuration corresponds to block protection), if the type of protection allowed it. Once unset, flashrom couldn’t revert the BP bit configuration. The ChromiumOS fork of flashrom has some support for locking/unlocking block access protection in place. A lot of the work is done around specific families of chips, but they are moving towards generalising it. For chips with OTP support, flashrom simply printed a warning.

In these two weeks I sifted through around 5-6 dozen datasheets and developed models for multiple status registers, block protection and OTP/security registers. I discussed with mentors and the community over mailing list (link to thread) the infrastructural changes and use cases corresponding to the models. To substantiate these ideas, I wrote separate prototype code. In the process, Stefan introduced me to a powerful tool, Coccinelle. This tool will make applying changes to the large struct flashchips easier while being safe. As a byproduct of studying existing flashrom infrastructure, I had the opportunity to explore the history of flashrom through git log – evolution of flashrom from its humble beginnings in coreboot/util to flash_and_burn to flash_rom to finally flashrom today!

My broad targets for the following few weeks will be to finish up with the pending dozen or two datasheets, polish the models and start transforming the prototype code into merge-worthy code. Following the infrastructure changes, I will update existing chips to make use of the new infrastructure, add support for a bunch of new chips and finally test on actual hardware.

Thanks. See you later!

[GSoC] Better RISC-V support, week #2

Last week, I updated my copy of spike (to commit 2fe8a17a), and familiarized myself with the differences between the old and the new version:

  • The Host-Target Interface (HTIF) isn’t accessed through the mtohost and mfromhost CSRs anymore. Instead, you have to define two ELF symbols (tohost and fromhost). Usually this is done by declaring two global variables with these names, but since the coreboot build system doesn’t natively produce an ELF file, it would get a little tricky.
  • Spike doesn’t implement a classic UART.
  • The memory layout is different. The default entry point is now at 0x1000, where spike puts a small ROM, which jumps to the start of the emulated RAM, at 0x80000000. One way to run coreboot is to load it at 0x80000000, but then it can’t catch exceptions: The exception vector is at 0x1010.
  • Within spike’s boot ROM, there’s also a text-based “platform tree”, which describes the installed peripherals.

“Why does coreboot need a serial console?”, you may ask. Coreboot uses it to log everything it does (at a configurable level of detail), and that’s quite useful for debugging and development.

Instead of working around the problems with HTIF, I decided to implement a minimal, 8250-compatible UART. I’m not done yet, but the goal is to use coreboot’s existing 8250 driver.

Plans for this week

This week, I will rewrite the bootblock and CBFS code to work with RISC-V’s new memory layout, and make sure that the spike UART works with coreboot’s 8250 UART driver. Booting Linux probably still takes some time.

[GSoC] Better RISC-V support, week #1

Hi, I’m Jonathan Neuschäfer (jn__ on IRC) and my GSoC project for this year is to improve coreboot’s support for RISC-V platforms. RISC-V is a new instruction set architecture (ISA) that can be implemented without paying license fees and is relatively simple.

Coreboot has already been ported to RISC-V in 2014, and has since received a bunch of patches, but since the RISC-V Privileged ISA Specification (which defines things like interrupt handling and virtual memory) is still in flux, it has become unbootable again.

My first first goal last week was to run coreboot in SPIKE, the official RISC-V emulator, and get some console output. I checked out commit 419f1b5f3 (current master) of the riscv-tools repository and built SPIKE from there.

After I patched a few outdated instructions and worked around the fact that the RISC-V binutils port currently included in coreboot targets a newer version of the RISC-V Privileged Spec by hardcoding some Control and Status Register numbers, I finally got coreboot booting until the point where it would jump into a payload, had I specified one.

All patches can be found under the riscv topic on gerrit.

Plans for this week

This week I will update my SPIKE to a version that supports the upcoming Privileged Spec 1.9, which will be released in the next couple weeks. This has the advantage that I don’t need to patch instructions because GCC encodes them differently than SPIKE decodes them. Additionally, I’ll try to get Linux to boot in SPIKE, under coreboot.