linux-support 0.0.25

Comprehensive Linux support for namespaces, cgroups, processes, scheduling, parsing /proc, parsing /sys, signals, hyper threads, CPUS, NUMA nodes, unusual file descriptors, PCI devices and much, much more
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
// This file is part of linux-support. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-support/master/COPYRIGHT. No part of linux-support, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2020 The developers of linux-support. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-support/master/COPYRIGHT.


/// Represents a Linux interrupt request line (IRQ).
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Deserialize, Serialize)]
#[repr(transparent)]
pub struct InterruptRequest(u8);

#[allow(missing_docs)]
impl From<u8> for InterruptRequest
{
	#[inline(always)]
	fn from(value: u8) -> Self
	{
		Self(value)
	}
}

#[allow(missing_docs)]
impl Into<u8> for InterruptRequest
{
	#[inline(always)]
	fn into(self) -> u8
	{
		self.0
	}
}

impl ParseNumber for InterruptRequest
{
	#[inline(always)]
	fn parse_number(bytes: &[u8], radix: Radix, parse_byte: impl Fn(Radix, u8) -> Result<u8, ParseNumberError>) -> Result<Self, ParseNumberError>
	{
		u8::parse_number(bytes, radix, parse_byte).map(Self)
	}
}

#[allow(missing_docs)]
impl InterruptRequest
{
	/// All known interrupt request numbers.
	pub fn all(sys_path: &SysPath) -> io::Result<impl Iterator<Item=Self>>
	{
		fn map(dir_entry: io::Result<DirEntry>) -> Option<InterruptRequest>
		{
			let dir_entry = match dir_entry
			{
				Err(_) => return None,
				
				Ok(dir_entry) => dir_entry
			};
			
			match dir_entry.file_type()
			{
				Err(_) => return None,
				
				Ok(file_type) => if !file_type.is_dir()
				{
					return None
				}
			}
			
			let file_name = dir_entry.file_name().into_vec();
			u8::from_bytes(&file_name[..]).ok().map(|irq| InterruptRequest(irq))
		}
		
		Ok(sys_path.kernel_irq_folder_path().read_dir()?.filter_map(map))
	}
	
	/// Actions (Interrupt Names).
	///
	/// May be empty.
	///
	/// See also `self.procfs_actions()`.
	///
	/// Values observed on a Parallels VM:-
	///
	/// * (empty string).
	/// * `acpi`.
	/// * `ahci[0000:00:1f.2]`.
	/// * `ata_piix`.
	/// * `i8042`.
	/// * `rtc0`.
	/// * `timer`.
	/// * `virtio1`.
	/// * `virtio0-config`.
	/// * `virtio0-input.0`.
	/// * `virtio0-output.0`.
	#[inline(always)]
	pub fn sysfs_actions(self, sys_path: &SysPath) -> io::Result<Vec<InterruptRequestActionName>>
	{
		let file_path = self.sys_file_path(sys_path, "actions");
		
		match Self::raw_data_if_empty(file_path)?
		{
			None => Ok(Vec::new()),
			
			Some(raw_data_without_line_feed) => Ok
			(
				{
					let mut actions = Vec::new();
					for action in raw_data_without_line_feed.split_bytes(b',')
					{
						if !action.is_empty()
						{
							actions.push(unsafe { CString::from_vec_unchecked(action.to_vec()) });
						}
					}
					actions
				}
			)
		}
	}
	
	/// Actions (Interrupt Names).
	///
	/// May be empty.
	///
	/// See also `self.sysfs_actions()`.
	pub fn procfs_actions(self, proc_path: &ProcPath) -> io::Result<Vec<InterruptRequestActionName>>
	{
		let folder_path = self.proc_folder_path(proc_path);
		let read_dir = folder_path.read_dir()?;
		let mut actions = Vec::new();
		for dir_entry in read_dir
		{
			if let Ok(dir_entry) = dir_entry
			{
				if let Ok(file_type) = dir_entry.file_type()
				{
					if !file_type.is_dir()
					{
						continue
					}
					
					let action = dir_entry.file_name().os_str_to_c_string();
					actions.push(action);
				}
			}
		}
		Ok(actions)
	}
	
	
	/// Chip name.
	///
	/// Values observed on a Parallels VM:-
	///
	/// * `IO-APIC`.
	/// * `PCI-MSI`.
	/// * `XT-PIC`.
	#[inline(always)]
	pub fn chip_name(self, sys_path: &SysPath) -> io::Result<Option<CString>>
	{
		let file_path = self.sys_file_path(sys_path, "chip_name");
		Ok
		(
			Self::raw_data_if_empty(file_path)?.map(|raw_data_without_line_feed|
			{
				unsafe { CString::from_vec_unchecked(raw_data_without_line_feed) }
			})
		)
	}
	
