starry-kernel 0.5.13

A Linux-compatible OS kernel built on ArceOS unikernel
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
use alloc::{borrow::Cow, boxed::Box, format, sync::Arc, vec::Vec};

use ax_sync::Mutex;
use axfs_ng_vfs::{VfsError, VfsResult};
use sg200x_bsp::{
    pwm::{Pwm, PwmChannel, PwmMode, PwmPolarity},
    soc::PWM0_BASE,
};
use spin::LazyLock;

use crate::pseudofs::{
    DirMaker, NodeOpsMux, RwFile, SimpleDir, SimpleDirOps, SimpleFile, SimpleFileOperation,
    SimpleFs,
};

const PWM_SYSFS_CHIPS: u8 = 4;
const PWM_SYSFS_CHANNELS_PER_CHIP: u8 = 4;
const PWM_PERIOD_NS: u64 = 1_000_000_000;

/// Returns a [`DirMaker`] for `/sys/class/pwm`, to be embedded into the
/// kernel-wide sysfs tree by [`crate::pseudofs::sysfs`]. The pwm subsystem
/// shares the sysfs superblock so that `realpath()` on subordinate symlinks
/// keeps resolving inside `/sys`.
pub(crate) fn pwm_class_dir_maker(fs: Arc<SimpleFs>) -> DirMaker {
    SimpleDir::new_maker(fs.clone(), Arc::new(PwmClassDir { fs }))
}

#[derive(Clone, Copy, Default)]
struct PwmChannelState {
    exported: bool,
    enabled: bool,
    period_ns: u64,
    duty_ns: u64,
}

struct PwmChipState {
    pwm: Pwm,
    channels: [PwmChannelState; PWM_SYSFS_CHANNELS_PER_CHIP as usize],
}

struct PwmSysfsState {
    chips: Vec<PwmChipState>,
}

unsafe impl Send for PwmSysfsState {}
unsafe impl Sync for PwmSysfsState {}

impl PwmSysfsState {
    fn new() -> Self {
        let mut chips = Vec::with_capacity(PWM_SYSFS_CHIPS as usize);
        for index in 0..PWM_SYSFS_CHIPS {
            let pwm_addr = PWM0_BASE + index as usize * 0x1000 + ax_config::plat::PHYS_VIRT_OFFSET;
            let pwm = unsafe { Pwm::new(pwm_addr) };
            chips.push(PwmChipState {
                pwm,
                channels: [PwmChannelState::default(); PWM_SYSFS_CHANNELS_PER_CHIP as usize],
            });
        }
        Self { chips }
    }
}

static PWM_SYSFS_STATE: LazyLock<Mutex<PwmSysfsState>> =
    LazyLock::new(|| Mutex::new(PwmSysfsState::new()));

struct PwmClassDir {
    fs: Arc<SimpleFs>,
}

impl SimpleDirOps for PwmClassDir {
    fn child_names<'a>(&'a self) -> Box<dyn Iterator<Item = Cow<'a, str>> + 'a> {
        Box::new(
            (0..PWM_SYSFS_CHIPS)
                .map(|index| Cow::Owned(format!("pwmchip{}", index * PWM_SYSFS_CHANNELS_PER_CHIP))),
        )
    }

    fn lookup_child(&self, name: &str) -> VfsResult<NodeOpsMux> {
        let chip_index = parse_pwmchip_index(name).ok_or(VfsError::NotFound)?;
        Ok(NodeOpsMux::Dir(SimpleDir::new_maker(
            self.fs.clone(),
            Arc::new(PwmChipDir {
                fs: self.fs.clone(),
                chip_index,
            }),
        )))
    }

    fn is_cacheable(&self) -> bool {
        false
    }
}

struct PwmChipDir {
    fs: Arc<SimpleFs>,
    chip_index: u8,
}

