forked from microsoft/WSL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
4220 lines (3176 loc) · 113 KB
/
main.cpp
File metadata and controls
4220 lines (3176 loc) · 113 KB
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
main.cpp
Abstract:
This file contains the entrypoint of the WSL init implementation.
--*/
#include <sys/mount.h>
#include <sys/signalfd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysinfo.h>
#include <sys/sysmacros.h>
#include <sys/reboot.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <net/if.h>
#include <net/route.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/audit.h> /* Definition of AUDIT_* constants */
#include <linux/if_tun.h>
#include <linux/loop.h>
#include <linux/net.h>
#include <linux/random.h>
#include <linux/vm_sockets.h>
#include <linux/filter.h>
#include <linux/seccomp.h>
#include <linux/sock_diag.h>
#include <sys/utsname.h>
#include <linux/netlink.h>
#include <dirent.h>
#include <errno.h>
#include <limits.h>
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <utmp.h>
#include <assert.h>
#include "configfile.h"
#include "lxfsshares.h"
#include "common.h"
#include "util.h"
#include "seccomp_defs.h"
#include "mountutilcpp.h"
#include "message.h"
#include "binfmt.h"
#include "address.h"
#include "SocketChannel.h"
#define BSDTAR_PATH "/usr/bin/bsdtar"
#define BINFMT_REGISTER_STRING ":" LX_INIT_BINFMT_NAME ":M::MZ::" LX_INIT_PATH ":FP\n"
#define BINFMT_PATH PROCFS_PATH "/sys/fs/binfmt_misc"
#define CHRONY_CONF_PATH ETC_PATH "/chrony.conf"
#define CHRONYD_PATH "/sbin/chronyd"
#define CROSS_DISTRO_SHARE_PATH "/mnt/wsl"
#define DEVFS_PATH "/dev"
#define DEVNULL_PATH DEVFS_PATH "/null"
#define DHCLIENT_CONF_PATH "/dhclient.conf"
#define DHCLIENT_PATH "/usr/sbin/dhclient"
#define DISTRO_PATH "/distro"
#define ETC_PATH "/etc"
#define GPU_SHARE_PREFIX "/gpu_"
#define GPU_SHARE_DRIVERS GPU_SHARE_PREFIX LXSS_GPU_DRIVERS_SHARE
#define GPU_SHARE_LIB GPU_SHARE_PREFIX LXSS_GPU_LIB_SHARE
#define GPU_SHARE_LIB_INBOX GPU_SHARE_LIB "_inbox"
#define GPU_SHARE_LIB_PACKAGED GPU_SHARE_LIB "_packaged"
#define KERNEL_MODULES_PATH "/lib/modules"
#define KERNEL_MODULES_VHD_PATH "/modules"
#define KERNEL_MODULES_OVERLAY "/modules_overlay"
#define MODPROBE_PATH "/sbin/modprobe"
#define PROCFS_PATH "/proc"
#define RESOLV_CONF_FILE "resolv.conf"
#define RESOLV_CONF_PATH ETC_PATH "/" RESOLV_CONF_FILE
#define RECLAIM_PATH "/sys/fs/cgroup/memory.reclaim"
#define SCSI_DEVICE_PATH "/sys/bus/scsi/devices"
#define SCSI_DEVICE_NAME_PREFIX "0:0:0:"
#define SCSI_DEVICE_PREFIX SCSI_DEVICE_PATH "/" SCSI_DEVICE_NAME_PREFIX
#define SYSFS_PATH "/sys"
#define SYSTEM_DISTRO_PATH "/system"
#define SYSTEM_DISTRO_VHD_PATH "/systemvhd"
#define WSLG_PATH "/wslg"
#define syscall_arg(_n) (offsetof(struct seccomp_data, args[_n]))
#define syscall_nr (offsetof(struct seccomp_data, nr))
#define syscall_arch (offsetof(struct seccomp_data, arch))
constexpr auto c_trueString = "1";
struct VmConfiguration
{
bool EnableGpuSupport = false;
bool EnableGuiApps = false;
bool EnableInboxGpuLibs = false;
bool EnableSafeMode = false;
bool EnableSystemDistro = false;
bool EnableCrashDumpCollection = false;
std::string KernelModulesPath;
LX_MINI_INIT_NETWORKING_MODE NetworkingMode = LxMiniInitNetworkingModeNone;
};
int g_LogFd = STDERR_FILENO;
int g_TelemetryFd = -1;
std::optional<bool> g_EnableSocketLogging;
int Chroot(const char* Target);
void ConfigureMemoryReduction(int PageReportingOrder, LX_MINI_INIT_MEMORY_RECLAIM_MODE Mode);
void CreateSwap(unsigned int Lun);
int CreateTempDirectory(const char* ParentPath, std::string& Path);
int DetachScsiDisk(unsigned int Lun);
int EjectScsi(unsigned int Lun);
int EnableInterface(int Socket, const char* Name);
int ExportToSocket(const char* Source, int Socket, int ErrorSocket, unsigned int flags);
int FormatDevice(unsigned int Lun);
std::string GetLunDeviceName(unsigned int Lun);
std::string GetLunDevicePath(unsigned int Lun);
int GetDiskPartitionIndex(const char* DiskPath, const char* PartitionName);
std::string GetMountTarget(const char* Name);
long long int GetUserCpuTime(void);
ssize_t GetMemoryInUse(void);
int ImportFromSocket(const char* Destination, int Socket, int ErrorSocket, unsigned int Flags);
int Initialize(const char* Hostname);
void InjectEntropy(gsl::span<gsl::byte> EntropyBuffer);
void LaunchInit(
int SocketFd,
const char* Target,
bool EnableGuiApps,
const VmConfiguration& Config,
const char* VmId = nullptr,
const char* DistributionName = nullptr,
const char* SharedMemoryRoot = nullptr,
const char* InstallPath = nullptr,
const char* UserProfile = nullptr,
std::optional<pid_t> DistroInitPid = {});
void LaunchSystemDistro(
int SocketFd,
const char* Target,
const VmConfiguration& Config,
const char* VmId,
const char* DistributionName,
const char* SharedMemoryRoot,
const char* InstallPath,
const char* UserProfile,
pid_t DistroInitPid);
std::map<unsigned long, std::string> ListDiskPartitions(const std::string& DeviceName, std::optional<unsigned long> WaitForIndex = {});
std::vector<unsigned int> ListScsiDisks();
void LogException(const char* Message, const char* Description) noexcept;
int MountDevice(LX_MINI_INIT_MOUNT_DEVICE_TYPE DeviceType, unsigned int DeviceId, const char* Target, const char* FsType, unsigned int Flags, const char* Options);
int MountSystemDistro(LX_MINI_INIT_MOUNT_DEVICE_TYPE DeviceType, unsigned int DeviceId);
int MountInit(const char* Target);
int MountPlan9(const char* Name, const char* Target, bool ReadOnly, std::optional<int> BufferSize = {});
int ProcessMessage(wsl::shared::SocketChannel& channel, LX_MESSAGE_TYPE Type, gsl::span<gsl::byte> Buffer, VmConfiguration& Config);
wil::unique_fd RegisterSeccompHook();
int ReportMountStatus(wsl::shared::SocketChannel& Channel, int Result, LX_MINI_MOUNT_STEP Step);
int SendCapabilities(wsl::shared::SocketChannel& Channel);
int SetCloseOnExec(int Fd, bool Enable);
int SetEphemeralPortRange(uint16_t Start, uint16_t End);
void StartDebugShell();
int StartDhcpClient(int DhcpTimeout);
int StartGuestNetworkService(int GnsFd, wil::unique_fd&& DnsTunnelingFd, uint32_t DnsTunnelingIpAddress);
void StartPortTracker(LX_MINI_INIT_PORT_TRACKER_TYPE Type);
void StartTimeSyncAgent(void);
void WaitForBlockDevice(const char* Path);
int WaitForChild(pid_t Pid, const char* Name);
int Chroot(const char* Target)
/*++
Routine Description:
This routine changes the root directory of the calling process to the specified
path.
Arguments:
Target - Supplies the path to chroot to.
Return Value:
0 on success, -1 on failure.
--*/
{
//
// Set the current working directory to the distro mount point, move the
// mount to the root, and chroot.
//
if (chdir(Target) < 0)
{
LOG_ERROR("chdir({}) failed {}", Target, errno);
return -1;
}
if (mount(".", "/", nullptr, MS_MOVE, nullptr) < 0)
{
LOG_ERROR("mount(MS_MOVE) failed {}", errno);
return -1;
}
if (chroot(".") < 0)
{
LOG_ERROR("chroot failed {}", errno);
return -1;
}
return 0;
}
void ConfigureMemoryReduction(int PageReportingOrder, LX_MINI_INIT_MEMORY_RECLAIM_MODE Mode)
/*++
Routine Description:
This routine sets the page reporting order.
Arguments:
PageReportingOrder - Supplies the page reporting order. This value determines the size of cold discard hints
by using the equation: 2^PageReportingOrder * PAGE_SIZE
Example: 2^9 * 4096 = 2MB
Mode - Supplies the memory reclaim mode.
Return Value:
None.
--*/
try
{
//
// Ensure the value falls within a reasonable range (single page to 2MB).
//
if (PageReportingOrder < 0 || PageReportingOrder > 9)
{
LOG_WARNING("Invalid page_reporting_order {}", PageReportingOrder);
PageReportingOrder = 0;
}
else
{
WriteToFile("/sys/module/page_reporting/parameters/page_reporting_order", std::to_string(PageReportingOrder).c_str());
}
//
// Create a worker thread to periodically check if the VM is idle and performs memory compaction.
// This ensures that the maximum number of pages can be discarded to the host.
//
// N.B. Compaction is not needed if page reporting order is set to single page mode.
//
if (PageReportingOrder == 0 && Mode == LxMiniInitMemoryReclaimModeDisabled)
{
return;
}
std::thread([PageReportingOrder = PageReportingOrder, Mode = Mode]() mutable {
try
{
//
// Set the thread's scheduling policy to idle.
//
sched_param Parameter{};
Parameter.sched_priority = 0;
THROW_LAST_ERROR_IF(pthread_setschedparam(pthread_self(), SCHED_IDLE, &Parameter) < 0);
//
// Periodically check if the machine is idle by querying procfs for CPU usage.
// Memory compaction will occur if both of the following conditions are true:
// 1. The CPU time since the last check is greater than the idle threshold.
// 2. The current CPU usage is below the idle threshold. This is measured by taking two readings one second apart.
//
double MemoryLow = 1024 * 1024 * 1024;
double MemoryHigh = 1.1 * 1024.0 * 1024.0 * 1024.0;
const int IdleThreshold = get_nprocs(); // Change math to adjust if sysconf(_SC_CLK_TCK) != 100? Is 1%
long long int Start, Stop = 0;
auto constexpr SleepDuration = std::chrono::seconds(30);
size_t ReclaimIndex = 0;
long long int const ReclaimThreshold = (get_nprocs() * sysconf(_SC_CLK_TCK) * SleepDuration / std::chrono::seconds(1)) / 200; // 0.5%
long long int ReclaimWindow[20] = {}; // 10 minutes
long long int ReclaimWindowLength = COUNT_OF(ReclaimWindow);
bool ReclaimIdling;
//
// Fall back to drop cache if the required cgroup path is not present.
//
if (Mode == LxMiniInitMemoryReclaimModeGradual && access(RECLAIM_PATH, W_OK) < 0)
{
LOG_WARNING("access({}, W_OK) failed {}, falling back to autoMemoryReclaim = dropcache", RECLAIM_PATH, errno);
Mode = LxMiniInitMemoryReclaimModeDropCache;
}
if (Mode == LxMiniInitMemoryReclaimModeGradual)
{
static_assert(COUNT_OF(ReclaimWindow) >= 6);
ReclaimWindowLength = 6; // Set to 3 minutes.
}
for (auto i = 1; i < ReclaimWindowLength; i++)
{
ReclaimWindow[i] = LLONG_MIN;
}
std::this_thread::sleep_for(SleepDuration);
for (;;)
{
auto const Target = std::chrono::steady_clock::now() + SleepDuration;
Start = GetUserCpuTime();
THROW_LAST_ERROR_IF(Start == -1);
if (Mode != LxMiniInitMemoryReclaimModeDisabled)
{
//
// Ensure that utilization is below 0.5% from the last 30 seconds, and last n minutes, of usage.
//
size_t const LastIndex = (ReclaimIndex + 1) % ReclaimWindowLength;
if ((ReclaimWindow[LastIndex] > Start - ReclaimThreshold * (ReclaimWindowLength + 1)) &&
(ReclaimWindow[ReclaimIndex] > Start - ReclaimThreshold))
{
if (Mode == LxMiniInitMemoryReclaimModeGradual)
{
double MemorySize = GetMemoryInUse();
THROW_LAST_ERROR_IF(MemorySize < 0);
if (MemorySize > MemoryHigh)
{
ReclaimIdling = false;
}
if (!ReclaimIdling && MemorySize > MemoryLow)
{
double MemoryTargetSize = MemorySize * 0.97;
std::string MemoryToFree = std::to_string(size_t(MemorySize - MemoryTargetSize));
// EAGAIN Means that it attempted, but was unable to evict sufficient pages.
THROW_LAST_ERROR_IF(WriteToFile(RECLAIM_PATH, MemoryToFree.c_str()) < 0 && errno != EAGAIN);
if (MemoryTargetSize < MemoryLow)
{
ReclaimIdling = true;
}
}
}
else if (!ReclaimIdling)
{
ReclaimIdling = true;
THROW_LAST_ERROR_IF(WriteToFile(PROCFS_PATH "/sys/vm/drop_caches", "1\n") < 0);
}
}
else
{
ReclaimIdling = false;
}
ReclaimIndex = LastIndex;
ReclaimWindow[ReclaimIndex] = Start;
}
//
// Perform memory compaction if the VM is idle.
//
// N.B. Memory compaction is not needed if the page reporting order is set to single page (0).
//
if (PageReportingOrder != 0 && (Start - Stop) > IdleThreshold)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
const long long int Stop = GetUserCpuTime();
THROW_LAST_ERROR_IF(Stop == -1);
if ((Stop - Start) < IdleThreshold)
{
THROW_LAST_ERROR_IF(WriteToFile(PROCFS_PATH "/sys/vm/compact_memory", "1\n") < 0);
}
}
std::this_thread::sleep_until(Target);
}
}
CATCH_LOG()
}).detach();
}
CATCH_LOG()
wil::unique_fd CreateNetlinkSocket(void)
/*++
Routine Description:
Create and bind a netlink socket.
Arguments:
None.
Return Value:
The socket file descriptor or < 0 on failure.
--*/
{
wil::unique_fd Fd{socket(AF_NETLINK, SOCK_RAW, NETLINK_SOCK_DIAG)};
if (!Fd)
{
LOG_ERROR("socket failed {}", errno);
return {};
}
struct sockaddr_nl Address;
Address.nl_family = AF_NETLINK;
if (bind(Fd.get(), (struct sockaddr*)&Address, sizeof(Address)) < 0)
{
LOG_ERROR("bind failed {}", errno);
return {};
}
return Fd;
}
void CreateSwap(unsigned int Lun)
/*++
Routine Description:
This routine sets up a swap area on the specified SCSI device.
Arguments:
Lun - Supplies the LUN number of the SCSI device.
Return Value:
None.
--*/
{
//
// Create the swap file asynchronously using the mkswap and swapon utilities in the system distro.
//
// N.B. This is done because creating the swap file can take some time and
// the swap file does not need to be available immediately.
//
UtilCreateChildProcess("CreateSwap", [Lun]() {
std::string DevicePath = GetLunDevicePath(Lun);
WaitForBlockDevice(DevicePath.c_str());
std::string CommandLine = std::format("/usr/sbin/mkswap '{}'", DevicePath);
THROW_LAST_ERROR_IF(UtilExecCommandLine(CommandLine.c_str(), nullptr) < 0);
CommandLine = std::format("/usr/sbin/swapon '{}'", DevicePath);
UtilExecCommandLine(CommandLine.c_str(), nullptr);
});
}
int CreateTempDirectory(const char* ParentPath, std::string& Path)
/*++
Routine Description:
This routine creates a unique directory under the specified parent path.
Arguments:
ParentPath - Supplies the path of the parent directory.
Path - Supplies a buffer to receive the path of the child directory that was
created.
Return Value:
0 on success, -1 on failure.
--*/
{
if (ParentPath)
{
Path = ParentPath;
}
//
// Generate a random name for the directory.
//
// N.B. mkdtemp requires a template string that ends in "XXXXXX".
//
Path += "/wslXXXXXX";
if (mkdtemp(Path.data()) == NULL)
{
LOG_ERROR("mkdtemp({}) failed {}", Path.c_str(), errno);
return -1;
}
return 0;
}
dev_t GetBlockDeviceNumber(const std::string& BlockDeviceName)
/*++
Routine Description:
This method return the device number of a given block device.
Arguments:
BlockDeviceName - Supplies the name of the block device.
Return Value:
The device block number. Throws on error.
--*/
{
std::string content = wsl::shared::string::ReadFile<char, char>(std::format("/sys/block/{}/dev", BlockDeviceName).c_str());
auto separator = content.find(':');
if (separator == 0 || separator - 1 >= content.size() || separator == std::string::npos)
{
LOG_ERROR("Failed to parse device number '{}' for device '{}'", content.c_str(), BlockDeviceName.c_str());
THROW_ERRNO(EINVAL);
}
try
{
return makedev(std::strtoul(content.c_str(), nullptr, 10), std::strtoul(content.substr(separator + 1).c_str(), nullptr, 10));
}
catch (...)
{
LOG_ERROR("Failed to parse device number '{}' for device '{}'", content.c_str(), BlockDeviceName.c_str());
THROW_ERRNO(EINVAL);
}
}
int DetachScsiDisk(unsigned int Lun)
/*++
Routine Description:
This routine detaches a SCSI disk.
Arguments:
Lun - Supplies the LUN of the disk to detach.
Return Value:
0 on success, -1 on failure.
--*/
{
auto deviceName = GetLunDeviceName(Lun);
try
{
auto deviceNumbers = std::set<dev_t>{GetBlockDeviceNumber(deviceName)};
for (const auto& e : ListDiskPartitions(deviceName.c_str()))
{
deviceNumbers.insert(GetBlockDeviceNumber(std::format("{}/{}", deviceName, e.second)));
}
mountutil::MountEnum mounts;
while (mounts.Next())
{
if (deviceNumbers.find(mounts.Current().Device) != deviceNumbers.end())
{
if (umount(mounts.Current().MountPoint) < 0)
{
LOG_ERROR("Failed to unmount '{}', {}", mounts.Current().MountPoint, errno);
}
}
}
}
CATCH_LOG();
// Flush the block device.
std::string DevicePath = DEVFS_PATH + std::string("/") + deviceName;
wil::unique_fd BlockDevice{open(DevicePath.c_str(), O_RDONLY)};
int Result = ioctl(BlockDevice.get(), BLKFLSBUF);
if (Result < 0)
{
LOG_ERROR("Failed to flush block device: '{}', {}", DevicePath.c_str(), errno);
return Result;
}
// Close the device before trying to delete it.
BlockDevice.reset();
// Remove the block device.
return WriteToFile(std::format("/sys/block/{}/device/delete", deviceName).c_str(), "1");
}
int DetectFilesystem(const char* BlockDevice, std::string& Output)
/*++
Routine Description:
This routine performs file system detect on a block device.
Arguments:
BlockDevice - Path to the block device.
Output - Detected filesystem, if any.
Return Value:
0 on success, < 0 on failure.
--*/
try
{
//
// Wait for the block device to be available.
//
wsl::shared::retry::RetryWithTimeout<void>(
[&]() { THROW_LAST_ERROR_IF(!wil::unique_fd{open(BlockDevice, O_RDONLY)}); },
c_defaultRetryPeriod,
c_defaultRetryTimeout,
[]() {
auto err = wil::ResultFromCaughtException();
return err == ENOENT || err == ENXIO;
});
auto CommandLine = std::format("/usr/sbin/blkid '{}' -p -s TYPE -o value -u filesystem", BlockDevice);
if (UtilExecCommandLine(CommandLine.c_str(), &Output) < 0)
{
return -1;
}
while (!Output.empty() && Output.back() == '\n')
{
Output.pop_back();
}
LOG_INFO("Detected {} filesystem for device: {}", Output, BlockDevice);
return 0;
}
CATCH_RETURN_ERRNO()
int EjectScsi(unsigned int Lun)
/*++
Routine Description:
This routine ejects the specified SCSI device.
Arguments:
Lun - Supplies the LUN of the SCSI device to eject.
Return Value:
0 on success, -1 on failure.
--*/
try
{
//
// Perform a sync to ensure all writes are flushed.
//
sync();
//
// Write "1" to /sys/bus/scsi/devices/0:0:<controller>:<lun>/delete to eject the SCSI device.
//
std::string Path = std::format("{}{}/delete", SCSI_DEVICE_PREFIX, Lun);
if (WriteToFile(Path.c_str(), c_trueString) < 0)
{
return -1;
}
return 0;
}
CATCH_RETURN_ERRNO()
void EnableCrashDumpCollection()
{
if (symlink("/init", "/" LX_INIT_WSL_CAPTURE_CRASH) < 0)
{
LOG_ERROR("symlink({}, {}) failed {}", "/init", "/" LX_INIT_WSL_CAPTURE_CRASH, errno);
return;
}
// If the first character is a pipe, then the kernel will interperet this path as a command.
constexpr auto core_pattern = "|/" LX_INIT_WSL_CAPTURE_CRASH " %t %E %p %s";
WriteToFile("/proc/sys/kernel/core_pattern", core_pattern);
}
int EnableInterface(int Socket, const char* Name)
/*++
Routine Description:
This routine marks the specified interface as up / running.
Arguments:
Socket - Supplies a socket file descriptor.
Name - Supplies the name of an interface.
Return Value:
0 on success, -1 on failure.
--*/
{
ifreq InterfaceRequest{};
strncpy(InterfaceRequest.ifr_name, Name, IFNAMSIZ - 1);
if (ioctl(Socket, SIOCGIFFLAGS, &InterfaceRequest) < 0)
{
LOG_ERROR("SIOCGIFFLAGS failed {}", errno);
return -1;
}
InterfaceRequest.ifr_flags |= (IFF_UP | IFF_RUNNING);
if (ioctl(Socket, SIOCSIFFLAGS, &InterfaceRequest) < 0)
{
LOG_ERROR("SIOCSIFFLAGS failed {}", errno);
return -1;
}
return 0;
}
int ExportToSocket(const char* Source, int Socket, int ErrorSocket, unsigned int Flags)
/*++
Routine Description:
This routine uses bsdtar to export a source directory in tar format via a
socket.
Arguments:
Source - Supplies the path to export.
Socket - Supplies the socket to write to.
Flags - Additional compression flags.
Return Value:
0 on success, -1 on failure.
--*/
{
//
// Create a child process running bsdtar with the socket set to stdout.
//
int ChildPid = UtilCreateChildProcess("ExportDistro", [Source, TarFd = Socket, ErrorSocket = ErrorSocket, Flags = Flags]() {
THROW_LAST_ERROR_IF(TEMP_FAILURE_RETRY(dup2(TarFd, STDOUT_FILENO)) < 0);
THROW_LAST_ERROR_IF(TEMP_FAILURE_RETRY(dup2(ErrorSocket, STDERR_FILENO)) < 0);
std::string compressionArguments;
if (WI_IsFlagSet(Flags, LxMiniInitMessageFlagExportCompressGzip))
{
assert(!WI_IsFlagSet(Flags, LxMiniInitMessageFlagExportCompressXzip));
compressionArguments = "-cz";
}
else if (WI_IsFlagSet(Flags, LxMiniInitMessageFlagExportCompressXzip))
{
compressionArguments = "-cJ";
}
else
{
compressionArguments = "-c";
}
if (WI_IsFlagSet(Flags, LxMiniInitMessageFlagVerbose))
{
compressionArguments += "v";
}
const char* arguments[] = {
BSDTAR_PATH,
"-C",
Source,
compressionArguments.c_str(),
"--one-file-system",
"--xattrs",
"--numeric-owner",
"-f",
"-",
".",
nullptr};
execv(BSDTAR_PATH, const_cast<char**>(arguments));
LOG_ERROR("execl failed, {}", errno);
});
if (ChildPid < 0)
{
return -1;
}
//
// Wait for the child to exit and shut down the socket.
//
const int Result = WaitForChild(ChildPid, BSDTAR_PATH);
if (shutdown(Socket, SHUT_WR) < 0)
{
LOG_ERROR("shutdown failed {}", errno);
}
return Result;
}
int FormatDevice(unsigned int Lun)
/*++
Routine Description:
This routine formats the specified SCSI device with the ext4 file system.
N.B. The group size was chosen based on the best practices for Linux VHDs:
https://docs.microsoft.com/en-us/windows-server/virtualization/hyper-v/best-practices-for-running-linux-on-hyper-v
Arguments:
Lun - Supplies the LUN number of the SCSI device.
Return Value:
0 on success, < 0 on failure.
--*/
try
{
std::string DevicePath = GetLunDevicePath(Lun);
WaitForBlockDevice(DevicePath.c_str());
std::string CommandLine = std::format("/usr/sbin/mkfs.ext4 -G 4096 '{}'", DevicePath);
if (UtilExecCommandLine(CommandLine.c_str(), nullptr) < 0)
{
return -1;
}
return 0;
}
CATCH_RETURN_ERRNO()
std::string GetLunDeviceName(unsigned int Lun)
/*++
Routine Description:
This routine returns the device name(sdX) for the specified SCSI device.
Arguments:
Lun - Supplies a SCSI LUN.
Return Value:
The device name (throws on error).
--*/
{
//
// Construct a path to the block directory which contains a single directory
// entry with the name of the device where the vhd is attached, for example: sda.
//
// N.B. A retry loop is needed because there is a delay between when the vhd
// is hot-added from the host, and when the sysfs directory is
// available in the guest.
//
std::string Path = std::format("{}{}/block", SCSI_DEVICE_PREFIX, Lun);
return wsl::shared::retry::RetryWithTimeout<std::string>(
[&]() {
wil::unique_dir Dir{opendir(Path.c_str())};
THROW_LAST_ERROR_IF(!Dir);
//
// Find the first directory entry that does not begin with a dot.
//
dirent64* Entry{};
while ((Entry = readdir64(Dir.get())) != nullptr)
{
if (Entry->d_name[0] != '.')
{
return std::string(Entry->d_name);
}
}
THROW_ERRNO(ENXIO);
},
c_defaultRetryPeriod,
c_defaultRetryTimeout);
}
std::string GetLunDevicePath(unsigned int Lun)
/*++
Routine Description:
This routine returns the device path for the specified SCSI device.
Arguments:
Lun - Supplies a SCSI LUN.
Return Value:
The device path;