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
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
// 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.


/// A file descriptor for a BPF map.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MapFileDescriptor(RawFd);

impl Drop for MapFileDescriptor
{
	#[inline(always)]
	fn drop(&mut self)
	{
		self.0.close()
	}
}

impl AsRawFd for MapFileDescriptor
{
	#[inline(always)]
	fn as_raw_fd(&self) -> RawFd
	{
		self.0
	}
}

impl IntoRawFd for MapFileDescriptor
{
	#[inline(always)]
	fn into_raw_fd(self) -> RawFd
	{
		self.0
	}
}

impl FromRawFd for MapFileDescriptor
{
	#[inline(always)]
	unsafe fn from_raw_fd(fd: RawFd) -> Self
	{
		Self(fd)
	}
}

impl FileDescriptor for MapFileDescriptor
{
}

impl BpfFileDescriptor for MapFileDescriptor
{
	type Identifier = MapIdentifier;
	
	type Information = bpf_map_info;
	
	type Access = KernelOnlyAccessPermissions;
	
	const GetFileDescriptor: bpf_cmd = bpf_cmd::BPF_MAP_GET_FD_BY_ID;
	
	const DefaultAccess: Self::Access = KernelOnlyAccessPermissions::KernelReadAndWriteUserspaceReadWrite;
	
	#[inline(always)]
	fn access_permissions_to_open_flags(access: Self::Access) -> u32
	{
		access.to_map_flags().bits() as u32
	}
}

impl MemoryMappableFileDescriptor for MapFileDescriptor
{
}

impl UsedAsValueInArrayMapDescriptor for MapFileDescriptor
{
	#[inline(always)]
	fn transmute_from_file_descriptor_copies(values: &[Self]) -> &[RawFd]
	{
		unsafe { transmute(values) }
	}
}

impl ProvidesIdentifierWhenUsedAsValueInArrayMapDescriptor for MapFileDescriptor
{
	type Identifier = MapIdentifier;
}

impl MapFileDescriptor
{
	/// Gets the next key.
	///
	/// Returns `None` if the `key` is the last one (ie `capacity() - 1`).
	#[inline(always)]
	pub fn get_next_key<K: Copy>(&self, key: *const K) -> Result<Option<K>, Errno>
	{
		debug_assert_ne!(size_of::<K>(), 0);
		
		let mut next_key = unsafe_uninitialized();
		
		let mut attr = bpf_attr::default();
		attr.map_change = BpfCommandMapChange
		{
			map_fd: self.as_raw_fd(),
			key: AlignedU64::from(key),
			value_or_next_key: BpfCommandMapChangeValueOrNextKey
			{
				next_key: AlignedU64::from(&mut next_key),
			},
			flags: BPF_MAP_UPDATE_ELEM_flags::BPF_ANY,
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_GET_NEXT_KEY);
		if likely!(result == 0)
		{
			Ok(Some(next_key))
		}
		else if likely!(result == -1)
		{
			let errno = errno();
			match errno.0
			{
				// "If key is the last element, -1 is returned and errno is set to ENOENT'.
				ENOENT => Ok(None),
				
				// "Other possible errno values are ENOMEM, EFAULT, EPERM, and EINVAL".
				_ => Err(errno)
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_GET_NEXT_KEY)", result))
		}
	}
	
	#[inline(always)]
	pub(crate) fn get<K: Copy, V: Copy>(&self, key: &K) -> Option<V>
	{
		debug_assert_ne!(size_of::<V>(), 0);
		
		let mut value: V = unsafe_uninitialized();
		let found = self.get_internal(key, new_non_null(&mut value));
		if found
		{
			Some(value)
		}
		else
		{
			None
		}
	}
	
