xref: /linux/drivers/gpu/nova-core/regs/macros.rs (revision 7a9cb3dfb07d3e29c0eeebb26b11a34a19a889a4)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! `register!` macro to define register layout and accessors.
4 //!
5 //! A single register typically includes several fields, which are accessed through a combination
6 //! of bit-shift and mask operations that introduce a class of potential mistakes, notably because
7 //! not all possible field values are necessarily valid.
8 //!
9 //! The `register!` macro in this module provides an intuitive and readable syntax for defining a
10 //! dedicated type for each register. Each such type comes with its own field accessors that can
11 //! return an error if a field's value is invalid.
12 
13 /// Defines a dedicated type for a register with an absolute offset, including getter and setter
14 /// methods for its fields and methods to read and write it from an `Io` region.
15 ///
16 /// Example:
17 ///
18 /// ```no_run
19 /// register!(BOOT_0 @ 0x00000100, "Basic revision information about the GPU" {
20 ///    3:0     minor_revision as u8, "Minor revision of the chip";
21 ///    7:4     major_revision as u8, "Major revision of the chip";
22 ///    28:20   chipset as u32 ?=> Chipset, "Chipset model";
23 /// });
24 /// ```
25 ///
26 /// This defines a `BOOT_0` type which can be read or written from offset `0x100` of an `Io`
27 /// region. It is composed of 3 fields, for instance `minor_revision` is made of the 4 least
28 /// significant bits of the register. Each field can be accessed and modified using accessor
29 /// methods:
30 ///
31 /// ```no_run
32 /// // Read from the register's defined offset (0x100).
33 /// let boot0 = BOOT_0::read(&bar);
34 /// pr_info!("chip revision: {}.{}", boot0.major_revision(), boot0.minor_revision());
35 ///
36 /// // `Chipset::try_from` is called with the value of the `chipset` field and returns an
37 /// // error if it is invalid.
38 /// let chipset = boot0.chipset()?;
39 ///
40 /// // Update some fields and write the value back.
41 /// boot0.set_major_revision(3).set_minor_revision(10).write(&bar);
42 ///
43 /// // Or, just read and update the register in a single step:
44 /// BOOT_0::alter(&bar, |r| r.set_major_revision(3).set_minor_revision(10));
45 /// ```
46 ///
47 /// Fields are defined as follows:
48 ///
49 /// - `as <type>` simply returns the field value casted to <type>, typically `u32`, `u16`, `u8` or
50 ///   `bool`. Note that `bool` fields must have a range of 1 bit.
51 /// - `as <type> => <into_type>` calls `<into_type>`'s `From::<<type>>` implementation and returns
52 ///   the result.
53 /// - `as <type> ?=> <try_into_type>` calls `<try_into_type>`'s `TryFrom::<<type>>` implementation
54 ///   and returns the result. This is useful with fields for which not all values are valid.
55 ///
56 /// The documentation strings are optional. If present, they will be added to the type's
57 /// definition, or the field getter and setter methods they are attached to.
58 ///
59 /// Putting a `+` before the address of the register makes it relative to a base: the `read` and
60 /// `write` methods take a `base` argument that is added to the specified address before access:
61 ///
62 /// ```no_run
63 /// register!(CPU_CTL @ +0x0000010, "CPU core control" {
64 ///    0:0     start as bool, "Start the CPU core";
65 /// });
66 ///
67 /// // Flip the `start` switch for the CPU core which base address is at `CPU_BASE`.
68 /// let cpuctl = CPU_CTL::read(&bar, CPU_BASE);
69 /// pr_info!("CPU CTL: {:#x}", cpuctl);
70 /// cpuctl.set_start(true).write(&bar, CPU_BASE);
71 /// ```
72 ///
73 /// It is also possible to create a alias register by using the `=> ALIAS` syntax. This is useful
74 /// for cases where a register's interpretation depends on the context:
75 ///
76 /// ```no_run
77 /// register!(SCRATCH @ 0x00000200, "Scratch register" {
78 ///    31:0     value as u32, "Raw value";
79 /// });
80 ///
81 /// register!(SCRATCH_BOOT_STATUS => SCRATCH, "Boot status of the firmware" {
82 ///     0:0     completed as bool, "Whether the firmware has completed booting";
83 /// });
84 /// ```
85 ///
86 /// In this example, `SCRATCH_0_BOOT_STATUS` uses the same I/O address as `SCRATCH`, while also
87 /// providing its own `completed` field.
88 macro_rules! register {
89     // Creates a register at a fixed offset of the MMIO space.
90     ($name:ident @ $offset:literal $(, $comment:literal)? { $($fields:tt)* } ) => {
91         register!(@core $name $(, $comment)? { $($fields)* } );
92         register!(@io $name @ $offset);
93     };
94 
95     // Creates an alias register of fixed offset register `alias` with its own fields.
96     ($name:ident => $alias:ident $(, $comment:literal)? { $($fields:tt)* } ) => {
97         register!(@core $name $(, $comment)? { $($fields)* } );
98         register!(@io $name @ $alias::OFFSET);
99     };
100 
101     // Creates a register at a relative offset from a base address.
102     ($name:ident @ + $offset:literal $(, $comment:literal)? { $($fields:tt)* } ) => {
103         register!(@core $name $(, $comment)? { $($fields)* } );
104         register!(@io $name @ + $offset);
105     };
106 
107     // Creates an alias register of relative offset register `alias` with its own fields.
108     ($name:ident => + $alias:ident $(, $comment:literal)? { $($fields:tt)* } ) => {
109         register!(@core $name $(, $comment)? { $($fields)* } );
110         register!(@io $name @ + $alias::OFFSET);
111     };
112 
113     // All rules below are helpers.
114 
115     // Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`, `BitOr`,
116     // and conversion to the value type) and field accessor methods.
117     (@core $name:ident $(, $comment:literal)? { $($fields:tt)* }) => {
118         $(
119         #[doc=$comment]
120         )?
121         #[repr(transparent)]
122         #[derive(Clone, Copy, Default)]
123         pub(crate) struct $name(u32);
124 
125         // TODO[REGA]: display the raw hex value, then the value of all the fields. This requires
126         // matching the fields, which will complexify the syntax considerably...
127         impl ::core::fmt::Debug for $name {
128             fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
129                 f.debug_tuple(stringify!($name))
130                     .field(&format_args!("0x{0:x}", &self.0))
131                     .finish()
132             }
133         }
134 
135         impl ::core::ops::BitOr for $name {
136             type Output = Self;
137 
138             fn bitor(self, rhs: Self) -> Self::Output {
139                 Self(self.0 | rhs.0)
140             }
141         }
142 
143         impl ::core::convert::From<$name> for u32 {
144             fn from(reg: $name) -> u32 {
145                 reg.0
146             }
147         }
148 
149         register!(@fields_dispatcher $name { $($fields)* });
150     };
151 
152     // Captures the fields and passes them to all the implementers that require field information.
153     //
154     // Used to simplify the matching rules for implementers, so they don't need to match the entire
155     // complex fields rule even though they only make use of part of it.
156     (@fields_dispatcher $name:ident {
157         $($hi:tt:$lo:tt $field:ident as $type:tt
158             $(?=> $try_into_type:ty)?
159             $(=> $into_type:ty)?
160             $(, $comment:literal)?
161         ;
162         )*
163     }
164     ) => {
165         register!(@field_accessors $name {
166             $(
167                 $hi:$lo $field as $type
168                 $(?=> $try_into_type)?
169                 $(=> $into_type)?
170                 $(, $comment)?
171             ;
172             )*
173         });
174     };
175 
176     // Defines all the field getter/methods methods for `$name`.
177     (
178         @field_accessors $name:ident {
179         $($hi:tt:$lo:tt $field:ident as $type:tt
180             $(?=> $try_into_type:ty)?
181             $(=> $into_type:ty)?
182             $(, $comment:literal)?
183         ;
184         )*
185         }
186     ) => {
187         $(
188             register!(@check_field_bounds $hi:$lo $field as $type);
189         )*
190 
191         #[allow(dead_code)]
192         impl $name {
193             $(
194             register!(@field_accessor $name $hi:$lo $field as $type
195                 $(?=> $try_into_type)?
196                 $(=> $into_type)?
197                 $(, $comment)?
198                 ;
199             );
200             )*
201         }
202     };
203 
204     // Boolean fields must have `$hi == $lo`.
205     (@check_field_bounds $hi:tt:$lo:tt $field:ident as bool) => {
206         #[allow(clippy::eq_op)]
207         const _: () = {
208             ::kernel::build_assert!(
209                 $hi == $lo,
210                 concat!("boolean field `", stringify!($field), "` covers more than one bit")
211             );
212         };
213     };
214 
215     // Non-boolean fields must have `$hi >= $lo`.
216     (@check_field_bounds $hi:tt:$lo:tt $field:ident as $type:tt) => {
217         #[allow(clippy::eq_op)]
218         const _: () = {
219             ::kernel::build_assert!(
220                 $hi >= $lo,
221                 concat!("field `", stringify!($field), "`'s MSB is smaller than its LSB")
222             );
223         };
224     };
225 
226     // Catches fields defined as `bool` and convert them into a boolean value.
227     (
228         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
229             $(, $comment:literal)?;
230     ) => {
231         register!(
232             @leaf_accessor $name $hi:$lo $field
233             { |f| <$into_type>::from(if f != 0 { true } else { false }) }
234             $into_type => $into_type $(, $comment)?;
235         );
236     };
237 
238     // Shortcut for fields defined as `bool` without the `=>` syntax.
239     (
240         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
241     ) => {
242         register!(@field_accessor $name $hi:$lo $field as bool => bool $(, $comment)?;);
243     };
244 
245     // Catches the `?=>` syntax for non-boolean fields.
246     (
247         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
248             $(, $comment:literal)?;
249     ) => {
250         register!(@leaf_accessor $name $hi:$lo $field
251             { |f| <$try_into_type>::try_from(f as $type) } $try_into_type =>
252             ::core::result::Result<
253                 $try_into_type,
254                 <$try_into_type as ::core::convert::TryFrom<$type>>::Error
255             >
256             $(, $comment)?;);
257     };
258 
259     // Catches the `=>` syntax for non-boolean fields.
260     (
261         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
262             $(, $comment:literal)?;
263     ) => {
264         register!(@leaf_accessor $name $hi:$lo $field
265             { |f| <$into_type>::from(f as $type) } $into_type => $into_type $(, $comment)?;);
266     };
267 
268     // Shortcut for non-boolean fields defined without the `=>` or `?=>` syntax.
269     (
270         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt
271             $(, $comment:literal)?;
272     ) => {
273         register!(@field_accessor $name $hi:$lo $field as $type => $type $(, $comment)?;);
274     };
275 
276     // Generates the accessor methods for a single field.
277     (
278         @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident
279             { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?;
280     ) => {
281         ::kernel::macros::paste!(
282         const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi;
283         const [<$field:upper _MASK>]: u32 = ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1);
284         const [<$field:upper _SHIFT>]: u32 = Self::[<$field:upper _MASK>].trailing_zeros();
285         );
286 
287         $(
288         #[doc="Returns the value of this field:"]
289         #[doc=$comment]
290         )?
291         #[inline]
292         pub(crate) fn $field(self) -> $res_type {
293             ::kernel::macros::paste!(
294             const MASK: u32 = $name::[<$field:upper _MASK>];
295             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
296             );
297             let field = ((self.0 & MASK) >> SHIFT);
298 
299             $process(field)
300         }
301 
302         ::kernel::macros::paste!(
303         $(
304         #[doc="Sets the value of this field:"]
305         #[doc=$comment]
306         )?
307         #[inline]
308         pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self {
309             const MASK: u32 = $name::[<$field:upper _MASK>];
310             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
311             let value = (u32::from(value) << SHIFT) & MASK;
312             self.0 = (self.0 & !MASK) | value;
313 
314             self
315         }
316         );
317     };
318 
319     // Generates the IO accessors for a fixed offset register.
320     (@io $name:ident @ $offset:expr) => {
321         #[allow(dead_code)]
322         impl $name {
323             pub(crate) const OFFSET: usize = $offset;
324 
325             /// Read the register from its address in `io`.
326             #[inline]
327             pub(crate) fn read<const SIZE: usize, T>(io: &T) -> Self where
328                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
329             {
330                 Self(io.read32($offset))
331             }
332 
333             /// Write the value contained in `self` to the register address in `io`.
334             #[inline]
335             pub(crate) fn write<const SIZE: usize, T>(self, io: &T) where
336                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
337             {
338                 io.write32(self.0, $offset)
339             }
340 
341             /// Read the register from its address in `io` and run `f` on its value to obtain a new
342             /// value to write back.
343             #[inline]
344             pub(crate) fn alter<const SIZE: usize, T, F>(
345                 io: &T,
346                 f: F,
347             ) where
348                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
349                 F: ::core::ops::FnOnce(Self) -> Self,
350             {
351                 let reg = f(Self::read(io));
352                 reg.write(io);
353             }
354         }
355     };
356 
357     // Generates the IO accessors for a relative offset register.
358     (@io $name:ident @ + $offset:literal) => {
359         #[allow(dead_code)]
360         impl $name {
361             pub(crate) const OFFSET: usize = $offset;
362 
363             #[inline]
364             pub(crate) fn read<const SIZE: usize, T>(
365                 io: &T,
366                 base: usize,
367             ) -> Self where
368                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
369             {
370                 Self(io.read32(base + $offset))
371             }
372 
373             #[inline]
374             pub(crate) fn write<const SIZE: usize, T>(
375                 self,
376                 io: &T,
377                 base: usize,
378             ) where
379                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
380             {
381                 io.write32(self.0, base + $offset)
382             }
383 
384             #[inline]
385             pub(crate) fn alter<const SIZE: usize, T, F>(
386                 io: &T,
387                 base: usize,
388                 f: F,
389             ) where
390                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
391                 F: ::core::ops::FnOnce(Self) -> Self,
392             {
393                 let reg = f(Self::read(io, base));
394                 reg.write(io, base);
395             }
396         }
397     };
398 }
399