2 * Copyright (C) 2008 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
23 #include <sys/types.h>
25 #include <sys/types.h>
27 #include <sys/mount.h>
28 #include <sys/param.h>
30 #include <linux/kdev_t.h>
32 #include <cutils/properties.h>
34 #include <diskconfig/diskconfig.h>
36 #include <private/android_filesystem_config.h>
38 #define LOG_TAG "Vold"
40 #include <cutils/fs.h>
41 #include <cutils/log.h>
46 #include "VolumeManager.h"
47 #include "ResponseCode.h"
52 extern "C" void dos_partition_dec(void const *pp, struct dos_partition *d);
53 extern "C" void dos_partition_enc(void *pp, struct dos_partition *d);
57 * Media directory - stuff that only media_rw user can see
59 const char *Volume::MEDIA_DIR = "/mnt/media_rw";
62 * Fuse directory - location where fuse wrapped filesystems go
64 const char *Volume::FUSE_DIR = "/storage";
67 * Path to external storage where *only* root can access ASEC image files
69 const char *Volume::SEC_ASECDIR_EXT = "/mnt/secure/asec";
72 * Path to internal storage where *only* root can access ASEC image files
74 const char *Volume::SEC_ASECDIR_INT = "/data/app-asec";
76 * Path to where secure containers are mounted
78 const char *Volume::ASECDIR = "/mnt/asec";
81 * Path to where OBBs are mounted
83 const char *Volume::LOOPDIR = "/mnt/obb";
85 const char *Volume::BLKID_PATH = "/system/bin/blkid";
87 static const char *stateToStr(int state) {
88 if (state == Volume::State_Init)
89 return "Initializing";
90 else if (state == Volume::State_NoMedia)
92 else if (state == Volume::State_Idle)
93 return "Idle-Unmounted";
94 else if (state == Volume::State_Pending)
96 else if (state == Volume::State_Mounted)
98 else if (state == Volume::State_Unmounting)
100 else if (state == Volume::State_Checking)
102 else if (state == Volume::State_Formatting)
104 else if (state == Volume::State_Shared)
105 return "Shared-Unmounted";
106 else if (state == Volume::State_SharedMnt)
107 return "Shared-Mounted";
109 return "Unknown-Error";
112 Volume::Volume(VolumeManager *vm, const fstab_rec* rec, int flags) {
115 mLabel = strdup(rec->label);
118 mState = Volume::State_Init;
120 mCurrentlyMountedKdev = -1;
121 mPartIdx = rec->partnum;
131 void Volume::setDebug(bool enable) {
135 dev_t Volume::getDiskDevice() {
139 dev_t Volume::getShareDevice() {
140 return getDiskDevice();
143 void Volume::handleVolumeShared() {
146 void Volume::handleVolumeUnshared() {
149 int Volume::handleBlockEvent(NetlinkEvent *evt) {
154 void Volume::setUuid(const char* uuid) {
162 mUuid = strdup(uuid);
163 snprintf(msg, sizeof(msg), "%s %s \"%s\"", getLabel(),
164 getFuseMountpoint(), mUuid);
167 snprintf(msg, sizeof(msg), "%s %s", getLabel(), getFuseMountpoint());
170 mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeUuidChange, msg,
174 void Volume::setUserLabel(const char* userLabel) {
182 mUserLabel = strdup(userLabel);
183 snprintf(msg, sizeof(msg), "%s %s \"%s\"", getLabel(),
184 getFuseMountpoint(), mUserLabel);
187 snprintf(msg, sizeof(msg), "%s %s", getLabel(), getFuseMountpoint());
190 mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeUserLabelChange,
194 void Volume::setState(int state) {
196 int oldState = mState;
198 if (oldState == state) {
199 SLOGW("Duplicate state (%d)\n", state);
203 if ((oldState == Volume::State_Pending) && (state != Volume::State_Idle)) {
209 SLOGD("Volume %s state changing %d (%s) -> %d (%s)", mLabel,
210 oldState, stateToStr(oldState), mState, stateToStr(mState));
211 snprintf(msg, sizeof(msg),
212 "Volume %s %s state changed from %d (%s) to %d (%s)", getLabel(),
213 getFuseMountpoint(), oldState, stateToStr(oldState), mState,
216 mVm->getBroadcaster()->sendBroadcast(ResponseCode::VolumeStateChange,
220 int Volume::createDeviceNode(const char *path, int major, int minor) {
221 mode_t mode = 0660 | S_IFBLK;
222 dev_t dev = (major << 8) | minor;
223 if (mknod(path, mode, dev) < 0) {
224 if (errno != EEXIST) {
231 int Volume::formatVol(bool wipe) {
233 if (getState() == Volume::State_NoMedia) {
236 } else if (getState() != Volume::State_Idle) {
241 if (isMountpointMounted(getMountpoint())) {
242 SLOGW("Volume is idle but appears to be mounted - fixing");
243 setState(Volume::State_Mounted);
244 // mCurrentlyMountedKdev = XXX
249 bool formatEntireDevice = (mPartIdx == -1);
250 char devicePath[255];
251 dev_t diskNode = getDiskDevice();
252 dev_t partNode = MKDEV(MAJOR(diskNode), (formatEntireDevice ? 1 : mPartIdx));
254 setState(Volume::State_Formatting);
257 // Only initialize the MBR if we are formatting the entire device
258 if (formatEntireDevice) {
259 sprintf(devicePath, "/dev/block/vold/%d:%d",
260 MAJOR(diskNode), MINOR(diskNode));
262 if (initializeMbr(devicePath)) {
263 SLOGE("Failed to initialize MBR (%s)", strerror(errno));
268 sprintf(devicePath, "/dev/block/vold/%d:%d",
269 MAJOR(partNode), MINOR(partNode));
272 SLOGI("Formatting volume %s (%s)", getLabel(), devicePath);
275 if (Fat::format(devicePath, 0, wipe)) {
276 SLOGE("Failed to format (%s)", strerror(errno));
283 setState(Volume::State_Idle);
287 bool Volume::isMountpointMounted(const char *path) {
289 char mount_path[256];
294 if (!(fp = fopen("/proc/mounts", "r"))) {
295 SLOGE("Error opening /proc/mounts (%s)", strerror(errno));
299 while(fgets(line, sizeof(line), fp)) {
300 line[strlen(line)-1] = '\0';
301 sscanf(line, "%255s %255s %255s\n", device, mount_path, rest);
302 if (!strcmp(mount_path, path)) {
312 int Volume::mountVol() {
313 dev_t deviceNodes[4];
317 int flags = getFlags();
318 bool providesAsec = (flags & VOL_PROVIDES_ASEC) != 0;
320 // TODO: handle "bind" style mounts, for emulated storage
322 char decrypt_state[PROPERTY_VALUE_MAX];
323 char crypto_state[PROPERTY_VALUE_MAX];
324 char encrypt_progress[PROPERTY_VALUE_MAX];
326 property_get("vold.decrypt", decrypt_state, "");
327 property_get("vold.encrypt_progress", encrypt_progress, "");
329 /* Don't try to mount the volumes if we have not yet entered the disk password
330 * or are in the process of encrypting.
332 if ((getState() == Volume::State_NoMedia) ||
333 ((!strcmp(decrypt_state, "1") || encrypt_progress[0]) && providesAsec)) {
334 snprintf(errmsg, sizeof(errmsg),
335 "Volume %s %s mount failed - no media",
336 getLabel(), getFuseMountpoint());
337 mVm->getBroadcaster()->sendBroadcast(
338 ResponseCode::VolumeMountFailedNoMedia,
342 } else if (getState() != Volume::State_Idle) {
344 if (getState() == Volume::State_Pending) {
350 if (isMountpointMounted(getMountpoint())) {
351 SLOGW("Volume is idle but appears to be mounted - fixing");
352 setState(Volume::State_Mounted);
353 // mCurrentlyMountedKdev = XXX
357 n = getDeviceNodes((dev_t *) &deviceNodes, 4);
359 SLOGE("Failed to get device nodes (%s)\n", strerror(errno));
363 /* If we're running encrypted, and the volume is marked as encryptable and nonremovable,
364 * and also marked as providing Asec storage, then we need to decrypt
365 * that partition, and update the volume object to point to it's new decrypted
368 property_get("ro.crypto.state", crypto_state, "");
370 ((flags & (VOL_NONREMOVABLE | VOL_ENCRYPTABLE))==(VOL_NONREMOVABLE | VOL_ENCRYPTABLE)) &&
371 !strcmp(crypto_state, "encrypted") && !isDecrypted()) {
372 char new_sys_path[MAXPATHLEN];
374 int new_major, new_minor;
377 /* We only expect one device node returned when mounting encryptable volumes */
378 SLOGE("Too many device nodes returned when mounting %d\n", getMountpoint());
382 if (cryptfs_setup_volume(getLabel(), MAJOR(deviceNodes[0]), MINOR(deviceNodes[0]),
383 new_sys_path, sizeof(new_sys_path),
384 &new_major, &new_minor)) {
385 SLOGE("Cannot setup encryption mapping for %d\n", getMountpoint());
388 /* We now have the new sysfs path for the decrypted block device, and the
389 * majore and minor numbers for it. So, create the device, update the
390 * path to the new sysfs path, and continue.
393 sizeof(nodepath), "/dev/block/vold/%d:%d",
394 new_major, new_minor);
395 if (createDeviceNode(nodepath, new_major, new_minor)) {
396 SLOGE("Error making device node '%s' (%s)", nodepath,
400 // Todo: Either create sys filename from nodepath, or pass in bogus path so
401 // vold ignores state changes on this internal device.
402 updateDeviceInfo(nodepath, new_major, new_minor);
404 /* Get the device nodes again, because they just changed */
405 n = getDeviceNodes((dev_t *) &deviceNodes, 4);
407 SLOGE("Failed to get device nodes (%s)\n", strerror(errno));
412 for (i = 0; i < n; i++) {
413 char devicePath[255];
415 sprintf(devicePath, "/dev/block/vold/%d:%d", MAJOR(deviceNodes[i]),
416 MINOR(deviceNodes[i]));
418 SLOGI("%s being considered for volume %s\n", devicePath, getLabel());
421 setState(Volume::State_Checking);
423 if (Fat::check(devicePath)) {
424 if (errno == ENODATA) {
425 SLOGW("%s does not contain a FAT filesystem\n", devicePath);
429 /* Badness - abort the mount */
430 SLOGE("%s failed FS checks (%s)", devicePath, strerror(errno));
431 setState(Volume::State_Idle);
438 if (Fat::doMount(devicePath, getMountpoint(), false, false, false,
439 AID_MEDIA_RW, AID_MEDIA_RW, 0007, true)) {
440 SLOGE("%s failed to mount via VFAT (%s)\n", devicePath, strerror(errno));
444 extractMetadata(devicePath);
446 if (providesAsec && mountAsecExternal() != 0) {
447 SLOGE("Failed to mount secure area (%s)", strerror(errno));
448 umount(getMountpoint());
449 setState(Volume::State_Idle);
454 snprintf(service, 64, "fuse_%s", getLabel());
455 property_set("ctl.start", service);
457 setState(Volume::State_Mounted);
458 mCurrentlyMountedKdev = deviceNodes[i];
462 SLOGE("Volume %s found no suitable devices for mounting :(\n", getLabel());
463 setState(Volume::State_Idle);
468 int Volume::mountAsecExternal() {
469 char legacy_path[PATH_MAX];
470 char secure_path[PATH_MAX];
472 snprintf(legacy_path, PATH_MAX, "%s/android_secure", getMountpoint());
473 snprintf(secure_path, PATH_MAX, "%s/.android_secure", getMountpoint());
475 // Recover legacy secure path
476 if (!access(legacy_path, R_OK | X_OK) && access(secure_path, R_OK | X_OK)) {
477 if (rename(legacy_path, secure_path)) {
478 SLOGE("Failed to rename legacy asec dir (%s)", strerror(errno));
482 if (fs_prepare_dir(secure_path, 0770, AID_MEDIA_RW, AID_MEDIA_RW) != 0) {
486 if (mount(secure_path, SEC_ASECDIR_EXT, "", MS_BIND, NULL)) {
487 SLOGE("Failed to bind mount points %s -> %s (%s)", secure_path,
488 SEC_ASECDIR_EXT, strerror(errno));
495 int Volume::doUnmount(const char *path, bool force) {
499 SLOGD("Unmounting {%s}, force = %d", path, force);
503 if (!umount(path) || errno == EINVAL || errno == ENOENT) {
504 SLOGI("%s sucessfully unmounted", path);
512 action = 2; // SIGKILL
513 } else if (retries == 2) {
514 action = 1; // SIGHUP
518 SLOGW("Failed to unmount %s (%s, retries %d, action %d)",
519 path, strerror(errno), retries, action);
521 Process::killProcessesWithOpenFiles(path, action);
525 SLOGE("Giving up on unmount %s (%s)", path, strerror(errno));
529 int Volume::unmountVol(bool force, bool revert) {
532 int flags = getFlags();
533 bool providesAsec = (flags & VOL_PROVIDES_ASEC) != 0;
535 if (getState() != Volume::State_Mounted) {
536 SLOGE("Volume %s unmount request when not mounted", getLabel());
538 return UNMOUNT_NOT_MOUNTED_ERR;
541 setState(Volume::State_Unmounting);
542 usleep(1000 * 1000); // Give the framework some time to react
545 snprintf(service, 64, "fuse_%s", getLabel());
546 property_set("ctl.stop", service);
547 /* Give it a chance to stop. I wish we had a synchronous way to determine this... */
550 // TODO: determine failure mode if FUSE times out
552 if (providesAsec && doUnmount(Volume::SEC_ASECDIR_EXT, force) != 0) {
553 SLOGE("Failed to unmount secure area on %s (%s)", getMountpoint(), strerror(errno));
557 /* Now that the fuse daemon is dead, unmount it */
558 if (doUnmount(getFuseMountpoint(), force) != 0) {
559 SLOGE("Failed to unmount %s (%s)", getFuseMountpoint(), strerror(errno));
560 goto fail_remount_secure;
563 /* Unmount the real sd card */
564 if (doUnmount(getMountpoint(), force) != 0) {
565 SLOGE("Failed to unmount %s (%s)", getMountpoint(), strerror(errno));
566 goto fail_remount_secure;
569 SLOGI("%s unmounted successfully", getMountpoint());
571 /* If this is an encrypted volume, and we've been asked to undo
572 * the crypto mapping, then revert the dm-crypt mapping, and revert
573 * the device info to the original values.
575 if (revert && isDecrypted()) {
576 cryptfs_revert_volume(getLabel());
578 SLOGI("Encrypted volume %s reverted successfully", getMountpoint());
583 setState(Volume::State_Idle);
584 mCurrentlyMountedKdev = -1;
588 if (providesAsec && mountAsecExternal() != 0) {
589 SLOGE("Failed to remount secure area (%s)", strerror(errno));
594 setState(Volume::State_Mounted);
598 setState(Volume::State_NoMedia);
602 int Volume::initializeMbr(const char *deviceNode) {
603 struct disk_info dinfo;
605 memset(&dinfo, 0, sizeof(dinfo));
607 if (!(dinfo.part_lst = (struct part_info *) malloc(MAX_NUM_PARTS * sizeof(struct part_info)))) {
608 SLOGE("Failed to malloc prt_lst");
612 memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
613 dinfo.device = strdup(deviceNode);
614 dinfo.scheme = PART_SCHEME_MBR;
615 dinfo.sect_size = 512;
616 dinfo.skip_lba = 2048;
620 struct part_info *pinfo = &dinfo.part_lst[0];
622 pinfo->name = strdup("android_sdcard");
623 pinfo->flags |= PART_ACTIVE_FLAG;
624 pinfo->type = PC_PART_TYPE_FAT32;
627 int rc = apply_disk_config(&dinfo, 0);
630 SLOGE("Failed to apply disk configuration (%d)", rc);
637 free(dinfo.part_lst);
643 * Use blkid to extract UUID and label from device, since it handles many
644 * obscure edge cases around partition types and formats. Always broadcasts
645 * updated metadata values.
647 int Volume::extractMetadata(const char* devicePath) {
652 cmd += " -c /dev/null ";
655 FILE* fp = popen(cmd.c_str(), "r");
657 ALOGE("Failed to run %s: %s", cmd.c_str(), strerror(errno));
664 if (fgets(line, sizeof(line), fp) != NULL) {
665 ALOGD("blkid reported: %s", line);
667 char* start = strstr(line, "UUID=") + 5;
668 if (sscanf(start, "\"%127[^\"]\"", value) == 1) {
674 start = strstr(line, "LABEL=") + 6;
675 if (sscanf(start, "\"%127[^\"]\"", value) == 1) {