	#[inline(always)]
	pub(crate) fn get_variably_sized<K: Copy, V: Copy>(&self, key: &K, length: usize) -> Option<Vec<V>>
	{
		let mut allocate_values: Vec<V> = Vec::with_capacity(length);
		
		let found = self.get_variably_sized_vector(key, &mut allocate_values);
		if found
		{
			unsafe { allocate_values.set_len(length) };
			Some(allocate_values)
		}
		else
		{
			None
		}
	}
	
	#[inline(always)]
	pub(crate) fn get_variably_sized_vector<K: Copy, V: Copy>(&self, key: &K, allocate_values: &mut Vec<V>) -> bool
	{
		self.get_internal(key, new_non_null(allocate_values.as_mut_ptr()))
	}
	
	#[inline(always)]
	fn get_internal<K: Copy, V: Copy>(&self, key: &K, value: NonNull<V>) -> bool
	{
		debug_assert_ne!(size_of::<K>(), 0);
		
		let mut attr = bpf_attr::default();
		attr.map_change = BpfCommandMapChange
		{
			map_fd: self.as_raw_fd(),
			key: AlignedU64::from(key),
			value_or_next_key: BpfCommandMapChangeValueOrNextKey
			{
				value: AlignedU64::from(value),
			},
			flags: BPF_MAP_UPDATE_ELEM_flags::BPF_ANY,
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_LOOKUP_ELEM);
		if likely!(result == 0)
		{
			true
		}
		else if likely!(result == -1)
		{
			let errno = errno();
			match errno.0
			{
				ENOENT => false,
				ENOTSUPP | EOPNOTSUPP => panic!("Operation is unsupported"),
				_ => panic!("Unexpected error {}", errno)
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_LOOKUP_ELEM)", result))
		}
	}
	
	/// Insert or set.
	///
	/// Errors if already present.
	pub(crate) fn insert_or_set<K: Copy, V: Copy>(&self, key: &K, value: &V, lock_flags: LockFlags) -> Result<(), ()>
	{
		match self.update(key, value, BPF_MAP_UPDATE_ELEM_flags::BPF_ANY, lock_flags)
		{
			Ok(()) => Ok(()),
			
			Err(errno) => match errno.0
			{
				E2BIG => Err(()),
				
				EEXIST => unreachable_code(format_args!("Should not return `EEXIST` as flag `BPF_NOEXIST` not specified")),
				
				ENOENT => unreachable_code(format_args!("Should not return `ENOENT` as flag `BPF_EXIST` not specified")),
				
				ENOMEM => Err(()),
				
				_ => panic!("Unexpected error `{}`", errno),
			}
		}
	}
	
	/// Insert or set.
	///
	/// Errors if already present.
	pub(crate) fn insert_or_set_variably_sized<K: Copy, V: Copy>(&self, key: &K, values: &[V]) -> Result<(), ()>
	{
		match self.update(key, values.as_ptr(), BPF_MAP_UPDATE_ELEM_flags::BPF_ANY, LockFlags::DoNotLock)
		{
			Ok(()) => Ok(()),
			
			Err(errno) => match errno.0
			{
				E2BIG => Err(()),
				
				EEXIST => unreachable_code(format_args!("Should not return `EEXIST` as flag `BPF_NOEXIST` not specified")),
				
				ENOENT => unreachable_code(format_args!("Should not return `ENOENT` as flag `BPF_EXIST` not specified")),
				
				ENOMEM => Err(()),
				
				_ => panic!("Unexpected error `{}`", errno),
			}
		}
	}
	
	/// Insert.
	///
	/// Errors if already present.
	pub(crate) fn insert<K: Copy, V: Copy>(&self, key: &K, value: &V, lock_flags: LockFlags) -> Result<(), InsertError>
	{
		use self::InsertError::*;
		
		match self.update(key, value, BPF_MAP_UPDATE_ELEM_flags::BPF_NOEXIST, lock_flags)
		{
			Ok(()) => Ok(()),
			
			Err(errno) => match errno.0
			{
				E2BIG => Err(MaximumCapacityReached),
				
				EEXIST => Err(AlreadyPresent),
				
				ENOENT => unreachable_code(format_args!("Should not return `ENOENT` as flag `BPF_EXIST` not specified")),
				
				ENOMEM => Err(OutOfMemory),
				
				_ => panic!("Unexpected error `{}`", errno),
			}
		}
	}
	
