StorageManagerService 的启动

1. StorageManagerService的创建

frameworks/base/services/java/com/android/server/SystemServer.java

在SystemServer的startOtherServices()中启动StorageManagerService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
private static final String STORAGE_MANAGER_SERVICE_CLASS =
"com.android.server.StorageManagerService$Lifecycle";
private void startOtherServices() {
...
IStorageManager storageManager = null;
if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
if (!"0".equals(SystemProperties.get("system_init.startmountservice"))) {
traceBeginAndSlog("StartStorageManagerService");
try {
// 创建STORAGE_MANAGER_SERVICE_CLASS对象,并将其加入ServiceManager服务列表
mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
storageManager = IStorageManager.Stub.asInterface(
ServiceManager.getService("mount"));
} catch (Throwable e) {
reportWtf("starting StorageManagerService", e);
}
traceEnd();
...
}
}
...
}

2. StorageManagerService的onStart()方法

frameworks/base/services/core/java/com/android/server/StorageManagerService.java

1
2
3
4
5
6
7
8
9
10
11
12
public static class Lifecycle extends SystemService {
@Override
public void onStart() {
// 创建StorageManagerService对象
mStorageManagerService = new StorageManagerService(getContext());
// 登记Binder服务,其名为'mount'
publishBinderService("mount", mStorageManagerService);
// 启动StorageManagerService,包括'storaged'与'vold'
mStorageManagerService.start();
}
...
}

3. StorageManagerService的onBootPhase()方法

frameworks/base/services/core/java/com/android/server/StorageManagerService.java

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
public static class Lifecycle extends SystemService {
...
@Override
public void onBootPhase(int phase) {
// 系统启动到PHASE_ACTIVITY_MANAGER_READY时回调
if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
mStorageManagerService.systemReady();
// 系统启动到PHASE_BOOT_COMPLETED时回调
} else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
mStorageManagerService.bootCompleted();
}
}
...
}

private void systemReady() {
LocalServices.getService(ActivityManagerInternal.class)
.registerScreenObserver(this);
mSystemReady = true;
// 发送H_SYSTEM_READY消息
mHandler.obtainMessage(H_SYSTEM_READY).sendToTarget();
}

private void handleSystemReady() {
initIfReadyAndConnected();
resetIfReadyAndConnected();
// 开始每日fstrim操作
MountServiceIdler.scheduleIdlePass(mContext);
// 切换zram-enable系统属性以响应设置
mContext.getContentResolver().registerContentObserver(
Settings.Global.getUriFor(Settings.Global.ZRAM_ENABLED),
false /*notifyForDescendants*/,
new ContentObserver(null /* current thread */) {
@Override
public void onChange(boolean selfChange) {
refreshZramSettings();
}
});
refreshZramSettings();
}

private void resetIfReadyAndConnected() {
Slog.d(TAG, "Thinking about reset, mSystemReady=" + mSystemReady
+ ", mDaemonConnected=" + mDaemonConnected);
// vold守护进程已连接,则执行reset操作
if (mSystemReady && mDaemonConnected) {
final List<UserInfo> users = mContext.getSystemService(UserManager.class).getUsers();
killMediaProvider(users);
final int[] systemUnlockedUsers;
synchronized (mLock) {
systemUnlockedUsers = mSystemUnlockedUsers;
mDisks.clear();
mVolumes.clear();
// 将/data路径的private volume添加到mVolumes
addInternalVolumeLocked();
}

try {
mVold.reset();
// 告知vold所有已存在、启动的users
for (UserInfo user : users) {
mVold.onUserAdded(user.id, user.serialNumber);
}
for (int userId : systemUnlockedUsers) {
mVold.onUserStarted(userId);
mStoraged.onUserStarted(userId);
}
mVold.onSecureKeyguardStateChanged(mSecureKeyguardShowing);
} catch (Exception e) {
Slog.wtf(TAG, e);
}
}
}

4. StorageManagerService的构造函数