	/// Hardware interrupt request line.
	///
	/// eg `10`; usually the same value as `self` but can be a large value, eg `512000`.
	///
	/// Note that `0xFFFF_FFFF` is invalid (this is not an error).
	#[inline(always)]
	pub fn hardware_interrupt_request_line(self, sys_path: &SysPath) -> io::Result<Option<u32>>
	{
		let file_path = self.sys_file_path(sys_path, "hwirq");
		
		match Self::raw_data_if_empty(file_path)?
		{
			None => Ok(None),
			
			Some(bytes) =>
			{
				let value = i32::from_bytes(&bytes[..]).map_err(io_error_invalid_data)?;
				Ok(Some(value as u32))
			}
		}
	}
	
	/// Name.
	///
	/// Values observed on a Parallels VM:-
	///
	/// * `Some(edge)`.
	/// * `Some(fasteoi)`.
	#[inline(always)]
	pub fn name(self, sys_path: &SysPath) -> io::Result<Option<CString>>
	{
		let file_path = self.sys_file_path(sys_path, "name");
		Ok
		(
			Self::raw_data_if_empty(file_path)?.map(|raw_data_without_line_feed|
			{
				unsafe { CString::from_vec_unchecked(raw_data_without_line_feed) }
			})
		)
	}
	
	/// Type.
	#[inline(always)]
	pub fn type_(self, sys_path: &SysPath) -> io::Result<InterruptRequestType>
	{
		let file_path = self.sys_file_path(sys_path, "type");
		file_path.read_value()
	}
	
	/// Wake up.
	#[inline(always)]
	pub fn wake_up(self, sys_path: &SysPath) -> io::Result<InterruptRequestWakeUp>
	{
		let file_path = self.sys_file_path(sys_path, "wakeup");
		file_path.read_value()
	}
	
	/// Number of occurrences per-HyperThread.
	///
	/// Number of indices is the number of possible HyperThreads (`/sys/devices/system/cpu/possible`).
	#[inline(always)]
	pub fn occurrences_per_hyper_thread(self, sys_path: &SysPath) -> io::Result<PerBitSetAwareData<HyperThread, u64>>
	{
		let file_path = self.sys_file_path(sys_path, "per_cpu_count");
		let comma_separated_string = file_path.read_raw_without_line_feed()?;
		
		#[inline(always)]
		fn mapper((index, count_in_bytes): (usize, &[u8])) -> Result<(HyperThread, u64), BitSetAwareTryFromU16Error>
		{
			let count = u64::parse_decimal_number(count_in_bytes)?;
			let hyper_thread = HyperThread::try_from(index)?;
			Ok((hyper_thread, count))
		}
		
		let constructor = comma_separated_string.split_bytes(b',').enumerate().map(mapper);
		let result = PerBitSetAwareData::from_iterator(constructor);
		result.map_err(io_error_invalid_data)
	}
	
	/// Usually `ffffffff` (ie `/sys/devices/system/cpu/possible` but as a bitmask not a list).
	#[inline(always)]
	pub fn default_smp_affinity(proc_path: &ProcPath) -> io::Result<HyperThreads>
	{
		proc_path.irq_file_path("default_smp_affinity").parse_comma_separated_bit_set().map(HyperThreads)
	}
	
	#[inline(always)]
	pub fn set_default_smp_affinity(proc_path: &ProcPath, affinity: &HyperThreads) -> io::Result<()>
	{
		affinity.set_affinity(proc_path.irq_file_path("default_smp_affinity"))
	}
	
	#[inline(always)]
	pub fn affinity_hint(self, proc_path: &ProcPath) -> HyperThreads
	{
		self.get_hyper_threads(proc_path, "affinity_hint")
	}
	
	#[inline(always)]
	pub fn effective_affinity(self, proc_path: &ProcPath) -> HyperThreads
	{
		self.get_hyper_threads(proc_path, "effective_affinity")
	}
	
	#[inline(always)]
	pub fn effective_affinity_list(self, proc_path: &ProcPath) -> HyperThreads
	{
		self.get_hyper_threads_list(proc_path, "effective_affinity_list")
	}
	
	/// Returns `None` if not configured for NUMA.
	#[inline(always)]
	pub fn numa_node(self, proc_path: &ProcPath) -> Option<NumaNode>
	{
		let file_path = self.proc_file_path(proc_path, "node");
		if file_path.exists()
		{
			Some(file_path.read_value().unwrap())
		}
		else
		{
			None
		}
	}
	