	/// Insert.
	///
	/// Errors if already present.
	pub(crate) fn insert_variably_sized<K: Copy, V: Copy>(&self, key: &K, values: &[V]) -> Result<(), InsertError>
	{
		use self::InsertError::*;
		
		match self.update(key, values.as_ptr(), BPF_MAP_UPDATE_ELEM_flags::BPF_NOEXIST, LockFlags::DoNotLock)
		{
			Ok(()) => Ok(()),
			
			Err(errno) => match errno.0
			{
				E2BIG => Err(MaximumCapacityReached),
				
				EEXIST => Err(AlreadyPresent),
				
				ENOENT => unreachable_code(format_args!("Should not return `ENOENT` as flag `BPF_EXIST` not specified")),
				
				ENOMEM => Err(OutOfMemory),
				
				_ => panic!("Unexpected error `{}`", errno),
			}
		}
	}
	
	/// Set.
	///
	/// Returns an error if the key does not exist.
	///
	/// If specifying `BPF_MAP_UPDATE_ELEM_flags::BPF_F_LOCK`:-
	///
	/// * Only valid for basic hash, basic array and cgroup local-storage when `V` has been created with a `bpf_spin_lock`.
	/// * This will panic if this array was not created with a spinlock; it is not valid on per-CPU and per-device arrays nor if the array has been memory-mapped.
	/// * Additionally, the map needs to have been created with BTF data.
	/// * Furthermore, `V` must be a struct of type `SpinLockableValue`.
	pub(crate) fn set<K: Copy, V: Copy>(&self, key: &K, value: &V, lock_flags: LockFlags) -> Result<(), ()>
	{
		match self.update(key, value, BPF_MAP_UPDATE_ELEM_flags::BPF_EXIST, lock_flags)
		{
			Ok(()) => Ok(()),
			
			Err(errno) => match errno.0
			{
				E2BIG => unreachable_code(format_args!("Should not return `E2BIG` as flag `BPF_NOEXIST` or `BPF_ANY` not specified")),
				
				EEXIST => unreachable_code(format_args!("Should not return `EEXIST` as flag `BPF_NOEXIST` not specified")),
				
				ENOENT => Err(()),
				
				_ => panic!("Unexpected error `{}`", errno),
			}
		}
	}
	
	/// Set.
	///
	/// Returns an error if the key does not exist.
	pub(crate) fn set_variably_sized<K: Copy, V: Copy>(&self, key: &K, values: &[V]) -> Result<(), ()>
	{
		match self.update(key, values.as_ptr(), BPF_MAP_UPDATE_ELEM_flags::BPF_EXIST, LockFlags::DoNotLock)
		{
			Ok(()) => Ok(()),
			
			Err(errno) => match errno.0
			{
				E2BIG => unreachable_code(format_args!("Should not return `E2BIG` as flag `BPF_NOEXIST` or `BPF_ANY` not specified")),
				
				EEXIST => unreachable_code(format_args!("Should not return `EEXIST` as flag `BPF_NOEXIST` not specified")),
				
				ENOENT => Err(()),
				
				_ => panic!("Unexpected error `{}`", errno),
			}
		}
	}
	