impl SimpleDirOps for PwmChipDir {
    fn child_names<'a>(&'a self) -> Box<dyn Iterator<Item = Cow<'a, str>> + 'a> {
        let mut names = Vec::new();
        names.push(Cow::Borrowed("export"));
        names.push(Cow::Borrowed("unexport"));
        names.push(Cow::Borrowed("npwm"));
        let state = PWM_SYSFS_STATE.lock();
        if let Some(chip) = state.chips.get(self.chip_index as usize) {
            for (index, channel) in chip.channels.iter().enumerate() {
                if channel.exported {
                    names.push(Cow::Owned(format!("pwm{}", index)));
                }
            }
        }
        Box::new(names.into_iter())
    }

    fn lookup_child(&self, name: &str) -> VfsResult<NodeOpsMux> {
        match name {
            "export" => Ok(SimpleFile::new_regular(
                self.fs.clone(),
                RwFile::new({
                    let chip_index = self.chip_index;
                    move |req| match req {
                        SimpleFileOperation::Read => Ok(Some(Vec::new())),
                        SimpleFileOperation::Write(data) => {
                            if data.is_empty() || data.iter().all(|b| b.is_ascii_whitespace()) {
                                return Ok(None);
                            }
                            let channel = parse_u8(data)?;
                            export_pwm_channel(chip_index, channel)?;
                            Ok(None)
                        }
                    }
                }),
            )
            .into()),
            "unexport" => Ok(SimpleFile::new_regular(
                self.fs.clone(),
                RwFile::new({
                    let chip_index = self.chip_index;
                    move |req| match req {
                        SimpleFileOperation::Read => Ok(Some(Vec::new())),
                        SimpleFileOperation::Write(data) => {
                            if data.is_empty() || data.iter().all(|b| b.is_ascii_whitespace()) {
                                return Ok(None);
                            }
                            let channel = parse_u8(data)?;
                            unexport_pwm_channel(chip_index, channel)?;
                            Ok(None)
                        }
                    }
                }),
            )
            .into()),
            "npwm" => Ok(SimpleFile::new_regular(self.fs.clone(), || {
                Ok(format!("{}\n", PWM_SYSFS_CHANNELS_PER_CHIP))
            })
            .into()),
            _ => {
                let local_index = parse_pwm_local_index(name).ok_or(VfsError::NotFound)?;
                let state = PWM_SYSFS_STATE.lock();
                let exported = state
                    .chips
                    .get(self.chip_index as usize)
                    .and_then(|chip| chip.channels.get(local_index as usize))
                    .map(|ch| ch.exported)
                    .unwrap_or(false);
                if !exported {
                    return Err(VfsError::NotFound);
                }
                Ok(NodeOpsMux::Dir(SimpleDir::new_maker(
                    self.fs.clone(),
                    Arc::new(PwmChannelDir {
                        fs: self.fs.clone(),
                        chip_index: self.chip_index,
                        channel_index: local_index,
                    }),
                )))
            }
        }
    }

    fn is_cacheable(&self) -> bool {
        false
    }
}

struct PwmChannelDir {
    fs: Arc<SimpleFs>,
    chip_index: u8,
    channel_index: u8,
}

impl SimpleDirOps for PwmChannelDir {
    fn child_names<'a>(&'a self) -> Box<dyn Iterator<Item = Cow<'a, str>> + 'a> {
        Box::new(
            ["period", "duty_cycle", "enable"]
                .iter()
                .map(|s| Cow::Borrowed(*s)),
        )
    }

    fn lookup_child(&self, name: &str) -> VfsResult<NodeOpsMux> {
        let chip_index = self.chip_index;
        let channel_index = self.channel_index;
        let file = match name {
            "period" => SimpleFile::new_regular(
                self.fs.clone(),
                RwFile::new(move |req| match req {
                    SimpleFileOperation::Read => Ok(Some(
                        format!("{}\n", pwm_read_period(chip_index, channel_index)?).into_bytes(),
                    )),
                    SimpleFileOperation::Write(data) => {
                        if data.is_empty() || data.iter().all(|b| b.is_ascii_whitespace()) {
                            return Ok(None);
                        }
                        pwm_write_period(chip_index, channel_index, data)?;
                        Ok(None)
                    }
                }),
            ),
            "duty_cycle" => SimpleFile::new_regular(
                self.fs.clone(),
                RwFile::new(move |req| match req {
                    SimpleFileOperation::Read => Ok(Some(
                        format!("{}\n", pwm_read_duty(chip_index, channel_index)?).into_bytes(),
                    )),
                    SimpleFileOperation::Write(data) => {
                        if data.is_empty() || data.iter().all(|b| b.is_ascii_whitespace()) {
                            return Ok(None);
                        }
                        pwm_write_duty(chip_index, channel_index, data)?;
                        Ok(None)
                    }
                }),
            ),
            "enable" => SimpleFile::new_regular(
                self.fs.clone(),
                RwFile::new(move |req| match req {
                    SimpleFileOperation::Read => Ok(Some(
                        format!("{}\n", pwm_read_enable(chip_index, channel_index)?).into_bytes(),
                    )),
                    SimpleFileOperation::Write(data) => {
                        if data.is_empty() || data.iter().all(|b| b.is_ascii_whitespace()) {
                            return Ok(None);
                        }
                        pwm_write_enable(chip_index, channel_index, data)?;
                        Ok(None)
                    }
                }),
            ),
            _ => return Err(VfsError::NotFound),
        };
        Ok(file.into())
    }

    fn is_cacheable(&self) -> bool {
        false
    }
}

