Skip to contentSkip to conversation

A glimpse at PL011 emulation in safe Rust

DISCUSSION Paolo Bonzini 1 participant 1 message Dec 4, 2024

lore
Share & tools
lore
#0 lore raw

Hi all,

this is finally a look at what the PL011 device model would look like in Rust, without having to write unsafe so often. The attached file is a synopsis of the C code, the Rust code and my commentary (the C code is partly rearranged to match the ordering of the Rust code).

The code compiles on my computer, but it needs some functionality that is still untested or stubbed out. Getting to here will take some time and some reviews. But in the meanwhile, this is already useful to show what having Rust available in QEMU *actually* looks like for people who have to write a device.

While preparing this I noticed some logic changes between the C and Rust version, for which I will send patches in due course. Otherwise, the device logic was changed as little as possible and especially the naming style. So, while the coding style is mostly fixed to what rustfmt produces, some adjustments to the names and how they are referred to can be made (absolutely tell me if you prefer "registers::Data" or "regs::Data" or "DataReg"!).

Please review and be as brutal as needed. :) For your convenience I copied the commentary after my signature, with line numbers; quoting it is probably the easiest way to reply, though of course in some cases you might prefer to quote code instead.

If we want to continue, please remember that people will need to step in sooner rather than later (e.g. adding bindings to QAPI and DMA; but also doing reviews to ensure that the code is not impenetrable to anyone but me). Or if we want to abort because there is not enough benefit, this is also the time to decide it.

Paolo

10 These are the APIs that PL011 needs. Note that "bindings" is not 11 imported, all that is necessary from C code has been wrapped.

14 "prelude" provides commonly used structs and traits from all over the place.

18 "qom_isa" is a macro that helps with defining QOM superclasses.

44 Rust only allows indexing arrays with usize indices. Adding 45 the Index implementation here removes some casts elsewhere.

52 Equivalent code is generated automatically by the Rust compiler 53 (with "#[derive(Display)]" on the RegisterOffsets enum).

70 I am not very happy with the handling of bitmasks. It is certainly 71 possible to do better. The ".0" is because the code tries to use a 72 type wrapping the bitfields, but not hard enough (irq_level, irq_enable, 73 IRQMASK are all u32).

75 Rust supports operator overloading, but not yet in "const" context (which 76 includes "const" declarations of course, but also "static" declarations). 77 This is the main missing bit that I would like from the language. 78 Until it's in, we'll probably have to be creative.

85 Needed for migration to look at the struct.

88 These are effectively bitfields, but portable. They are handled by an 89 external crate. The ugly-ish part about it is that it doesn't support 90 const operation very well, so it is hard to define constants for recurring 91 values of the registers (e.g. DR_BE in the C code).

95 read_fifo could be a [registers::Data; PL011_FIFO_DEPTH] too. Not sure 96 how that would work for vmstate, though.

98 Note how the mutable part of the device is in a separate struct. This is 99 because all accesses check that the BQL is taken, and also that it is 100 not dropped in the middle of the access.

116 This [BqlRefCell] is what does the BQL checks.

118 Owned<> means that instance_init will add a reference to the Clock and 119 instance_finalize will drop it.

122 All superclasses have to be listed, at least for now.

124 I took a slightly different approach to the device_id, compared to the 125 C code, mostly to test whether the bindings to QOM could do subclasses 126 of classes that written themselves in Rust.

130 These "unsafe impl" are the only occurrence of unsafe in the whole device. 131 The ObjectType trait is marked unsafe because it tells the QOM C code 132 things about the layout of the PL011State struct that the user is promising. 133 Often, unsafe traits are generated by macros that can promise safety.

138 As will be visible later, implementing class_init for "standard" classes 139 is mostly automatic, but you do have to recurse up the class hierarchy.

142 This trait defines what goes in TypeInfo.

145 So for example this ends up in the TypeInfo's .instance_post_init field.

148 This "Builder" thing is a common idiom in Rust whenever not all fields 149 are always initialized. Note that the MemoryRegionOps callbacks are 150 methods implemented by struct PL011State.

155 Rust code will have a stricter separation between instance_init and 156 instance_post_init. The former only takes care of initializing the struct 157 (the compiler checks that all fields are initialized!), the latter does 158 other initialization such as sysbus_init_irq and sysbus_init_mmio.

172 This trait defines what goes in DeviceClass.

173 This can become a "const" with a newer version of Rust.

177 This one too.

180 Realize and reset cannot be functions in the DeviceImpl trait, because 181 the code also needs to express their *absence* (i.e. using the inherited 182 implementation). It may be possible in the future to use procedural 183 macros to make things look a bit more natural. But this is at the cost 184 of hidden magic, so it is a debatable benefit and for now I am leaving 185 everything visible.

