aboutsummaryrefslogtreecommitdiff
path: root/volume_manager/VolumeManager.cpp
blob: ded6565b1985cd5f3e3b532c4d85d034c5e14e9d (plain)
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
/*
 * Copyright (C) 2008 The Android Open Source Project
 * Copyright (C) 2019 The LineageOS Project
 *
 * 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.
 */

#include <blkid/blkid.h>
#include <dirent.h>
#include <fcntl.h>
#include <fs_mgr.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/types.h>

#define LOG_TAG "VolumeManager"

#include <android-base/logging.h>
#include <cutils/properties.h>

#include <sysutils/NetlinkEvent.h>

#include <volume_manager/VolumeManager.h>
#include <fstab/fstab.h>
#include "Disk.h"
#include "DiskPartition.h"
#include "EmulatedVolume.h"
#include "VolumeBase.h"
#include "NetlinkManager.h"

#include "sehandle.h"

struct selabel_handle* sehandle;

using android::fs_mgr::Fstab;
using android::fs_mgr::FstabEntry;

static const unsigned int kMajorBlockMmc = 179;
static const unsigned int kMajorBlockExperimentalMin = 240;
static const unsigned int kMajorBlockExperimentalMax = 254;

namespace android {
namespace volmgr {

static void do_coldboot(DIR* d, int lvl) {
    struct dirent* de;
    int dfd, fd;

    dfd = dirfd(d);

    fd = openat(dfd, "uevent", O_WRONLY | O_CLOEXEC);
    if (fd >= 0) {
        write(fd, "add\n", 4);
        close(fd);
    }

    while ((de = readdir(d))) {
        DIR* d2;

        if (de->d_name[0] == '.') continue;

        if (de->d_type != DT_DIR && lvl > 0) continue;

        fd = openat(dfd, de->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
        if (fd < 0) continue;

        d2 = fdopendir(fd);
        if (d2 == 0)
            close(fd);
        else {
            do_coldboot(d2, lvl + 1);
            closedir(d2);
        }
    }
}

static void coldboot(const char* path) {
    DIR* d = opendir(path);
    if (d) {
        do_coldboot(d, 0);
        closedir(d);
    }
}

static int process_config(VolumeManager* vm, FstabEntry* data_recp) {
    Fstab fstab;
    if (!ReadDefaultFstab(&fstab)) {
        PLOG(ERROR) << "Failed to open default fstab";
        return -1;
    }

    /* Loop through entries looking for ones that vold manages */
    for (int i = 0; i < fstab.size(); i++) {
        if (fstab[i].fs_mgr_flags.vold_managed) {
            std::string sysPattern(fstab[i].blk_device);
            std::string fstype = fstab[i].fs_type;
            std::string mntopts = fstab[i].fs_options;
            std::string nickname = fstab[i].label;
            int partnum = fstab[i].partnum;
            int flags = 0;

            if (fstab[i].is_encryptable()) {
                flags |= android::volmgr::Disk::Flags::kAdoptable;
            }
            if (fstab[i].fs_mgr_flags.no_emulated_sd ||
                property_get_bool("vold.debug.default_primary", false)) {
                flags |= android::volmgr::Disk::Flags::kDefaultPrimary;
            }
            if (fstab[i].fs_mgr_flags.nonremovable) {
                flags |= android::volmgr::Disk::Flags::kNonRemovable;
            }

            vm->addDiskSource(new VolumeManager::DiskSource(sysPattern, nickname, partnum, flags,
                                                            fstype, mntopts));
        } else {
            if (data_recp->fs_type.empty() && fstab[i].mount_point == "/data") {
                char* detected_fs_type =
                    blkid_get_tag_value(nullptr, "TYPE", fstab[i].blk_device.c_str());
                if (!detected_fs_type || fstab[i].fs_type == detected_fs_type) {
                    *data_recp = fstab[i];
                }
            }
        }
    }
    return 0;
}

VolumeInfo::VolumeInfo(const VolumeBase* vol)
    : mId(vol->getId()), mLabel(vol->getPartLabel()), mPath(vol->getPath()), mMountable(vol->isMountable()) {
    // Empty
}

VolumeManager* VolumeManager::sInstance = nullptr;

VolumeManager* VolumeManager::Instance(void) {
    if (!sInstance) {
        sInstance = new VolumeManager();
    }
    return sInstance;
}

VolumeManager::VolumeManager(void)
    : mWatcher(nullptr), mNetlinkManager(NetlinkManager::Instance()), mInternalEmulated(nullptr) {
    // Empty
}

VolumeManager::~VolumeManager(void) {
    stop();
}

bool VolumeManager::start(VolumeWatcher* watcher) {
    setenv("BLKID_FILE", "/tmp/vold_blkid.tab", 1);

    sehandle = selinux_android_file_context_handle();
    if (sehandle) {
        selinux_android_set_sehandle(sehandle);
    }

    mkdir("/dev/block/volmgr", 0755);

    mWatcher = watcher;

    FstabEntry data_rec;
    if (process_config(this, &data_rec) != 0) {
        LOG(ERROR) << "Error reading configuration... continuing anyway";
    }

    if (!data_rec.fs_type.empty()) {
        mInternalEmulated = new EmulatedVolume(&data_rec, "media/0");
        mInternalEmulated->create();
    }

    if (!mNetlinkManager->start()) {
        LOG(ERROR) << "Unable to start NetlinkManager";
        return false;
    }

    coldboot("/sys/block");

    unmountAll();

    LOG(INFO) << "VolumeManager initialized";
    return true;
}

void VolumeManager::stop(void) {
    for (auto& disk : mDisks) {
        disk->destroy();
        delete disk;
    }
    mDisks.clear();
    for (auto& source : mDiskSources) {
        delete source;
    }
    mDiskSources.clear();

    mNetlinkManager->stop();
    mWatcher = nullptr;
}

bool VolumeManager::reset(void) {
    return false;
}

bool VolumeManager::unmountAll(void) {
    std::lock_guard<std::mutex> lock(mLock);

    if (mInternalEmulated) {
        mInternalEmulated->unmount();
    }

    for (auto& disk : mDisks) {
        disk->unmountAll();
    }

    return true;
}

void VolumeManager::getVolumeInfo(std::vector<VolumeInfo>& info) {
    std::lock_guard<std::mutex> lock(mLock);

    info.clear();
    if (mInternalEmulated) {
        info.push_back(VolumeInfo(mInternalEmulated));
    }
    for (const auto& disk : mDisks) {
        disk->getVolumeInfo(info);
    }
}

VolumeBase* VolumeManager::findVolume(const std::string& id) {
    if (mInternalEmulated && mInternalEmulated->getId() == id) {
        return mInternalEmulated;
    }
    for (const auto& disk : mDisks) {
        auto vol = disk->findVolume(id);
        if (vol != nullptr) {
            return vol.get();
        }
    }
    return nullptr;
}

bool VolumeManager::volumeMount(const std::string& id) {
    std::lock_guard<std::mutex> lock(mLock);
    auto vol = findVolume(id);
    if (!vol) {
        return false;
    }
    status_t res = vol->mount();
    return (res == OK);
}

bool VolumeManager::volumeUnmount(const std::string& id, bool detach /* = false */) {
    std::lock_guard<std::mutex> lock(mLock);
    auto vol = findVolume(id);
    if (!vol) {
        return false;
    }
    status_t res = vol->unmount(detach);
    return (res == OK);
}

void VolumeManager::addDiskSource(DiskSource* source) {
    std::lock_guard<std::mutex> lock(mLock);

    mDiskSources.push_back(source);
}

void VolumeManager::handleBlockEvent(NetlinkEvent* evt) {
    std::lock_guard<std::mutex> lock(mLock);

    const char* param;
    param = evt->findParam("DEVTYPE");
    std::string devType(param ? param : "");
    if (devType != "disk") {
        return;
    }
    param = evt->findParam("DEVPATH");
    std::string eventPath(param ? param : "");

    int major = atoi(evt->findParam("MAJOR"));
    int minor = atoi(evt->findParam("MINOR"));
    dev_t device = makedev(major, minor);

    switch (evt->getAction()) {
        case NetlinkEvent::Action::kAdd: {
            for (const auto& source : mDiskSources) {
                if (source->matches(eventPath)) {
                    // For now, assume that MMC, virtio-blk (the latter is
                    // emulator-specific; see Disk.cpp for details) and UFS card
                    // devices are SD, and that everything else is USB
                    int flags = source->getFlags();
                    if (major == kMajorBlockMmc || (eventPath.find("ufs") != std::string::npos) ||
                        (IsRunningInEmulator() && major >= (int)kMajorBlockExperimentalMin &&
                         major <= (int)kMajorBlockExperimentalMax)) {
                        flags |= Disk::Flags::kSd;
                    } else {
                        flags |= Disk::Flags::kUsb;
                    }

                    Disk* disk = (source->getPartNum() == -1)
                                     ? new Disk(eventPath, device, source->getNickname(), flags)
                                     : new DiskPartition(eventPath, device, source->getNickname(),
                                                         flags, source->getPartNum(),
                                                         source->getFsType(), source->getMntOpts());
                    disk->create();
                    mDisks.push_back(disk);
                    break;
                }
            }
            break;
        }
        case NetlinkEvent::Action::kChange: {
            LOG(DEBUG) << "Disk at " << major << ":" << minor << " changed";
            for (const auto& disk : mDisks) {
                if (disk->getDevice() == device) {
                    disk->readMetadata();
                    disk->readPartitions();
                }
            }
            break;
        }
        case NetlinkEvent::Action::kRemove: {
            auto i = mDisks.begin();
            while (i != mDisks.end()) {
                if ((*i)->getDevice() == device) {
                    (*i)->destroy();
                    i = mDisks.erase(i);
                } else {
                    ++i;
                }
            }
            break;
        }
        default: {
            LOG(WARNING) << "Unexpected block event action " << (int)evt->getAction();
            break;
        }
    }
}

void VolumeManager::notifyEvent(int code) {
    std::vector<std::string> argv;
    notifyEvent(code, argv);
}

void VolumeManager::notifyEvent(int code, const std::string& arg) {
    std::vector<std::string> argv;
    argv.push_back(arg);
    notifyEvent(code, argv);
}

void VolumeManager::notifyEvent(int code, const std::vector<std::string>& argv) {
    mWatcher->handleEvent(code, argv);
}

}  // namespace volmgr
}  // namespace android