xref: /linux/drivers/gpu/nova-core/regs/macros.rs (revision 036c5fa25020d8b1619a96dabbcf9b156f4329bb)
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     (
91         $name:ident @ $offset:literal $(, $comment:literal)? {
92             $($fields:tt)*
93         }
94     ) => {
95         register!(@common $name $(, $comment)?);
96         register!(@field_accessors $name { $($fields)* });
97         register!(@io $name @ $offset);
98     };
99 
100     // Creates a alias register of fixed offset register `alias` with its own fields.
101     (
102         $name:ident => $alias:ident $(, $comment:literal)? {
103             $($fields:tt)*
104         }
105     ) => {
106         register!(@common $name $(, $comment)?);
107         register!(@field_accessors $name { $($fields)* });
108         register!(@io $name @ $alias::OFFSET);
109     };
110 
111     // Creates a register at a relative offset from a base address.
112     (
113         $name:ident @ + $offset:literal $(, $comment:literal)? {
114             $($fields:tt)*
115         }
116     ) => {
117         register!(@common $name $(, $comment)?);
118         register!(@field_accessors $name { $($fields)* });
119         register!(@io $name @ + $offset);
120     };
121 
122     // Creates a alias register of relative offset register `alias` with its own fields.
123     (
124         $name:ident => + $alias:ident $(, $comment:literal)? {
125             $($fields:tt)*
126         }
127     ) => {
128         register!(@common $name $(, $comment)?);
129         register!(@field_accessors $name { $($fields)* });
130         register!(@io $name @ + $alias::OFFSET);
131     };
132 
133     // All rules below are helpers.
134 
135     // Defines the wrapper `$name` type, as well as its relevant implementations (`Debug`, `BitOr`,
136     // and conversion to regular `u32`).
137     (@common $name:ident $(, $comment:literal)?) => {
138         $(
139         #[doc=$comment]
140         )?
141         #[repr(transparent)]
142         #[derive(Clone, Copy, Default)]
143         pub(crate) struct $name(u32);
144 
145         // TODO[REGA]: display the raw hex value, then the value of all the fields. This requires
146         // matching the fields, which will complexify the syntax considerably...
147         impl ::core::fmt::Debug for $name {
148             fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
149                 f.debug_tuple(stringify!($name))
150                     .field(&format_args!("0x{0:x}", &self.0))
151                     .finish()
152             }
153         }
154 
155         impl ::core::ops::BitOr for $name {
156             type Output = Self;
157 
158             fn bitor(self, rhs: Self) -> Self::Output {
159                 Self(self.0 | rhs.0)
160             }
161         }
162 
163         impl ::core::convert::From<$name> for u32 {
164             fn from(reg: $name) -> u32 {
165                 reg.0
166             }
167         }
168     };
169 
170     // Defines all the field getter/methods methods for `$name`.
171     (
172         @field_accessors $name:ident {
173         $($hi:tt:$lo:tt $field:ident as $type:tt
174             $(?=> $try_into_type:ty)?
175             $(=> $into_type:ty)?
176             $(, $comment:literal)?
177         ;
178         )*
179         }
180     ) => {
181         $(
182             register!(@check_field_bounds $hi:$lo $field as $type);
183         )*
184 
185         #[allow(dead_code)]
186         impl $name {
187             $(
188             register!(@field_accessor $name $hi:$lo $field as $type
189                 $(?=> $try_into_type)?
190                 $(=> $into_type)?
191                 $(, $comment)?
192                 ;
193             );
194             )*
195         }
196     };
197 
198     // Boolean fields must have `$hi == $lo`.
199     (@check_field_bounds $hi:tt:$lo:tt $field:ident as bool) => {
200         #[allow(clippy::eq_op)]
201         const _: () = {
202             ::kernel::build_assert!(
203                 $hi == $lo,
204                 concat!("boolean field `", stringify!($field), "` covers more than one bit")
205             );
206         };
207     };
208 
209     // Non-boolean fields must have `$hi >= $lo`.
210     (@check_field_bounds $hi:tt:$lo:tt $field:ident as $type:tt) => {
211         #[allow(clippy::eq_op)]
212         const _: () = {
213             ::kernel::build_assert!(
214                 $hi >= $lo,
215                 concat!("field `", stringify!($field), "`'s MSB is smaller than its LSB")
216             );
217         };
218     };
219 
220     // Catches fields defined as `bool` and convert them into a boolean value.
221     (
222         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool => $into_type:ty
223             $(, $comment:literal)?;
224     ) => {
225         register!(
226             @leaf_accessor $name $hi:$lo $field
227             { |f| <$into_type>::from(if f != 0 { true } else { false }) }
228             $into_type => $into_type $(, $comment)?;
229         );
230     };
231 
232     // Shortcut for fields defined as `bool` without the `=>` syntax.
233     (
234         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as bool $(, $comment:literal)?;
235     ) => {
236         register!(@field_accessor $name $hi:$lo $field as bool => bool $(, $comment)?;);
237     };
238 
239     // Catches the `?=>` syntax for non-boolean fields.
240     (
241         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt ?=> $try_into_type:ty
242             $(, $comment:literal)?;
243     ) => {
244         register!(@leaf_accessor $name $hi:$lo $field
245             { |f| <$try_into_type>::try_from(f as $type) } $try_into_type =>
246             ::core::result::Result<
247                 $try_into_type,
248                 <$try_into_type as ::core::convert::TryFrom<$type>>::Error
249             >
250             $(, $comment)?;);
251     };
252 
253     // Catches the `=>` syntax for non-boolean fields.
254     (
255         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt => $into_type:ty
256             $(, $comment:literal)?;
257     ) => {
258         register!(@leaf_accessor $name $hi:$lo $field
259             { |f| <$into_type>::from(f as $type) } $into_type => $into_type $(, $comment)?;);
260     };
261 
262     // Shortcut for fields defined as non-`bool` without the `=>` or `?=>` syntax.
263     (
264         @field_accessor $name:ident $hi:tt:$lo:tt $field:ident as $type:tt
265             $(, $comment:literal)?;
266     ) => {
267         register!(@field_accessor $name $hi:$lo $field as $type => $type $(, $comment)?;);
268     };
269 
270     // Generates the accessor methods for a single field.
271     (
272         @leaf_accessor $name:ident $hi:tt:$lo:tt $field:ident
273             { $process:expr } $to_type:ty => $res_type:ty $(, $comment:literal)?;
274     ) => {
275         ::kernel::macros::paste!(
276         const [<$field:upper _RANGE>]: ::core::ops::RangeInclusive<u8> = $lo..=$hi;
277         const [<$field:upper _MASK>]: u32 = ((((1 << $hi) - 1) << 1) + 1) - ((1 << $lo) - 1);
278         const [<$field:upper _SHIFT>]: u32 = Self::[<$field:upper _MASK>].trailing_zeros();
279         );
280 
281         $(
282         #[doc="Returns the value of this field:"]
283         #[doc=$comment]
284         )?
285         #[inline]
286         pub(crate) fn $field(self) -> $res_type {
287             ::kernel::macros::paste!(
288             const MASK: u32 = $name::[<$field:upper _MASK>];
289             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
290             );
291             let field = ((self.0 & MASK) >> SHIFT);
292 
293             $process(field)
294         }
295 
296         ::kernel::macros::paste!(
297         $(
298         #[doc="Sets the value of this field:"]
299         #[doc=$comment]
300         )?
301         #[inline]
302         pub(crate) fn [<set_ $field>](mut self, value: $to_type) -> Self {
303             const MASK: u32 = $name::[<$field:upper _MASK>];
304             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
305             let value = (u32::from(value) << SHIFT) & MASK;
306             self.0 = (self.0 & !MASK) | value;
307 
308             self
309         }
310         );
311     };
312 
313     // Creates the IO accessors for a fixed offset register.
314     (@io $name:ident @ $offset:expr) => {
315         #[allow(dead_code)]
316         impl $name {
317             pub(crate) const OFFSET: usize = $offset;
318 
319             #[inline]
320             pub(crate) fn read<const SIZE: usize, T>(io: &T) -> Self where
321                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
322             {
323                 Self(io.read32($offset))
324             }
325 
326             #[inline]
327             pub(crate) fn write<const SIZE: usize, T>(self, io: &T) where
328                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
329             {
330                 io.write32(self.0, $offset)
331             }
332 
333             #[inline]
334             pub(crate) fn alter<const SIZE: usize, T, F>(
335                 io: &T,
336                 f: F,
337             ) where
338                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
339                 F: ::core::ops::FnOnce(Self) -> Self,
340             {
341                 let reg = f(Self::read(io));
342                 reg.write(io);
343             }
344         }
345     };
346 
347     // Create the IO accessors for a relative offset register.
348     (@io $name:ident @ + $offset:literal) => {
349         #[allow(dead_code)]
350         impl $name {
351             pub(crate) const OFFSET: usize = $offset;
352 
353             #[inline]
354             pub(crate) fn read<const SIZE: usize, T>(
355                 io: &T,
356                 base: usize,
357             ) -> Self where
358                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
359             {
360                 Self(io.read32(base + $offset))
361             }
362 
363             #[inline]
364             pub(crate) fn write<const SIZE: usize, T>(
365                 self,
366                 io: &T,
367                 base: usize,
368             ) where
369                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
370             {
371                 io.write32(self.0, base + $offset)
372             }
373 
374             #[inline]
375             pub(crate) fn alter<const SIZE: usize, T, F>(
376                 io: &T,
377                 base: usize,
378                 f: F,
379             ) where
380                 T: ::core::ops::Deref<Target = ::kernel::io::Io<SIZE>>,
381                 F: ::core::ops::FnOnce(Self) -> Self,
382             {
383                 let reg = f(Self::read(io, base));
384                 reg.write(io, base);
385             }
386         }
387     };
388 }
389