189 Here I am taking a slightly different approach to callbacks; 190 they are all included in a trait instead of being methods 191 implemented by PL011State. The reason for this is only to 192 figure out the advantages and disadvantages; this one seems 193 more "natural" but if one has more than one character device 194 backend things will get more complicated. I am leaning 195 towards using methods for character device ops as well, which 196 is also more similar to the C API. I started with this other 197 idea but only because I hadn't yet figured out methods

202 Due to the separation between registers and the rest, I 203 removed external interrupt update from put_fifo (and made 204 it #[must_use] to not forget).

221 The bulk of read and write is implemented on PL011Registers. read must 222 also return whether to invoke qemu_chr_fe_accept_input() because it can 223 cause reentrancy in PL011Registers (which is an abort!). "ControlFlow" 224 is how the code currently represents it, but it's probably easiest to 225 return a (bool, u32) pair. Patches are welcome.

227 Here are bitfields in action.

240 Another case in which bitmasks need more work.

243 The RSR layout is the same as bits 8-15 of DR. This is visible in 244 the types. Including the "error clear" part in the name is probably 245 wrong because the register is only used for the reads part. It's 246 not a "write 1 clears" registers, for example. This brings another 247 question: what is the best way to note open improvements in the files?

297 Again some differences due to read and write being implemented on a 298 separate struct:
299
300 - read/write gets the register decoded into an enum
301
302 - write send back whether to look for interrupts
303
304 - write also needs to know the character backend. Alternatively 305 PL011Registers could know its outer PL011State, or
306 "char_backend.write_all(&ch);" could be sent down as a 307 closure

381 This #[must_use] asks the caller to check the result (to call 382 update() or to pass it up).

428 The difference between bitfields here and ints below is a bit jarring. 429 I guess if one doesn't like it, they could use u32 like in C for both 430 registers and interrupts; nobody would complain to be honest. Using the 431 language's features makes it clear where they leave something to be 432 desired, at least (and I don't feel like undoing the work that Manos 433 did in converting the registers to bitfields...).

463 This is still the implementation of PL011Registers.

476 And this as well. This is *not* the reset method on DeviceState.

491 This line resets all FIFO flags, both transmit and receive.

523 Another #[must_use] here.

576 This is the callback for self.clock

582 This was the missing part of pl011_init. BTW, vmstate is 583 the main missing part.

590 And here are also the remaining parts of read and write. 591
592 After borrow_mut(), "regs" provides a way to write to self.regs, 593 but only while the local variable regs is live.
594
595 Converting from hwaddr to enum returns Err(offset) if the offset is 596 not part of a known register. This is one case where macros are good 597 at hiding code that "does the obvious thing". Rust macros are more 598 powerful and generally do not have the same issues as C, but they can 599 make the code unreadable if done wrong.

602 Logging and tracing are the main missing pieces.

606 regs is dropped here. Someone else can now write to self.regs. 607
608 Again, don't read too much in Break/Continue. The intention of 609 the ControlFlow enum doesn't really match how QEMU uses it here. 610
611 accept_input is called after coming back; the character device 612 callbacks do their own borrow_mut().

638 PL011State needs a couple more forwarding methods to call into PL011Registers. 639 In fact, *this* is the implementation of the "reset" method in DeviceState.

667 The wrappers for qdev_prop_set_chr and sysbus_connect_irq take an 668 Owned<...> smart pointer. This smart pointer automatically handles 669 object_ref() and object_unref(). The reason why they take Owned<...> and 670 not a normal reference is to signify that the object is heap allocated. 671 Since C gave a raw pointer, create the Owned by hand in unsafe blocks. 672 Also tell Rust not to drop it, i.e. not to call object_unref(). 673
674 ... I lied, the functions take *a reference* to the pointer (that is, an 675 &Owned<...>). This means that they *request* you to own a reference but 676 they don't steal it from you. The functions take care of adding their own 677 reference: qemu_chr_fe_init() does it; or, if I'm not wrong, it should). 678
679 PL011State::new() gave us an Owned<PL011State>, converting it with into_raw 680 gives ownership of the reference to the C caller.

694 instance_init is mandatory in Rust; the case where you have no additional 695 fields to initialize (as is the case here) is rare enough. This is why 696 it is an "fn" and not a "const" like REALIZE and RESET. If needed, it 697 would be possible to write a separate wrapper for "this class only 698 differs from its superclass in its class_init method".

701 Again, the implementation is different so this is a class_init method.

715 The defaults are good. No need to override realize and reset, so the default of 716 None for the REALIZE and RESET constants are ok.

718 type_register_static is handled automagically by #[derive(Object)], 719 as an initial tasting of what macros could do. The main things that 720 we could do with macros is implementing qdev properties in a type-safe 721 manner, and perhaps improve the bitmask situation.