fn parse_pwmchip_index(name: &str) -> Option<u8> {
    let value = name.strip_prefix("pwmchip")?.parse::<u8>().ok()?;
    if value % PWM_SYSFS_CHANNELS_PER_CHIP != 0 {
        return None;
    }
    let index = value / PWM_SYSFS_CHANNELS_PER_CHIP;
    if index < PWM_SYSFS_CHIPS {
        Some(index)
    } else {
        None
    }
}

fn parse_pwm_local_index(name: &str) -> Option<u8> {
    let value = name.strip_prefix("pwm")?.parse::<u8>().ok()?;
    if value < PWM_SYSFS_CHANNELS_PER_CHIP {
        Some(value)
    } else {
        None
    }
}

fn parse_u64(data: &[u8]) -> VfsResult<u64> {
    core::str::from_utf8(data)
        .ok()
        .and_then(|t| t.trim().parse::<u64>().ok())
        .ok_or(VfsError::InvalidInput)
}

fn parse_u8(data: &[u8]) -> VfsResult<u8> {
    core::str::from_utf8(data)
        .ok()
        .and_then(|t| t.trim().parse::<u8>().ok())
        .ok_or(VfsError::InvalidInput)
}

fn export_pwm_channel(chip_index: u8, channel: u8) -> VfsResult<()> {
    if channel >= PWM_SYSFS_CHANNELS_PER_CHIP {
        return Err(VfsError::InvalidInput);
    }
    let mut state = PWM_SYSFS_STATE.lock();
    let chip = state
        .chips
        .get_mut(chip_index as usize)
        .ok_or(VfsError::InvalidInput)?;
    let entry = &mut chip.channels[channel as usize];
    if !entry.exported {
        *entry = PwmChannelState {
            exported: true,
            ..Default::default()
        };
    }
    Ok(())
}

fn unexport_pwm_channel(chip_index: u8, channel: u8) -> VfsResult<()> {
    if channel >= PWM_SYSFS_CHANNELS_PER_CHIP {
        return Err(VfsError::InvalidInput);
    }
    let mut state = PWM_SYSFS_STATE.lock();
    let chip = state
        .chips
        .get_mut(chip_index as usize)
        .ok_or(VfsError::InvalidInput)?;
    let entry = &mut chip.channels[channel as usize];
    if entry.enabled {
        let ch = PwmChannel::from_u8(channel).ok_or(VfsError::InvalidInput)?;
        chip.pwm.stop(ch);
        chip.pwm.disable_output(ch);
    }
    *entry = PwmChannelState::default();
    Ok(())
}

fn pwm_read_period(chip_index: u8, channel_index: u8) -> VfsResult<u64> {
    let state = PWM_SYSFS_STATE.lock();
    Ok(state
        .chips
        .get(chip_index as usize)
        .and_then(|c| c.channels.get(channel_index as usize))
        .ok_or(VfsError::InvalidInput)?
        .period_ns)
}

fn pwm_read_duty(chip_index: u8, channel_index: u8) -> VfsResult<u64> {
    let state = PWM_SYSFS_STATE.lock();
    Ok(state
        .chips
        .get(chip_index as usize)
        .and_then(|c| c.channels.get(channel_index as usize))
        .ok_or(VfsError::InvalidInput)?
        .duty_ns)
}

