-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathkernel.go
2159 lines (1913 loc) · 66.6 KB
/
kernel.go
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 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package kernel provides an emulation of the Linux kernel.
//
// See README.md for a detailed overview.
//
// Lock order (outermost locks must be taken first):
//
// Kernel.extMu
// TTY.mu
// timekeeperTcpipTimer.mu
// ThreadGroup.timerMu
// Locks acquired by ktime.Timer methods
// TaskSet.mu
// SignalHandlers.mu
// Task.mu
// runningTasksMu
//
// Locking SignalHandlers.mu in multiple SignalHandlers requires locking
// TaskSet.mu exclusively first. Locking Task.mu in multiple Tasks at the same
// time requires locking all of their signal mutexes first.
package kernel
import (
"errors"
"fmt"
"io"
"path/filepath"
"time"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/atomicbitops"
"gvisor.dev/gvisor/pkg/cleanup"
"gvisor.dev/gvisor/pkg/context"
"gvisor.dev/gvisor/pkg/cpuid"
"gvisor.dev/gvisor/pkg/devutil"
"gvisor.dev/gvisor/pkg/errors/linuxerr"
"gvisor.dev/gvisor/pkg/eventchannel"
"gvisor.dev/gvisor/pkg/fd"
"gvisor.dev/gvisor/pkg/fspath"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/pkg/refs"
"gvisor.dev/gvisor/pkg/sentry/arch"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/nsfs"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/pipefs"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/sockfs"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/timerfd"
"gvisor.dev/gvisor/pkg/sentry/fsimpl/tmpfs"
"gvisor.dev/gvisor/pkg/sentry/hostcpu"
"gvisor.dev/gvisor/pkg/sentry/inet"
"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
"gvisor.dev/gvisor/pkg/sentry/kernel/futex"
"gvisor.dev/gvisor/pkg/sentry/kernel/ipc"
"gvisor.dev/gvisor/pkg/sentry/kernel/sched"
"gvisor.dev/gvisor/pkg/sentry/ktime"
"gvisor.dev/gvisor/pkg/sentry/limits"
"gvisor.dev/gvisor/pkg/sentry/loader"
"gvisor.dev/gvisor/pkg/sentry/mm"
"gvisor.dev/gvisor/pkg/sentry/pgalloc"
"gvisor.dev/gvisor/pkg/sentry/platform"
"gvisor.dev/gvisor/pkg/sentry/socket/netlink/port"
"gvisor.dev/gvisor/pkg/sentry/socket/unix/transport"
sentrytime "gvisor.dev/gvisor/pkg/sentry/time"
"gvisor.dev/gvisor/pkg/sentry/unimpl"
uspb "gvisor.dev/gvisor/pkg/sentry/unimpl/unimplemented_syscall_go_proto"
"gvisor.dev/gvisor/pkg/sentry/uniqueid"
"gvisor.dev/gvisor/pkg/sentry/vfs"
"gvisor.dev/gvisor/pkg/state"
"gvisor.dev/gvisor/pkg/sync"
"gvisor.dev/gvisor/pkg/tcpip"
)
// IOUringEnabled is set to true when IO_URING is enabled. Added as a global to
// allow easy access everywhere.
var IOUringEnabled = false
// UserCounters is a set of user counters.
//
// +stateify savable
type UserCounters struct {
uid auth.KUID
rlimitNProc atomicbitops.Uint64
}
// incRLimitNProc increments the rlimitNProc counter.
func (uc *UserCounters) incRLimitNProc(ctx context.Context) error {
lim := limits.FromContext(ctx).Get(limits.ProcessCount)
creds := auth.CredentialsFromContext(ctx)
nproc := uc.rlimitNProc.Add(1)
if nproc > lim.Cur &&
!creds.HasCapability(linux.CAP_SYS_ADMIN) &&
!creds.HasCapability(linux.CAP_SYS_RESOURCE) {
uc.rlimitNProc.Add(^uint64(0))
return linuxerr.EAGAIN
}
return nil
}
// decRLimitNProc decrements the rlimitNProc counter.
func (uc *UserCounters) decRLimitNProc() {
uc.rlimitNProc.Add(^uint64(0))
}
// CgroupMount contains the cgroup mount. These mounts are created for the root
// container by default and are stored in the kernel.
//
// +stateify savable
type CgroupMount struct {
Fs *vfs.Filesystem
Root *vfs.Dentry
Mount *vfs.Mount
}
// Kernel represents an emulated Linux kernel. It must be initialized by calling
// Init() or LoadFrom().
//
// +stateify savable
type Kernel struct {
// extMu serializes external changes to the Kernel with calls to
// Kernel.SaveTo. (Kernel.SaveTo requires that the state of the Kernel
// remains frozen for the duration of the call; it requires that the Kernel
// is paused as a precondition, which ensures that none of the tasks
// running within the Kernel can affect its state, but extMu is required to
// ensure that concurrent users of the Kernel *outside* the Kernel's
// control cannot affect its state by calling e.g.
// Kernel.SendExternalSignal.)
extMu sync.Mutex `state:"nosave"`
// started is true if Start has been called. Unless otherwise specified,
// all Kernel fields become immutable once started becomes true.
started bool `state:"nosave"`
// All of the following fields are immutable unless otherwise specified.
// Platform is the platform that is used to execute tasks in the created
// Kernel.
platform.Platform `state:"nosave"`
// mf provides application memory.
mf *pgalloc.MemoryFile `state:"nosave"`
// See InitKernelArgs for the meaning of these fields.
featureSet cpuid.FeatureSet
timekeeper *Timekeeper
tasks *TaskSet
rootUserNamespace *auth.UserNamespace
rootNetworkNamespace *inet.Namespace
applicationCores uint
useHostCores bool
extraAuxv []arch.AuxEntry
vdso *loader.VDSO
vdsoParams *VDSOParamPage
rootUTSNamespace *UTSNamespace
rootIPCNamespace *IPCNamespace
// futexes is the "root" futex.Manager, from which all others are forked.
// This is necessary to ensure that shared futexes are coherent across all
// tasks, including those created by CreateProcess.
futexes *futex.Manager
// globalInit is the thread group whose leader has ID 1 in the root PID
// namespace. globalInit is stored separately so that it is accessible even
// after all tasks in the thread group have exited, such that ID 1 is no
// longer mapped.
//
// globalInit is mutable until it is assigned by the first successful call
// to CreateProcess, and is protected by extMu.
globalInit *ThreadGroup
// syslog is the kernel log.
syslog syslog
runningTasksMu runningTasksMutex `state:"nosave"`
// runningTasks is the total count of tasks currently in
// TaskGoroutineRunningSys or TaskGoroutineRunningApp. i.e., they are
// not blocked or stopped.
//
// runningTasks must be accessed atomically. Increments from 0 to 1 are
// further protected by runningTasksMu (see incRunningTasks).
runningTasks atomicbitops.Int64
// runningTasksCond is signaled when runningTasks is incremented from 0 to 1.
//
// Invariant: runningTasksCond.L == &runningTasksMu.
runningTasksCond sync.Cond `state:"nosave"`
// cpuClockTickTimer drives increments of cpuClock.
cpuClockTickTimer *time.Timer `state:"nosave"`
// cpuClockTickerRunning is true if the goroutine that increments cpuClock is
// running, and false if it is blocked in runningTasksCond.Wait() or if it
// never started.
//
// cpuClockTickerRunning is protected by runningTasksMu.
cpuClockTickerRunning bool
// cpuClockTickerWakeCh is sent to to wake the goroutine that increments
// cpuClock if it's sleeping between ticks.
cpuClockTickerWakeCh chan struct{} `state:"nosave"`
// cpuClockTickerStopCond is broadcast when cpuClockTickerRunning transitions
// from true to false.
//
// Invariant: cpuClockTickerStopCond.L == &runningTasksMu.
cpuClockTickerStopCond sync.Cond `state:"nosave"`
// cpuClock is a coarse monotonic clock that is advanced by the CPU clock
// ticker and thus approximates wall time when tasks are running (but is
// strictly slower due to CPU clock ticker goroutine wakeup latency). This
// does not use ktime.SyntheticClock since this clock currently does not
// need to support timers.
cpuClock atomicbitops.Int64
// uniqueID is used to generate unique identifiers.
//
// uniqueID is mutable, and is accessed using atomic memory operations.
uniqueID atomicbitops.Uint64
// nextInotifyCookie is a monotonically increasing counter used for
// generating unique inotify event cookies.
//
// nextInotifyCookie is mutable.
nextInotifyCookie atomicbitops.Uint32
// netlinkPorts manages allocation of netlink socket port IDs.
netlinkPorts *port.Manager
// saveStatus is nil if the sandbox has not been saved, errSaved or
// errAutoSaved if it has been saved successfully, or the error causing the
// sandbox to exit during save.
// It is protected by extMu.
saveStatus error `state:"nosave"`
// danglingEndpoints is used to save / restore tcpip.DanglingEndpoints.
danglingEndpoints struct{} `state:".([]tcpip.Endpoint)"`
// sockets records all network sockets in the system. Protected by extMu.
sockets map[*vfs.FileDescription]*SocketRecord
// nextSocketRecord is the next entry number to use in sockets. Protected
// by extMu.
nextSocketRecord uint64
// unimplementedSyscallEmitterOnce is used in the initialization of
// unimplementedSyscallEmitter.
unimplementedSyscallEmitterOnce sync.Once `state:"nosave"`
// unimplementedSyscallEmitter is used to emit unimplemented syscall
// events. This is initialized lazily on the first unimplemented
// syscall.
unimplementedSyscallEmitter eventchannel.Emitter `state:"nosave"`
// SpecialOpts contains special kernel options.
SpecialOpts
// vfs keeps the filesystem state used across the kernel.
vfs vfs.VirtualFilesystem
// hostMount is the Mount used for file descriptors that were imported
// from the host.
hostMount *vfs.Mount
// pipeMount is the Mount used for pipes created by the pipe() and pipe2()
// syscalls (as opposed to named pipes created by mknod()).
pipeMount *vfs.Mount
// nsfsMount is the Mount used for namespaces.
nsfsMount *vfs.Mount
// shmMount is the Mount used for anonymous files created by the
// memfd_create() syscalls. It is analogous to Linux's shm_mnt.
shmMount *vfs.Mount
// socketMount is the Mount used for sockets created by the socket() and
// socketpair() syscalls. There are several cases where a socket dentry will
// not be contained in socketMount:
// 1. Socket files created by mknod()
// 2. Socket fds imported from the host (Kernel.hostMount is used for these)
// 3. Socket files created by binding Unix sockets to a file path
socketMount *vfs.Mount
// sysVShmDevID is the device number used by SysV shm segments. In Linux,
// SysV shm uses shmem_file_setup() and thus uses shm_mnt's device number.
// In gVisor, the shm implementation does not use shmMount, extracting
// shmMount's device number is inconvenient, applications accept a
// different device number in practice, and using a distinct device number
// avoids the possibility of inode number collisions due to the hack
// described in shm.Shm.InodeID().
sysVShmDevID uint32
// If set to true, report address space activation waits as if the task is in
// external wait so that the watchdog doesn't report the task stuck.
SleepForAddressSpaceActivation bool
// Exceptions to YAMA ptrace restrictions. Each key-value pair represents a
// tracee-tracer relationship. The key is a process (technically, the thread
// group leader) that can be traced by any thread that is a descendant of the
// value. If the value is nil, then anyone can trace the process represented by
// the key.
//
// ptraceExceptions is protected by the TaskSet mutex.
ptraceExceptions map[*Task]*Task
// YAMAPtraceScope is the current level of YAMA ptrace restrictions.
YAMAPtraceScope atomicbitops.Int32
// cgroupRegistry contains the set of active cgroup controllers on the
// system. It is controller by cgroupfs. Nil if cgroupfs is unavailable on
// the system.
cgroupRegistry *CgroupRegistry
// cgroupMountsMap maps the cgroup controller names to the cgroup mounts
// created for the root container. These mounts are then bind mounted
// for other application containers by creating their own container
// directories.
cgroupMountsMap map[string]*CgroupMount
cgroupMountsMapMu cgroupMountsMutex `state:"nosave"`
// userCountersMap maps auth.KUID into a set of user counters.
userCountersMap map[auth.KUID]*UserCounters
userCountersMapMu userCountersMutex `state:"nosave"`
// MaxFDLimit specifies the maximum file descriptor number that can be
// used by processes.
MaxFDLimit atomicbitops.Int32
// devGofers maps containers (using its name) to its device gofer client.
devGofers map[string]*devutil.GoferClient `state:"nosave"`
devGofersMu sync.Mutex `state:"nosave"`
// containerNames store the container name based on their container ID.
// Names are preserved between save/restore session, while IDs can change.
//
// Mapping: cid -> name.
// It's protected by extMu.
containerNames map[string]string
// checkpointMu is used to protect the checkpointing related fields below.
checkpointMu sync.Mutex `state:"nosave"`
// additionalCheckpointState stores additional state that needs
// to be checkpointed. It's protected by checkpointMu.
additionalCheckpointState map[any]any
// saver implements the Saver interface, which (as of writing) supports
// asynchronous checkpointing. It's protected by checkpointMu.
saver Saver `state:"nosave"`
// CheckpointWait is used to wait for a checkpoint to complete.
CheckpointWait CheckpointWaitable
// checkpointGen aims to track the number of times the kernel has been
// successfully checkpointed. Callers of checkpoint must notify the kernel
// when checkpoint/restore are done. It's protected by checkpointMu.
checkpointGen CheckpointGeneration
// UnixSocketOpts stores configuration options for management of unix sockets.
UnixSocketOpts transport.UnixSocketOpts
}
// InitKernelArgs holds arguments to Init.
type InitKernelArgs struct {
// FeatureSet is the emulated CPU feature set.
FeatureSet cpuid.FeatureSet
// Timekeeper manages time for all tasks in the system.
Timekeeper *Timekeeper
// RootUserNamespace is the root user namespace.
RootUserNamespace *auth.UserNamespace
// RootNetworkNamespace is the root network namespace. If nil, no networking
// will be available.
RootNetworkNamespace *inet.Namespace
// ApplicationCores is the number of logical CPUs visible to sandboxed
// applications. The set of logical CPU IDs is [0, ApplicationCores); thus
// ApplicationCores is analogous to Linux's nr_cpu_ids, the index of the
// most significant bit in cpu_possible_mask + 1.
ApplicationCores uint
// If UseHostCores is true, Task.CPU() returns the task goroutine's CPU
// instead of a virtualized CPU number, and Task.CopyToCPUMask() is a
// no-op. If ApplicationCores is less than hostcpu.MaxPossibleCPU(), it
// will be overridden.
UseHostCores bool
// ExtraAuxv contains additional auxiliary vector entries that are added to
// each process by the ELF loader.
ExtraAuxv []arch.AuxEntry
// Vdso holds the VDSO and its parameter page.
Vdso *loader.VDSO
// VdsoParams is the VDSO parameter page manager.
VdsoParams *VDSOParamPage
// RootUTSNamespace is the root UTS namespace.
RootUTSNamespace *UTSNamespace
// RootIPCNamespace is the root IPC namespace.
RootIPCNamespace *IPCNamespace
// PIDNamespace is the root PID namespace.
PIDNamespace *PIDNamespace
// MaxFDLimit specifies the maximum file descriptor number that can be
// used by processes. If it is zero, the limit will be set to
// unlimited.
MaxFDLimit int32
// UnixSocketOpts contains configuration options for unix sockets.
UnixSocketOpts transport.UnixSocketOpts
}
// Init initialize the Kernel with no tasks.
//
// Callers must manually set Kernel.Platform and call Kernel.SetMemoryFile
// before calling Init.
func (k *Kernel) Init(args InitKernelArgs) error {
if args.Timekeeper == nil {
return fmt.Errorf("args.Timekeeper is nil")
}
if args.Timekeeper.clocks == nil {
return fmt.Errorf("must call Timekeeper.SetClocks() before Kernel.Init()")
}
if args.RootUserNamespace == nil {
return fmt.Errorf("args.RootUserNamespace is nil")
}
if args.ApplicationCores == 0 {
return fmt.Errorf("args.ApplicationCores is 0")
}
k.featureSet = args.FeatureSet
k.timekeeper = args.Timekeeper
k.tasks = newTaskSet(args.PIDNamespace)
k.rootUserNamespace = args.RootUserNamespace
k.rootUTSNamespace = args.RootUTSNamespace
k.rootIPCNamespace = args.RootIPCNamespace
k.rootNetworkNamespace = args.RootNetworkNamespace
if k.rootNetworkNamespace == nil {
k.rootNetworkNamespace = inet.NewRootNamespace(nil, nil, args.RootUserNamespace)
}
k.runningTasksCond.L = &k.runningTasksMu
k.cpuClockTickerWakeCh = make(chan struct{}, 1)
k.cpuClockTickerStopCond.L = &k.runningTasksMu
k.applicationCores = args.ApplicationCores
if args.UseHostCores {
k.useHostCores = true
maxCPU, err := hostcpu.MaxPossibleCPU()
if err != nil {
return fmt.Errorf("failed to get maximum CPU number: %v", err)
}
minAppCores := uint(maxCPU) + 1
if k.applicationCores < minAppCores {
log.Infof("UseHostCores enabled: increasing ApplicationCores from %d to %d", k.applicationCores, minAppCores)
k.applicationCores = minAppCores
}
}
k.extraAuxv = args.ExtraAuxv
k.vdso = args.Vdso
k.vdsoParams = args.VdsoParams
k.futexes = futex.NewManager()
k.netlinkPorts = port.New()
k.ptraceExceptions = make(map[*Task]*Task)
k.YAMAPtraceScope = atomicbitops.FromInt32(linux.YAMA_SCOPE_RELATIONAL)
k.userCountersMap = make(map[auth.KUID]*UserCounters)
if args.MaxFDLimit == 0 {
args.MaxFDLimit = MaxFdLimit
}
k.MaxFDLimit.Store(args.MaxFDLimit)
k.containerNames = make(map[string]string)
k.CheckpointWait.k = k
ctx := k.SupervisorContext()
if err := k.vfs.Init(ctx); err != nil {
return fmt.Errorf("failed to initialize VFS: %v", err)
}
err := k.rootIPCNamespace.InitPosixQueues(ctx, &k.vfs, auth.CredentialsFromContext(ctx))
if err != nil {
return fmt.Errorf("failed to create mqfs filesystem: %v", err)
}
pipeFilesystem, err := pipefs.NewFilesystem(&k.vfs)
if err != nil {
return fmt.Errorf("failed to create pipefs filesystem: %v", err)
}
defer pipeFilesystem.DecRef(ctx)
pipeMount := k.vfs.NewDisconnectedMount(pipeFilesystem, nil, &vfs.MountOptions{})
k.pipeMount = pipeMount
nsfsFilesystem, err := nsfs.NewFilesystem(&k.vfs)
if err != nil {
return fmt.Errorf("failed to create nsfs filesystem: %v", err)
}
defer nsfsFilesystem.DecRef(ctx)
k.nsfsMount = k.vfs.NewDisconnectedMount(nsfsFilesystem, nil, &vfs.MountOptions{})
k.rootNetworkNamespace.SetInode(nsfs.NewInode(ctx, k.nsfsMount, k.rootNetworkNamespace))
k.rootIPCNamespace.SetInode(nsfs.NewInode(ctx, k.nsfsMount, k.rootIPCNamespace))
k.rootUTSNamespace.SetInode(nsfs.NewInode(ctx, k.nsfsMount, k.rootUTSNamespace))
tmpfsOpts := vfs.GetFilesystemOptions{
InternalData: tmpfs.FilesystemOpts{
// See mm/shmem.c:shmem_init() => vfs_kern_mount(flags=SB_KERNMOUNT).
// Note how mm/shmem.c:shmem_fill_super() does not provide a default
// value for sbinfo->max_blocks when SB_KERNMOUNT is set.
DisableDefaultSizeLimit: true,
},
InternalMount: true,
}
tmpfsFilesystem, tmpfsRoot, err := tmpfs.FilesystemType{}.GetFilesystem(ctx, &k.vfs, auth.NewRootCredentials(k.rootUserNamespace), "", tmpfsOpts)
if err != nil {
return fmt.Errorf("failed to create tmpfs filesystem: %v", err)
}
defer tmpfsFilesystem.DecRef(ctx)
defer tmpfsRoot.DecRef(ctx)
k.shmMount = k.vfs.NewDisconnectedMount(tmpfsFilesystem, tmpfsRoot, &vfs.MountOptions{})
socketFilesystem, err := sockfs.NewFilesystem(&k.vfs)
if err != nil {
return fmt.Errorf("failed to create sockfs filesystem: %v", err)
}
defer socketFilesystem.DecRef(ctx)
k.socketMount = k.vfs.NewDisconnectedMount(socketFilesystem, nil, &vfs.MountOptions{})
sysVShmDevMinor, err := k.vfs.GetAnonBlockDevMinor()
if err != nil {
return fmt.Errorf("failed to get device number for SysV shm: %v", err)
}
k.sysVShmDevID = linux.MakeDeviceID(linux.UNNAMED_MAJOR, sysVShmDevMinor)
k.sockets = make(map[*vfs.FileDescription]*SocketRecord)
k.cgroupRegistry = newCgroupRegistry()
k.UnixSocketOpts = args.UnixSocketOpts
return nil
}
// +stateify savable
type privateMemoryFileMetadata struct {
owners []string
}
func savePrivateMFs(ctx context.Context, w io.Writer, pw io.Writer, mfsToSave map[string]*pgalloc.MemoryFile, mfOpts pgalloc.SaveOpts) error {
// mfOpts.ExcludeCommittedZeroPages is expected to reflect application
// memory usage behavior, but not necessarily usage of private MemoryFiles.
mfOpts.ExcludeCommittedZeroPages = false
var meta privateMemoryFileMetadata
// Generate the order in which private memory files are saved.
for fsID := range mfsToSave {
meta.owners = append(meta.owners, fsID)
}
// Save the metadata.
if _, err := state.Save(ctx, w, &meta); err != nil {
return err
}
// Followed by the private memory files in order.
for _, fsID := range meta.owners {
if err := mfsToSave[fsID].SaveTo(ctx, w, pw, mfOpts); err != nil {
return err
}
}
return nil
}
func loadPrivateMFs(ctx context.Context, r io.Reader, opts *pgalloc.LoadOpts) error {
// Load the metadata.
var meta privateMemoryFileMetadata
if _, err := state.Load(ctx, r, &meta); err != nil {
return err
}
mfmap := pgalloc.MemoryFileMapFromContext(ctx)
// Ensure that it is consistent with CtxFilesystemMemoryFileMap.
if len(mfmap) != len(meta.owners) {
return fmt.Errorf("inconsistent private memory files on restore: savedMFOwners = %v, CtxFilesystemMemoryFileMap = %v", meta.owners, mfmap)
}
// Load all private memory files.
for _, fsID := range meta.owners {
mf, ok := mfmap[fsID]
if !ok {
return fmt.Errorf("saved memory file for %q was not configured on restore", fsID)
}
if err := mf.LoadFrom(ctx, r, opts); err != nil {
return err
}
}
return nil
}
// SaveTo saves the state of k to w.
//
// Preconditions: The kernel must be paused throughout the call to SaveTo.
func (k *Kernel) SaveTo(ctx context.Context, w, pagesMetadata io.Writer, pagesFile *fd.FD, mfOpts pgalloc.SaveOpts) error {
saveStart := time.Now()
// Do not allow other Kernel methods to affect it while it's being saved.
k.extMu.Lock()
defer k.extMu.Unlock()
// Stop time.
k.pauseTimeLocked(ctx)
defer k.resumeTimeLocked(ctx)
// Evict all evictable MemoryFile allocations.
k.mf.StartEvictions()
k.mf.WaitForEvictions()
// Discard unsavable mappings, such as those for host file descriptors.
if err := k.invalidateUnsavableMappings(ctx); err != nil {
return fmt.Errorf("failed to invalidate unsavable mappings: %v", err)
}
// Capture all private memory files.
mfsToSave := make(map[string]*pgalloc.MemoryFile)
vfsCtx := context.WithValue(ctx, pgalloc.CtxMemoryFileMap, mfsToSave)
// Prepare filesystems for saving. This must be done after
// invalidateUnsavableMappings(), since dropping memory mappings may
// affect filesystem state (e.g. page cache reference counts).
if err := k.vfs.PrepareSave(vfsCtx); err != nil {
return err
}
// Mark all to-be-saved MemoryFiles as savable to inform kernel save below.
k.mf.MarkSavable()
for _, mf := range mfsToSave {
mf.MarkSavable()
}
var (
mfSaveWg sync.WaitGroup
mfSaveErr error
)
parallelMfSave := pagesMetadata != nil && pagesFile != nil
if parallelMfSave {
// Parallelize MemoryFile save and kernel save. Both are independent.
mfSaveWg.Add(1)
go func() {
defer mfSaveWg.Done()
mfSaveErr = k.saveMemoryFiles(ctx, w, pagesMetadata, pagesFile, mfsToSave, mfOpts)
}()
// Defer a Wait() so we wait for k.saveMemoryFiles() to complete even if we
// error out without reaching the other Wait() below.
defer mfSaveWg.Wait()
}
// Save the CPUID FeatureSet before the rest of the kernel so we can
// verify its compatibility on restore before attempting to restore the
// entire kernel, which may fail on an incompatible machine.
//
// N.B. This will also be saved along with the full kernel save below.
cpuidStart := time.Now()
if _, err := state.Save(ctx, w, &k.featureSet); err != nil {
return err
}
log.Infof("CPUID save took [%s].", time.Since(cpuidStart))
// Save the timekeeper's state.
if rootNS := k.rootNetworkNamespace; rootNS != nil && rootNS.Stack() != nil {
// Pause the network stack.
netstackPauseStart := time.Now()
log.Infof("Pausing root network namespace")
k.rootNetworkNamespace.Stack().Pause()
defer k.rootNetworkNamespace.Stack().Resume()
log.Infof("Pausing root network namespace took [%s].", time.Since(netstackPauseStart))
}
// Save the kernel state.
kernelStart := time.Now()
stats, err := state.Save(ctx, w, k)
if err != nil {
return err
}
log.Infof("Kernel save stats: %s", stats.String())
log.Infof("Kernel save took [%s].", time.Since(kernelStart))
if parallelMfSave {
mfSaveWg.Wait()
} else {
mfSaveErr = k.saveMemoryFiles(ctx, w, pagesMetadata, pagesFile, mfsToSave, mfOpts)
}
if mfSaveErr != nil {
return mfSaveErr
}
log.Infof("Overall save took [%s].", time.Since(saveStart))
return nil
}
func (k *Kernel) saveMemoryFiles(ctx context.Context, w, pagesMetadata io.Writer, pagesFile *fd.FD, mfsToSave map[string]*pgalloc.MemoryFile, mfOpts pgalloc.SaveOpts) error {
// Save the memory files' state.
memoryStart := time.Now()
pmw := w
if pagesMetadata != nil {
pmw = pagesMetadata
}
pw := w
if pagesFile != nil {
pw = pagesFile
}
if err := k.mf.SaveTo(ctx, pmw, pw, mfOpts); err != nil {
return err
}
if err := savePrivateMFs(ctx, pmw, pw, mfsToSave, mfOpts); err != nil {
return err
}
log.Infof("Memory files save took [%s].", time.Since(memoryStart))
return nil
}
// Preconditions: The kernel must be paused.
func (k *Kernel) invalidateUnsavableMappings(ctx context.Context) error {
invalidated := make(map[*mm.MemoryManager]struct{})
k.tasks.mu.RLock()
defer k.tasks.mu.RUnlock()
for t := range k.tasks.Root.tids {
// We can skip locking Task.mu here since the kernel is paused.
if memMgr := t.image.MemoryManager; memMgr != nil {
if _, ok := invalidated[memMgr]; !ok {
if err := memMgr.InvalidateUnsavable(ctx); err != nil {
return err
}
invalidated[memMgr] = struct{}{}
}
}
// I really wish we just had a sync.Map of all MMs...
if r, ok := t.runState.(*runSyscallAfterExecStop); ok {
if err := r.image.MemoryManager.InvalidateUnsavable(ctx); err != nil {
return err
}
}
}
return nil
}
// LoadFrom returns a new Kernel loaded from args.
//
// LoadFrom takes ownership of pagesFile.
func (k *Kernel) LoadFrom(ctx context.Context, r, pagesMetadata io.Reader, pagesFile *fd.FD, background bool, timeReady chan struct{}, net inet.Stack, clocks sentrytime.Clocks, vfsOpts *vfs.CompleteRestoreOptions, saveRestoreNet bool) error {
loadStart := time.Now()
defer func() {
if pagesFile != nil {
pagesFile.Close()
}
}()
var (
mfLoadWg sync.WaitGroup
mfLoadErr error
)
parallelMfLoad := pagesMetadata != nil && pagesFile != nil
if parallelMfLoad {
// Parallelize MemoryFile load and kernel load. Both are independent.
mfLoadWg.Add(1)
go func() {
defer mfLoadWg.Done()
mfLoadErr = k.loadMemoryFiles(ctx, r, pagesMetadata, pagesFile, background)
pagesFile = nil // transferred to k.loadMemoryFiles()
}()
// Defer a Wait() so we wait for k.loadMemoryFiles() to complete even if we
// error out without reaching the other Wait() below.
defer mfLoadWg.Wait()
}
k.runningTasksCond.L = &k.runningTasksMu
k.cpuClockTickerWakeCh = make(chan struct{}, 1)
k.cpuClockTickerStopCond.L = &k.runningTasksMu
initAppCores := k.applicationCores
// Load the pre-saved CPUID FeatureSet.
//
// N.B. This was also saved along with the full kernel below, so we
// don't need to explicitly install it in the Kernel.
cpuidStart := time.Now()
if _, err := state.Load(ctx, r, &k.featureSet); err != nil {
return err
}
log.Infof("CPUID load took [%s].", time.Since(cpuidStart))
// Verify that the FeatureSet is usable on this host. We do this before
// Kernel load so that the explicit CPUID mismatch error has priority
// over floating point state restore errors that may occur on load on
// an incompatible machine.
if err := k.featureSet.CheckHostCompatible(); err != nil {
return err
}
// Load the kernel state.
kernelStart := time.Now()
stats, err := state.Load(ctx, r, k)
if err != nil {
return err
}
log.Infof("Kernel load stats: %s", stats.String())
log.Infof("Kernel load took [%s].", time.Since(kernelStart))
if parallelMfLoad {
mfLoadWg.Wait()
} else {
mfLoadErr = k.loadMemoryFiles(ctx, r, pagesMetadata, pagesFile, background)
pagesFile = nil // transferred to k.loadMemoryFiles()
}
if mfLoadErr != nil {
return fmt.Errorf("failed to load memory files: %w", mfLoadErr)
}
if !saveRestoreNet {
// rootNetworkNamespace and stack should be populated after
// loading the state file. Reset the stack before restoring the
// root network stack.
k.rootNetworkNamespace.ResetStack()
k.rootNetworkNamespace.RestoreRootStack(net)
}
k.Timekeeper().SetClocks(clocks, k.vdsoParams)
if timeReady != nil {
close(timeReady)
}
if saveRestoreNet {
log.Infof("netstack save restore is enabled")
s := k.rootNetworkNamespace.Stack()
if s == nil {
panic("inet.Stack cannot be nil when netstack s/r is enabled")
}
if net != nil {
s.ReplaceConfig(net)
}
s.Restore()
} else if net != nil {
net.Restore()
}
if err := k.vfs.CompleteRestore(ctx, vfsOpts); err != nil {
return vfs.PrependErrMsg("vfs.CompleteRestore() failed", err)
}
tcpip.AsyncLoading.Wait()
log.Infof("Overall load took [%s] after async work", time.Since(loadStart))
// Applications may size per-cpu structures based on k.applicationCores, so
// it can't change across save/restore. When we are virtualizing CPU
// numbers, this isn't a problem. However, when we are exposing host CPU
// assignments, we can't tolerate an increase in the number of host CPUs,
// which could result in getcpu(2) returning CPUs that applications expect
// not to exist.
if k.useHostCores && initAppCores > k.applicationCores {
return fmt.Errorf("UseHostCores enabled: can't increase ApplicationCores from %d to %d after restore", k.applicationCores, initAppCores)
}
return nil
}
// loadMemoryFiles takes ownership of pagesFile.
func (k *Kernel) loadMemoryFiles(ctx context.Context, r, pagesMetadata io.Reader, pagesFile *fd.FD, background bool) error {
memoryStart := time.Now()
pmr := r
if pagesMetadata != nil {
pmr = pagesMetadata
}
var (
pagesFileUsers atomicbitops.Int64
asyncPageLoadWG sync.WaitGroup
)
opts := pgalloc.LoadOpts{
PagesFile: pagesFile,
OnAsyncPageLoadStart: func() {
pagesFileUsers.Add(1)
asyncPageLoadWG.Add(1)
},
OnAsyncPageLoadDone: func(error) {
if n := pagesFileUsers.Add(-1); n == 0 {
pagesFile.Close()
} else if n < 0 {
panic("pagesFileUsers < 0")
}
asyncPageLoadWG.Done()
},
}
if err := k.mf.LoadFrom(ctx, pmr, &opts); err != nil {
return err
}
if err := loadPrivateMFs(ctx, pmr, &opts); err != nil {
return err
}
if !background {
asyncPageLoadWG.Wait()
}
log.Infof("Memory files load took [%s].", time.Since(memoryStart))
return nil
}
// UniqueID returns a unique identifier.
func (k *Kernel) UniqueID() uint64 {
id := k.uniqueID.Add(1)
if id == 0 {
panic("unique identifier generator wrapped around")
}
return id
}
// CreateProcessArgs holds arguments to kernel.CreateProcess.
type CreateProcessArgs struct {
// Filename is the filename to load as the init binary.
//
// If this is provided as "", File will be checked, then the file will be
// guessed via Argv[0].
Filename string
// File is a passed host FD pointing to a file to load as the init binary.
//
// This is checked if and only if Filename is "".
File *vfs.FileDescription
// Argv is a list of arguments.
Argv []string
// Envv is a list of environment variables.
Envv []string
// WorkingDirectory is the initial working directory.
//
// This defaults to the root if empty.
WorkingDirectory string
// Credentials is the initial credentials.
Credentials *auth.Credentials
// FDTable is the initial set of file descriptors. If CreateProcess succeeds,
// it takes a reference on FDTable.
FDTable *FDTable
// Umask is the initial umask.
Umask uint
// Limits are the initial resource limits.
Limits *limits.LimitSet
// MaxSymlinkTraversals is the maximum number of symlinks to follow
// during resolution.
MaxSymlinkTraversals uint
// UTSNamespace is the initial UTS namespace.
UTSNamespace *UTSNamespace
// IPCNamespace is the initial IPC namespace.
IPCNamespace *IPCNamespace
// PIDNamespace is the initial PID Namespace.
PIDNamespace *PIDNamespace
// MountNamespace optionally contains the mount namespace for this
// process. If nil, the init process's mount namespace is used.
//
// Anyone setting MountNamespace must donate a reference (i.e.
// increment it).
MountNamespace *vfs.MountNamespace
// ContainerID is the container that the process belongs to.
ContainerID string
// InitialCgroups are the cgroups the container is initialized to.
InitialCgroups map[Cgroup]struct{}
// Origin indicates how the task was first created.
Origin TaskOrigin
// TTY is the optional controlling TTY to associate with this process.
TTY *TTY
}
// NewContext returns a context.Context that represents the task that will be
// created by args.NewContext(k).
func (args *CreateProcessArgs) NewContext(k *Kernel) context.Context {
return &createProcessContext{
Context: context.Background(),
kernel: k,
args: args,
}
}
// createProcessContext is a context.Context that represents the context