	/// Set.
	///
	/// For some weird reason, one needs to specify different `map_flags`.
	///
	/// See the Linux kernel function `bpf_fd_array_map_update_elem()`.
	pub(crate) fn set_for_file_descriptor_array_map<K: Copy, V: Copy>(&self, key: &K, value: &V) -> Result<(), ()>
	{
		match self.update(key, value, BPF_MAP_UPDATE_ELEM_flags::BPF_ANY, LockFlags::DoNotLock)
		{
			Ok(()) => Ok(()),
			
			Err(errno) => match errno.0
			{
				E2BIG => Err(()),
				
				EEXIST => unreachable_code(format_args!("Should not return `EEXIST` as flag `BPF_NOEXIST` not specified")),
				
				ENOENT => unreachable_code(format_args!("Should not return `ENOENT` as flag `BPF_EXIST` not specified")),
				
				ENOMEM => Err(()),
				
				_ => panic!("Unexpected error `{}`", errno),
			}
		}
	}
	
	#[inline(always)]
	fn update<K: Copy, V: Copy>(&self, key: &K, value: *const V, flags: BPF_MAP_UPDATE_ELEM_flags, lock_flags: LockFlags) -> Result<(), Errno>
	{
		debug_assert_ne!(size_of::<K>(), 0);
		debug_assert_ne!(size_of::<V>(), 0);
		
		let mut attr = bpf_attr::default();
		attr.map_change = BpfCommandMapChange
		{
			map_fd: self.as_raw_fd(),
			key: AlignedU64::from(key),
			value_or_next_key: BpfCommandMapChangeValueOrNextKey
			{
				value: AlignedU64::from(value),
			},
			flags: flags | lock_flags.to_update_flags(),
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_UPDATE_ELEM);
		if likely!(result == 0)
		{
			Ok(())
		}
		else if likely!(result == -1)
		{
			let errno = errno();
			match errno.0
			{
				ENOTSUPP | EOPNOTSUPP => panic!("Operation is unsupported"),
				_ => Err(errno)
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_UPDATE)", result))
		}
	}
	
	#[inline(always)]
	pub(crate) fn lookup_and_delete<K: Copy, V: Copy>(&self, key: &K) -> Result<Option<V>, Errno>
	{
		debug_assert_ne!(size_of::<K>(), 0);
		debug_assert_ne!(size_of::<V>(), 0);
		
		let mut value: V = unsafe_uninitialized();
		
		let mut attr = bpf_attr::default();
		attr.map_change = BpfCommandMapChange
		{
			map_fd: self.as_raw_fd(),
			key: AlignedU64::from(key),
			value_or_next_key: BpfCommandMapChangeValueOrNextKey
			{
				value: AlignedU64::from(&mut value),
			},
			flags: BPF_MAP_UPDATE_ELEM_flags::empty(),
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_LOOKUP_AND_DELETE_ELEM);
		if likely!(result == 0)
		{
			Ok(Some(value))
		}
		else if likely!(result == -1)
		{
			let errno = errno();
			match errno.0
			{
				ENOENT => Ok(None),
				_ => Err(errno)
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_LOOKUP_AND_DELETE_ELEM)", result))
		}
	}
	
	/// Returns `Ok(true)` if `key` was present.
	#[inline(always)]
	pub(crate) fn delete<K: Copy>(&self, key: &K) -> Result<bool, Errno>
	{
		debug_assert_ne!(size_of::<K>(), 0);
		
		let mut attr = bpf_attr::default();
		attr.map_change = BpfCommandMapChange
		{
			map_fd: self.as_raw_fd(),
			key: AlignedU64::from(key),
			value_or_next_key: BpfCommandMapChangeValueOrNextKey
			{
				value: AlignedU64::Null,
			},
			flags: BPF_MAP_UPDATE_ELEM_flags::empty(),
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_DELETE_ELEM);
		if likely!(result == 0)
		{
			Ok(true)
		}
		else if likely!(result == -1)
		{
			let errno = errno();
			match errno.0
			{
				ENOENT => Ok(false),
				_ => Err(errno)
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_DELETE_ELEM)", result))
		}
	}
	