fn pwm_read_enable(chip_index: u8, channel_index: u8) -> VfsResult<u8> {
    let state = PWM_SYSFS_STATE.lock();
    Ok(state
        .chips
        .get(chip_index as usize)
        .and_then(|c| c.channels.get(channel_index as usize))
        .ok_or(VfsError::InvalidInput)?
        .enabled as u8)
}

fn pwm_write_period(chip_index: u8, channel_index: u8, data: &[u8]) -> VfsResult<()> {
    let value = parse_u64(data)?;
    if value == 0 {
        return Err(VfsError::InvalidInput);
    }
    let mut state = PWM_SYSFS_STATE.lock();
    let chip = state
        .chips
        .get_mut(chip_index as usize)
        .ok_or(VfsError::InvalidInput)?;
    let enabled = {
        let e = chip
            .channels
            .get_mut(channel_index as usize)
            .ok_or(VfsError::InvalidInput)?;
        e.period_ns = value;
        e.enabled
    };
    pwm_apply_channel(chip, channel_index, enabled)
}

fn pwm_write_duty(chip_index: u8, channel_index: u8, data: &[u8]) -> VfsResult<()> {
    let value = parse_u64(data)?;
    let mut state = PWM_SYSFS_STATE.lock();
    let chip = state
        .chips
        .get_mut(chip_index as usize)
        .ok_or(VfsError::InvalidInput)?;
    let enabled = {
        let e = chip
            .channels
            .get_mut(channel_index as usize)
            .ok_or(VfsError::InvalidInput)?;
        e.duty_ns = value;
        e.enabled
    };
    pwm_apply_channel(chip, channel_index, enabled)
}

fn pwm_write_enable(chip_index: u8, channel_index: u8, data: &[u8]) -> VfsResult<()> {
    let value = parse_u8(data)?;
    if value > 1 {
        return Err(VfsError::InvalidInput);
    }
    let mut state = PWM_SYSFS_STATE.lock();
    let chip = state
        .chips
        .get_mut(chip_index as usize)
        .ok_or(VfsError::InvalidInput)?;
    let channel = PwmChannel::from_u8(channel_index).ok_or(VfsError::InvalidInput)?;
    if value == 1 {
        let period_ns = chip
            .channels
            .get(channel_index as usize)
            .ok_or(VfsError::InvalidInput)?
            .period_ns;
        if period_ns == 0 {
            return Err(VfsError::InvalidInput);
        }
        pwm_apply_channel(chip, channel_index, true)?;
        chip.pwm.set_mode(channel, PwmMode::Continuous);
        chip.pwm.enable_output(channel);
        chip.pwm.start(channel);
        chip.channels[channel_index as usize].enabled = true;
    } else {
        chip.pwm.stop(channel);
        chip.pwm.disable_output(channel);
        chip.channels[channel_index as usize].enabled = false;
    }
    Ok(())
}

fn pwm_apply_channel(chip: &mut PwmChipState, channel_index: u8, running: bool) -> VfsResult<()> {
    let entry = chip
        .channels
        .get(channel_index as usize)
        .ok_or(VfsError::InvalidInput)?;
    if entry.period_ns == 0 {
        return Ok(());
    }
    if entry.duty_ns > entry.period_ns {
        return Err(VfsError::InvalidInput);
    }
    let frequency_hz = (PWM_PERIOD_NS / entry.period_ns) as u32;
    if frequency_hz == 0 {
        return Err(VfsError::InvalidInput);
    }
    let high_percent = (entry.duty_ns * 100 / entry.period_ns) as u8;
    let low_percent = 100u8.saturating_sub(high_percent);
    let channel = PwmChannel::from_u8(channel_index).ok_or(VfsError::InvalidInput)?;
    let result = if running {
        chip.pwm
            .update_frequency_duty(channel, frequency_hz, low_percent)
    } else {
        chip.pwm
            .configure_channel(channel, frequency_hz, low_percent, PwmPolarity::ActiveHigh)
    };
    result.map_err(|_| VfsError::InvalidInput)
}