vold和mount service都是binder service,并不是mount service只调用vold,vold也会调用mount service,这是双向的,这里解答上一章的问题
思考, vold比mount service启动的早,那开机时vold获取到的listener为空,也就是说虽然disk创建了但是不会mount,那什么时候才会mount呢?
这里通过mount service 的分析解释上面的问题
1. mount service在SystemServer->startOtherServices() 可以看出这个service对android来说不是至关重要的,至少他不是bootstrap、core service
frameworks/base/services/java/com/android/server/SystemServer.java
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
.....
1788 mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS);
1789 storageManager = IStorageManager.Stub.asInterface(
1790 ServiceManager.getService("mount"));
2. onStart()
frameworks/base/services/core/java/com/android/server/StorageManagerService.java#231
231 public void onStart() {
232 mStorageManagerService = new StorageManagerService(getContext()); ----> 创建StorageManagerService实例
233 publishBinderService("mount", mStorageManagerService); -----> 添加mount到ServiceManager里
234 mStorageManagerService.start(); -
235 }
3. 两件事: connectStoraged() 和 connectVold()
1926 private void start() {
1927 connectStoraged();
1928 connectVold();
1929 }
1930
1931 private void connectStoraged() {
1932 IBinder binder = ServiceManager.getService("storaged");
1933 if (binder != null) {
1934 try {
1935 binder.linkToDeath(new DeathRecipient() {
1936 @Override
1937 public void binderDied() {
1938 Slog.w(TAG, "storaged died; reconnecting");
1939 mStoraged = null;
1940 connectStoraged();
1941 }
1942 }, 0);
1943 } catch (RemoteException e) {
1944 binder = null;
1945 }
1946 }
1947
1948 if (binder != null) {
1949 mStoraged = IStoraged.Stub.asInterface(binder);
1950 } else {
1951 Slog.w(TAG, "storaged not found; trying again");
1952 }
1953
1954 if (mStoraged == null) {
1955 BackgroundThread.getHandler().postDelayed(() -> {
1956 connectStoraged();
1957 }, DateUtils.SECOND_IN_MILLIS);
1958 } else {
1959 onDaemonConnected();
1960 }
1961 }
1962
1963 private void connectVold() {
1964 IBinder binder = ServiceManager.getService("vold");
1965 if (binder != null) {
1966 try {
1967 binder.linkToDeath(new DeathRecipient() {
1968 @Override
1969 public void binderDied() {
1970 Slog.w(TAG, "vold died; reconnecting");
1971 mVold = null;
1972 connectVold();
1973 }
1974 }, 0);
1975 } catch (RemoteException e) {
1976 binder = null;
1977 }
1978 }
1979
1980 if (binder != null) {
1981 mVold = IVold.Stub.asInterface(binder);
1982 try {
1983 mVold.setListener(mListener); ----------> 连上vold 后把listener设置到了vold中
1984 } catch (RemoteException e) {
1985 mVold = null;
1986 Slog.w(TAG, "vold listener rejected; trying again", e);
1987 }
1988 } else {
1989 Slog.w(TAG, "vold not found; trying again");
1990 }
1991
1992 if (mVold == null) {
1993 BackgroundThread.getHandler().postDelayed(() -> {
1994 connectVold();
1995 }, DateUtils.SECOND_IN_MILLIS);
1996 } else {
1997 restoreLocalUnlockedUsers();
1998 onDaemonConnected();
1999 }
2000 }
3. onDaemonConnected()
1313 public void onDaemonConnected() {
1314 mDaemonConnected = true;
1315 mHandler.obtainMessage(H_DAEMON_CONNECTED).sendToTarget();
1316 }
1317
1318 private void handleDaemonConnected() {
1319 resetIfBootedAndConnected();
1320 }
4. resetIfBootedAndConnected() 这里就是上一章提出的问题的原因函数
1056 private void resetIfBootedAndConnected() {
1057 Slog.d(TAG, "Thinking about reset, mBootCompleted=" + mBootCompleted
1058 + ", mDaemonConnected=" + mDaemonConnected);
1059 if (mBootCompleted && mDaemonConnected) { --------> 只有两个条件同时满足,才会执行reset操作
1060 final UserManager userManager = mContext.getSystemService(UserManager.class);
1061 final List<UserInfo> users = userManager.getUsers();
1062
1063 mStorageSessionController.onReset(mVold, () -> {
1064 mHandler.removeCallbacksAndMessages(null);
1065 });
1066
1067 final int[] systemUnlockedUsers;
1068 synchronized (mLock) {
1069 // make copy as sorting can change order
1070 systemUnlockedUsers = Arrays.copyOf(mSystemUnlockedUsers,
1071 mSystemUnlockedUsers.length);
1072
1073 mDisks.clear();
1074 mVolumes.clear();
1075
1076 addInternalVolumeLocked();
1077 }
1078
1079 try {
1080 // Reset vold to tear down existing disks/volumes and start from
1081 // a clean state. Exception: already-unlocked user storage will
1082 // remain unlocked and is not affected by the reset.
1083 //
1084 // TODO(b/135341433): Remove cautious logging when FUSE is stable
1085 Slog.i(TAG, "Resetting vold...");
1086 mVold.reset(); ----------->>>>>>>>>> 根源在这里
1087 Slog.i(TAG, "Reset vold");
1088
1089 // Tell vold about all existing and started users
1090 for (UserInfo user : users) {
1091 if (user.isCloneProfile()) {
1092 mVold.onUserAdded(user.id, user.serialNumber, user.profileGroupId);
1093 } else {
1094 mVold.onUserAdded(user.id, user.serialNumber, -1);
1095 }
1096 }
1097 for (int userId : systemUnlockedUsers) {
1098 mVold.onUserStarted(userId);
1099 mStoraged.onUserStarted(userId);
1100 }
1101 restoreSystemUnlockedUsers(userManager, users, systemUnlockedUsers);
1102 mVold.onSecureKeyguardStateChanged(mSecureKeyguardShowing);
1103 mStorageManagerInternal.onReset(mVold);
1104 } catch (Exception e) {
1105 Slog.wtf(TAG, e);
1106 }
1107 }
1108 }
5.bootCompleted() 这里才会真正的执行到reset
238 public void onBootPhase(int phase) {
239 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
240 mStorageManagerService.servicesReady();
241 } else if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
242 mStorageManagerService.systemReady();
243 } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
244 mStorageManagerService.bootCompleted();
245 }
2088 private void bootCompleted() {
2089 mBootCompleted = true;
2090 mHandler.obtainMessage(H_BOOT_COMPLETED).sendToTarget();
2091 }
2093 private void handleBootCompleted() {
2094 resetIfBootedAndConnected();
2095 }
log: 第三次才会执行reset
04-09 15:27:35.006 2112 3684 D StorageManagerService: Thinking about reset, mBootCompleted=false, mDaemonConnected=true
04-09 15:27:35.012 2112 3684 D StorageManagerService: Thinking about reset, mBootCompleted=false, mDaemonConnected=true
04-09 15:27:37.854 2112 3684 D StorageManagerService: Thinking about reset, mBootCompleted=true, mDaemonConnected=true
6. vold reset 就是执行的是VolumeManager::reset() 这里就不赘述了
904 int VolumeManager::reset() {
905 // Tear down all existing disks/volumes and start from a blank slate so
906 // newly connected framework hears all events.
907 for (const auto& vol : mInternalEmulatedVolumes) {
908 vol->destroy();
909 }
910 mInternalEmulatedVolumes.clear();
911
912 // Destroy and recreate all disks except that StubVolume disks are just
913 // destroyed and removed from both mDisks and mPendingDisks.
914 // StubVolumes are managed from outside Android (e.g. from Chrome OS) and
915 // their disk recreation on reset events should be handled from outside by
916 // calling createStubVolume() again.
917 for (const auto& disk : mDisks) {
918 disk->destroy();
919 if (!disk->isStub()) {
920 disk->create(); -------------> 所有的disks 重新create一遍, 这回listener不会为空了
921 }
922 }
923 const auto isStub = [](const auto& disk) { return disk->isStub(); };
924 mDisks.remove_if(isStub);
925 mPendingDisks.remove_if(isStub);
926
927 updateVirtualDisk();
928 mAddedUsers.clear();
929 mStartedUsers.clear();
930 mSharedStorageUser.clear();
931
932 // Abort all FUSE connections to avoid deadlocks if the FUSE daemon was killed
933 // with FUSE fds open.
934 abortFuse();
935 return 0;
936 }
7. onVolumeCreated()
system/vold/model/VolumeBase.cpp
181 status_t VolumeBase::create() {
182 CHECK(!mCreated);
183
184 mCreated = true;
185 status_t res = doCreate();
186
187 auto listener = getListener();
188 if (listener) {
189 listener->onVolumeCreated(getId(), static_cast<int32_t>(mType), mDiskId, mPartGuid,
190 mMountUserId);
191 }
192
193 setState(State::kUnmounted);
194 return res;
195 }
8. onVolumeCreatedLocked()
1373 public void onVolumeCreated(String volId, int type, String diskId, String partGuid,
1374 int userId) {
1375 synchronized (mLock) {
1376 final DiskInfo disk = mDisks.get(diskId);
1377 final VolumeInfo vol = new VolumeInfo(volId, type, disk, partGuid);
1378 vol.mountUserId = userId;
1379 mVolumes.put(volId, vol);
1380 onVolumeCreatedLocked(vol);
1381 }
1382 }
9. onVolumeCreatedLocked()
.....
1523 } else if (vol.type == VolumeInfo.TYPE_PUBLIC) {
1524 // TODO: only look at first public partition
1525 if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid)
1526 && vol.disk.isDefaultPrimary()) {
1527 Slog.v(TAG, "Found primary storage at " + vol);
1528 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
1529 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE_FOR_WRITE;
1530 }
1531
1532 // Adoptable public disks are visible to apps, since they meet
1533 // public API requirement of being in a stable location.
1534 // If FBE is enabled, sdcard is no longer considered adoptable,
1535 // make sdcard visible.
1536 if (vol.disk.isAdoptable() || (vol.disk.isSd() && !vol.disk.label.equals("Virtual"))) {
1537 vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE_FOR_WRITE;
1538 }
1539
1540 vol.mountUserId = mCurrentUserId;
1541 mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget(); -------> 执行mount
1542
1543 }
....
740 case H_VOLUME_MOUNT: {
741 final VolumeInfo vol = (VolumeInfo) msg.obj;
742 if (isMountDisallowed(vol)) {
743 Slog.i(TAG, "Ignoring mount " + vol.getId() + " due to policy");
744 break;
745 }
746
747 mount(vol);
748 brea