	#[inline(always)]
	pub fn set_smp_affinity(self, proc_path: &ProcPath, affinity: &HyperThreads) -> io::Result<()>
	{
		affinity.set_affinity(self.proc_file_path(proc_path, "smp_affinity"))
	}
	
	#[inline(always)]
	pub fn smp_affinity(self, proc_path: &ProcPath) -> HyperThreads
	{
		self.get_hyper_threads(proc_path, "smp_affinity")
	}
	
	#[inline(always)]
	pub fn set_smp_affinity_list(self, proc_path: &ProcPath, affinity: &HyperThreads) -> io::Result<()>
	{
		affinity.set_affinity_list(self.proc_file_path(proc_path, "smp_affinity_list"))
	}
	
	#[inline(always)]
	pub fn smp_affinity_list(self, proc_path: &ProcPath) -> HyperThreads
	{
		self.get_hyper_threads_list(proc_path, "smp_affinity_list")
	}
	
	/// Returns `count`, `unhandled` and `last_unhandled_milliseconds`.
	#[inline(always)]
	pub fn spurious(self, proc_path: &ProcPath) -> io::Result<SpuriousInterruptRequestInformation>
	{
		let file_path = self.proc_file_path(proc_path, "spurious");
		
		let data = file_path.read_raw()?;
		let mut lines = data.split_bytes_n(3, b'\n');
		
		fn parse_line<'a>(lines: &mut impl Iterator<Item=&'a [u8]>, expected_field_name: &'static [u8], ends_with: &'static [u8]) -> io::Result<usize>
		{
			let line = lines.next().unwrap();
			let mut fields = line.split_bytes_n(2, b' ');
			let field_name = fields.next().unwrap();
			if unlikely!(field_name != expected_field_name)
			{
				return Err(io_error_other("Invalid count field name"))
			}
			let field_value_and_unit = fields.next().unwrap();
			if unlikely!(!field_value_and_unit.ends_with(ends_with))
			{
				return Err(io_error_other( "Does not end with unit expected"))
			}
			let field_value = &field_value_and_unit[ .. field_value_and_unit.len() - ends_with.len()];
			usize::from_bytes(field_value).map_err(|_| io_error_other("Invalid field value"))
		}
		
		let count = parse_line(&mut lines, b"count", b"")?;
		let unhandled = parse_line(&mut lines, b"unhandled", b"")?;
		let last_unhandled_milliseconds = parse_line(&mut lines, b"last_unhandled", b" ms")?;
		
		Ok
		(
			SpuriousInterruptRequestInformation
			{
				count,
				unhandled,
				last_unhandled_milliseconds,
			}
		)
	}
	
	#[inline(always)]
	fn get_hyper_threads(self, proc_path: &ProcPath, file_name: &str) -> HyperThreads
	{
		HyperThreads(self.proc_file_path(proc_path, file_name).parse_comma_separated_bit_set().unwrap())
	}
	
	#[inline(always)]
	fn get_hyper_threads_list(self, proc_path: &ProcPath, file_name: &str) -> HyperThreads
	{
		HyperThreads(self.proc_file_path(proc_path, file_name).read_hyper_thread_or_numa_node_list().unwrap())
	}
	
	// Annoningly, Linux does not output "\n" for an empty value for actions and name but "".
	#[inline(always)]
	fn raw_data_if_empty(file_path: PathBuf) -> io::Result<Option<Vec<u8>>>
	{
		let raw = file_path.read_raw()?;
		let length = raw.len();
		if length == 0
		{
			Ok(None)
		}
		else
		{
			let mut vec = raw.into_vec();
			let should_be_line_feed = vec.remove(length - 1);
			if unlikely!(should_be_line_feed != b'\n')
			{
				Err(io_error_invalid_data("File lacks terminating line feed"))
			}
			else
			{
				Ok(Some(vec))
			}
		}
	}
	
	#[inline(always)]
	fn sys_file_path(self, sys_path: &SysPath, file_name: &str) -> PathBuf
	{
		sys_path.global_irq_file_path(self, file_name)
	}
	
	#[inline(always)]
	fn proc_file_path(self, proc_path: &ProcPath, file_name: &str) -> PathBuf
	{
		proc_path.irq_number_file_path(self, file_name)
	}
	
	#[inline(always)]
	fn proc_folder_path(self, proc_path: &ProcPath) -> PathBuf
	{
		proc_path.irq_number_folder_path(self)
	}
	
	#[inline(always)]
	pub(crate) fn file_name(self) -> String
	{
		format!("{}", self.0)
	}
}