	/// The map can no longer be updated from user space.
	///
	/// Not supported by `BPF_MAP_TYPE_STRUCT_OPS`.
	///
	/// Requires the capability `CAP_SYS_ADMIN`.
	/// Can only be called once.
	#[inline(always)]
	pub(crate) fn freeze(&self) -> Result<(), Errno>
	{
		let mut attr = bpf_attr::default();
		attr.map_change = BpfCommandMapChange
		{
			map_fd: self.as_raw_fd(),
			key: AlignedU64::Null,
			value_or_next_key: BpfCommandMapChangeValueOrNextKey
			{
				value: AlignedU64::Null,
			},
			flags: BPF_MAP_UPDATE_ELEM_flags::empty(),
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_FREEZE);
		if likely!(result == 0)
		{
			Ok(())
		}
		else if likely!(result == -1)
		{
			match errno().0
			{
				EINVAL => panic!("Invalid attr"),
				ENOTSUPP => panic!("Not supported for maps of type `BPF_MAP_TYPE_STRUCT_OPS`"),
				EBUSY => panic!("Already frozen"),
				EPERM => panic!("Permission denied"),
				errno @ _ => panic!("Unexpected error `{}`", errno),
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_FREEZE)", result))
		}
	}
	
	/// Returns `(values_filled, start of next batch position, more_entries_to_return)`.
	/// `values_filled.len()` may be less than `keys.len()`.
	#[inline(always)]
	pub(crate) fn get_batch<K: Copy, V: Copy>(&self, batch_position: Option<&OpaqueBatchPosition<K>>, keys: &[K]) -> Result<(Vec<V>, OpaqueBatchPosition<K>, bool), Errno>
	{
		let keys_length = keys.len();
		let mut values = Vec::with_capacity(keys_length);
		
		let (count, out_batch, more) = self.lookup_batch(batch_position, keys, AlignedU64::from(values.as_mut_ptr()))?;
		unsafe { values.set_len(count as usize) };
		Ok((values, out_batch, more))
	}
	
	#[inline(always)]
	pub(crate) fn get_batch_variably_sized<K: Copy>(&self, batch_position: Option<&OpaqueBatchPosition<K>>, keys: &[K], values: &mut [u8]) -> Result<(usize, OpaqueBatchPosition<K>, bool), Errno>
	{
		let (count, out_batch, more) = self.lookup_batch(batch_position, keys, AlignedU64::from(values.as_mut_ptr()))?;
		Ok((count as usize, out_batch, more))
	}
	
	/// Returns `(values_filled, start of next batch position, more_entries_to_return)`.
	/// `values_filled.len()` may be less than `keys.len()`.
	#[inline(always)]
	pub(crate) fn lookup_batch<K: Copy>(&self, batch_position: Option<&OpaqueBatchPosition<K>>, keys: &[K], values: AlignedU64) -> Result<(u32, OpaqueBatchPosition<K>, bool), Errno>
	{
		let keys_length = keys.len();
		assert_ne!(keys_length, 0, "There must be at least one key");
		debug_assert!(keys_length <= u32::MAX as usize);
		
		let mut out_batch: OpaqueBatchPosition<K> = unsafe_uninitialized();
		
		let mut attr = bpf_attr::default();
		attr.batch = BpfCommandMapBatch
		{
			in_batch: match batch_position
			{
				None => AlignedU64::Null,
				Some(batch_position) => AlignedU64::from(batch_position),
			},
			out_batch: AlignedU64::from(&mut out_batch),
			keys: AlignedU64::from(keys),
			values,
			count: keys_length as u32,
			map_fd: self.as_raw_fd(),
			elem_flags: elem_flags::empty(),
			flags: 0,
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_LOOKUP_BATCH);
		let count = unsafe { attr.batch.count };
		if likely!(result == 0)
		{
			Ok((count, out_batch, true))
		}
		else if likely!(result == -1)
		{
			let errno = errno();
			match errno.0
			{
				ENOENT =>
				{
					Ok((count, out_batch, false))
				},
				
				_ => Err(errno),
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_LOOKUP_BATCH)", result))
		}
	}
	