frameworks/base/services/core/java/com/android/server/StorageManagerService.java

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
public StorageManagerService(Context context) {
sSelf = this;
mContext = context;
// FgThread名为'android.fg',创建IStorageEventListener回调
mCallbacks = new Callbacks(FgThread.get().getLooper());
mLockPatternUtils = new LockPatternUtils(mContext);
// 创建PMS的客户端对象
mPms = (PackageManagerService) ServiceManager.getService("package");
// 创建线程
HandlerThread hthread = new HandlerThread(TAG);
hthread.start();
mHandler = new StorageManagerServiceHandler(hthread.getLooper());
// IoThread名为'android.io',创建Obb handler
mObbActionHandler = new ObbActionHandler(IoThread.get().getLooper());
File dataDir = Environment.getDataDirectory();
// /data/system目录
File systemDir = new File(dataDir, "system");
// LAST_FSTRIM_FILE - last-fstrim
mLastMaintenanceFile = new File(systemDir, LAST_FSTRIM_FILE);
// 若last-fstrim文件不存在则创建,若存在则更新其修改时间
if (!mLastMaintenanceFile.exists()) {
try {
(new FileOutputStream(mLastMaintenanceFile)).close();
} catch (IOException e) {
Slog.e(TAG, "Unable to create fstrim record " + mLastMaintenanceFile.getPath());
}
} else {
mLastMaintenance = mLastMaintenanceFile.lastModified();
}
// 解析/data/system/storage.xml文件,其标签为'storage-settings'
mSettingsFile = new AtomicFile(
new File(Environment.getDataSystemDirectory(), "storage.xml"), "storage-settings");
synchronized (mLock) {
readSettingsLocked();
}
// 将StorageManagerInternalImpl加入到LocalServices服务列表
LocalServices.addService(StorageManagerInternal.class, mStorageManagerInternal);
final IntentFilter userFilter = new IntentFilter();
userFilter.addAction(Intent.ACTION_USER_ADDED);
userFilter.addAction(Intent.ACTION_USER_REMOVED);
mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
// 创建内部存储存储根
synchronized (mLock) {
addInternalVolumeLocked();
}
// watchdog监视器
if (WATCHDOG_ENABLE) {
Watchdog.getInstance().addMonitor(this);
}
}

5. StorageManagerServiceHandler的handleMessage()方法

frameworks/base/services/core/java/com/android/server/StorageManagerService.java

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
class StorageManagerServiceHandler extends Handler {
public StorageManagerServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case H_SYSTEM_READY: {
handleSystemReady();
break;
}
case H_DAEMON_CONNECTED: {
handleDaemonConnected();
break;
}
case H_FSTRIM: {
Slog.i(TAG, "Running fstrim idle maintenance");
try {
mLastMaintenance = System.currentTimeMillis();
mLastMaintenanceFile.setLastModified(mLastMaintenance);
} catch (Exception e) {
Slog.e(TAG, "Unable to record last fstrim!");
}
fstrim(0, null);
Runnable callback = (Runnable) msg.obj;
if (callback != null) {
callback.run();
}
break;
}
case H_SHUTDOWN: {
final IStorageShutdownObserver obs = (IStorageShutdownObserver) msg.obj;
boolean success = false;
try {
mVold.shutdown();
success = true;
} catch (Exception e) {
Slog.wtf(TAG, e);
}
if (obs != null) {
try {
obs.onShutDownComplete(success ? 0 : -1);
} catch (Exception ignored) {
}
}
break;
}
case H_VOLUME_MOUNT: {
final VolumeInfo vol = (VolumeInfo) msg.obj;
if (isMountDisallowed(vol)) {
Slog.i(TAG, "Ignoring mount " + vol.getId() + " due to policy");
break;
}
try {
mVold.mount(vol.id, vol.mountFlags, vol.mountUserId);
} catch (Exception e) {
Slog.wtf(TAG, e);
}
break;
}
case H_VOLUME_UNMOUNT: {
final VolumeInfo vol = (VolumeInfo) msg.obj;
unmount(vol.getId());
break;
}
case H_VOLUME_BROADCAST: {
final StorageVolume userVol = (StorageVolume) msg.obj;
final String envState = userVol.getState();
Slog.d(TAG, "Volume " + userVol.getId() + " broadcasting " + envState + " to "
+ userVol.getOwner());
final String action = VolumeInfo.getBroadcastForEnvironment(envState);
if (action != null) {
final Intent intent = new Intent(action,
Uri.fromFile(userVol.getPathFile()));
intent.putExtra(StorageVolume.EXTRA_STORAGE_VOLUME, userVol);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
| Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
mContext.sendBroadcastAsUser(intent, userVol.getOwner());
}
break;
}
case H_INTERNAL_BROADCAST: {
final Intent intent = (Intent) msg.obj;
mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
android.Manifest.permission.WRITE_MEDIA_STORAGE);
break;
}
case H_PARTITION_FORGET: {
final VolumeRecord rec = (VolumeRecord) msg.obj;
forgetPartition(rec.partGuid, rec.fsUuid);
break;
}
case H_RESET: {
resetIfReadyAndConnected();
break;
}
case H_RUN_IDLE_MAINT: {
Slog.i(TAG, "Running idle maintenance");
runIdleMaint((Runnable)msg.obj);
break;
}
case H_ABORT_IDLE_MAINT: {
Slog.i(TAG, "Aborting idle maintenance");
abortIdleMaint((Runnable)msg.obj);
break;
}
}
}
}