	/// Returns `(values_filled, start of next batch position, more_entries_to_return)`.
	/// `values_filled.len()` may be less than `keys.len()`.
	#[inline(always)]
	pub(crate) fn get_and_delete_batch<K: Copy, V: Copy>(&self, batch_position: Option<&OpaqueBatchPosition<K>>, keys: &[K]) -> Result<(Vec<V>, OpaqueBatchPosition<K>, bool), Errno>
	{
		let keys_length = keys.len();
		let mut values = Vec::with_capacity(keys_length);
		
		let (count, out_batch, more) = self.lookup_and_delete_batch(batch_position, keys, AlignedU64::from(values.as_mut_ptr()))?;
		unsafe { values.set_len(count as usize) };
		Ok((values, out_batch, more))
	}
	
	#[inline(always)]
	pub(crate) fn get_and_delete_batch_variably_sized<K: Copy>(&self, batch_position: Option<&OpaqueBatchPosition<K>>, keys: &[K], values: &mut [u8]) -> Result<(usize, OpaqueBatchPosition<K>, bool), Errno>
	{
		let (count, out_batch, more) = self.lookup_and_delete_batch(batch_position, keys, AlignedU64::from(values.as_mut_ptr()))?;
		Ok((count as usize, out_batch, more))
	}
	
	/// Returns `(values_filled, start of next batch position, more_entries_to_return)`.
	/// `values_filled.len()` may be less than `keys.len()`.
	#[inline(always)]
	fn lookup_and_delete_batch<K: Copy>(&self, batch_position: Option<&OpaqueBatchPosition<K>>, keys: &[K], values: AlignedU64) -> Result<(u32, OpaqueBatchPosition<K>, bool), Errno>
	{
		let keys_length = keys.len();
		assert_ne!(keys_length, 0, "There must be at least one key");
		debug_assert!(keys_length <= u32::MAX as usize);
		
		let mut out_batch: OpaqueBatchPosition<K> = unsafe_uninitialized();
		
		let mut attr = bpf_attr::default();
		attr.batch = BpfCommandMapBatch
		{
			in_batch: match batch_position
			{
				None => AlignedU64::Null,
				Some(batch_position) => AlignedU64::from(batch_position),
			},
			out_batch: AlignedU64::from(&mut out_batch),
			keys: AlignedU64::from(keys),
			values,
			count: keys_length as u32,
			map_fd: self.as_raw_fd(),
			elem_flags: elem_flags::empty(),
			flags: 0,
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_LOOKUP_AND_DELETE_BATCH);
		let count = unsafe { attr.batch.count };
		if likely!(result == 0)
		{
			Ok((count, out_batch, true))
		}
		else if likely!(result == -1)
		{
			let errno = errno();
			match errno.0
			{
				ENOENT =>
				{
					Ok((count, out_batch, false))
				},
				
				_ => Err(errno),
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_LOOKUP_AND_DELETE_BATCH)", result))
		}
	}
	
	/// `keys` and `values` must be the same length.
	#[inline(always)]
	pub(crate) fn set_batch<K: Copy, V: Copy>(&self, keys: &[K], values: &[V], lock_flags: LockFlags) -> Result<usize, Errno>
	{
		self.update_batch(keys, AlignedU64::from(values), lock_flags)
	}
	
	#[inline(always)]
	pub(crate) fn set_batch_variably_sized<K: Copy>(&self, keys: &[K], values: &[u8]) -> Result<usize, Errno>
	{
		self.update_batch(keys, AlignedU64::from(values), LockFlags::DoNotLock)
	}
	
	/// `keys` and `values` must be the same length.
	#[inline(always)]
	 fn update_batch<K: Copy>(&self, keys: &[K], values: AlignedU64, lock_flags: LockFlags) -> Result<usize, Errno>
	{
		let keys_length = keys.len();
		assert_ne!(keys_length, 0, "There must be at least one key");
		debug_assert!(keys_length <= u32::MAX as usize);
		
		let mut attr = bpf_attr::default();
		attr.batch = BpfCommandMapBatch
		{
			in_batch: AlignedU64::Null,
			out_batch: AlignedU64::Null,
			keys: AlignedU64::from(keys),
			values,
			count: keys_length as u32,
			map_fd: self.as_raw_fd(),
			elem_flags: lock_flags.to_elem_flags(),
			flags: 0,
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_UPDATE_BATCH);
		let count = unsafe { attr.batch.count };
		if likely!(result == 0)
		{
			Ok(count as usize)
		}
		else if likely!(result == -1)
		{
			Err(errno())
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_UPDATE_BATCH)", result))
		}
	}
	
	/// Returns `(count_of_entries_filled, more_entries_to_return)`.
	pub(crate) fn delete_batch<K: Copy>(&self, keys: &[K]) -> Result<(usize, bool), Errno>
	{
		let keys_length = keys.len();
		assert_ne!(keys_length, 0, "There must be at least one key");
		debug_assert!(keys_length <= u32::MAX as usize);
	
		let mut attr = bpf_attr::default();
		attr.batch = BpfCommandMapBatch
		{
			in_batch: AlignedU64::Null,
			out_batch: AlignedU64::Null,
			keys: AlignedU64::from(keys),
			values: AlignedU64::Null,
			count: keys_length as u32,
			map_fd: self.as_raw_fd(),
			elem_flags: elem_flags::empty(),
			flags: 0,
		};
		
		let result = attr.syscall(bpf_cmd::BPF_MAP_DELETE_BATCH);
		let count = unsafe { attr.batch.count };
		if likely!(result == 0)
		{
			Ok((count as usize, true))
		}
		else if likely!(result == -1)
		{
			let errno = errno();
			match errno.0
			{
				ENOENT => Ok((count as usize, false)),
				
				_ => Err(errno),
			}
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_DELETE_BATCH)", result))
		}
	}
	
	/// `parsed_bpf_type_format_map_data` must be `None` for `map_type` when it is:-
	///
	/// * `MapType::HashPerDevice`.
	/// * `MapType::ArrayPerDevice`.
	/// * `MapType::StructOps`.
	///
	/// `parsed_bpf_type_format_map_data` must be `Some` for `map_type` when it is:-
	///
	/// * `MapType::SocketStorage`.
	pub(crate) fn create(map_file_descriptors: &mut FileDescriptorsMap<MapFileDescriptor>, map_type: MapType, map_name: &MapName, parsed_bpf_type_format_map_data: Option<&ParsedBpfTypeFormatMapData>) -> Result<Rc<Self>, MapCreationError>
	{
		let (map_type, map_flags, (btf_fd, btf_key_type_id, btf_value_type_id, btf_vmlinux_value_type_id), map_ifindex, numa_node, inner_map_fd, key_size, value_size, max_entries) = map_type.to_values(parsed_bpf_type_format_map_data)?;
		
		let mut attributes = bpf_attr
		{
			map_create: BpfCommandMapCreate
			{
				map_type,
				key_size,
				value_size,
				max_entries,
				map_flags,
				inner_map_fd,
				numa_node,
				map_name: map_name.into(),
				map_ifindex,
				
				btf_fd,
				btf_key_type_id,
				btf_value_type_id,
				btf_vmlinux_value_type_id,
			}
		};
		
		let result = attributes.syscall(bpf_cmd::BPF_MAP_CREATE);
		if likely!(result >= 0)
		{
			let map_file_descriptor = Self(result);
			Ok(map_file_descriptors.add(map_name.clone(), map_file_descriptor)?)
		}
		else if likely!(result == -1)
		{
			Err(MapCreationError::CreateFailed(errno()))
		}
		else
		{
			unreachable_code(format_args!("Unexpected result `{}` from bpf(BPF_MAP_CREATE)", result))
		}
	}
}