OSDN Git Service

Merge "Try SO_RCVBUF before SO_RCVBUFFORCE." am: 3f8fa0c215
[android-x86/system-vold.git] / Disk.cpp
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include "Disk.h"
18 #include "PublicVolume.h"
19 #include "PrivateVolume.h"
20 #include "Utils.h"
21 #include "VolumeBase.h"
22 #include "VolumeManager.h"
23 #include "ResponseCode.h"
24 #include "Ext4Crypt.h"
25
26 #include <android-base/file.h>
27 #include <android-base/stringprintf.h>
28 #include <android-base/logging.h>
29 #include <diskconfig/diskconfig.h>
30
31 #include <vector>
32 #include <fcntl.h>
33 #include <inttypes.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/sysmacros.h>
39 #include <sys/mount.h>
40
41 using android::base::ReadFileToString;
42 using android::base::WriteStringToFile;
43 using android::base::StringPrintf;
44
45 namespace android {
46 namespace vold {
47
48 static const char* kSgdiskPath = "/system/bin/sgdisk";
49 static const char* kSgdiskToken = " \t\n";
50
51 static const char* kSysfsLoopMaxMinors = "/sys/module/loop/parameters/max_part";
52 static const char* kSysfsMmcMaxMinors = "/sys/module/mmcblk/parameters/perdev_minors";
53
54 static const unsigned int kMajorBlockLoop = 7;
55 static const unsigned int kMajorBlockScsiA = 8;
56 static const unsigned int kMajorBlockScsiB = 65;
57 static const unsigned int kMajorBlockScsiC = 66;
58 static const unsigned int kMajorBlockScsiD = 67;
59 static const unsigned int kMajorBlockScsiE = 68;
60 static const unsigned int kMajorBlockScsiF = 69;
61 static const unsigned int kMajorBlockScsiG = 70;
62 static const unsigned int kMajorBlockScsiH = 71;
63 static const unsigned int kMajorBlockScsiI = 128;
64 static const unsigned int kMajorBlockScsiJ = 129;
65 static const unsigned int kMajorBlockScsiK = 130;
66 static const unsigned int kMajorBlockScsiL = 131;
67 static const unsigned int kMajorBlockScsiM = 132;
68 static const unsigned int kMajorBlockScsiN = 133;
69 static const unsigned int kMajorBlockScsiO = 134;
70 static const unsigned int kMajorBlockScsiP = 135;
71 static const unsigned int kMajorBlockMmc = 179;
72 static const unsigned int kMajorBlockExperimentalMin = 240;
73 static const unsigned int kMajorBlockExperimentalMax = 254;
74
75 static const char* kGptBasicData = "EBD0A0A2-B9E5-4433-87C0-68B6B72699C7";
76 static const char* kGptAndroidMeta = "19A710A2-B3CA-11E4-B026-10604B889DCF";
77 static const char* kGptAndroidExpand = "193D1EA4-B3CA-11E4-B075-10604B889DCF";
78
79 enum class Table {
80     kUnknown,
81     kMbr,
82     kGpt,
83 };
84
85 static bool isVirtioBlkDevice(unsigned int major) {
86     /*
87      * The new emulator's "ranchu" virtual board no longer includes a goldfish
88      * MMC-based SD card device; instead, it emulates SD cards with virtio-blk,
89      * which has been supported by upstream kernel and QEMU for quite a while.
90      * Unfortunately, the virtio-blk block device driver does not use a fixed
91      * major number, but relies on the kernel to assign one from a specific
92      * range of block majors, which are allocated for "LOCAL/EXPERIMENAL USE"
93      * per Documentation/devices.txt. This is true even for the latest Linux
94      * kernel (4.4; see init() in drivers/block/virtio_blk.c).
95      *
96      * This makes it difficult for vold to detect a virtio-blk based SD card.
97      * The current solution checks two conditions (both must be met):
98      *
99      *  a) If the running environment is the emulator;
100      *  b) If the major number is an experimental block device major number (for
101      *     x86/x86_64 3.10 ranchu kernels, virtio-blk always gets major number
102      *     253, but it is safer to match the range than just one value).
103      *
104      * Other conditions could be used, too, e.g. the hardware name should be
105      * "ranchu", the device's sysfs path should end with "/block/vd[d-z]", etc.
106      * But just having a) and b) is enough for now.
107      */
108     return IsRunningInEmulator() && major >= kMajorBlockExperimentalMin
109             && major <= kMajorBlockExperimentalMax;
110 }
111
112 Disk::Disk(const std::string& eventPath, dev_t device,
113         const std::string& nickname, int flags) :
114         mDevice(device), mSize(-1), mNickname(nickname), mFlags(flags), mCreated(
115                 false), mJustPartitioned(false) {
116     mId = StringPrintf("disk:%u,%u", major(device), minor(device));
117     mEventPath = eventPath;
118     mSysPath = StringPrintf("/sys/%s", eventPath.c_str());
119     mDevPath = StringPrintf("/dev/block/vold/%s", mId.c_str());
120     CreateDeviceNode(mDevPath, mDevice);
121 }
122
123 Disk::~Disk() {
124     CHECK(!mCreated);
125     DestroyDeviceNode(mDevPath);
126 }
127
128 std::shared_ptr<VolumeBase> Disk::findVolume(const std::string& id) {
129     for (auto vol : mVolumes) {
130         if (vol->getId() == id) {
131             return vol;
132         }
133         auto stackedVol = vol->findVolume(id);
134         if (stackedVol != nullptr) {
135             return stackedVol;
136         }
137     }
138     return nullptr;
139 }
140
141 void Disk::listVolumes(VolumeBase::Type type, std::list<std::string>& list) {
142     for (const auto& vol : mVolumes) {
143         if (vol->getType() == type) {
144             list.push_back(vol->getId());
145         }
146         // TODO: consider looking at stacked volumes
147     }
148 }
149
150 status_t Disk::create() {
151     CHECK(!mCreated);
152     mCreated = true;
153     notifyEvent(ResponseCode::DiskCreated, StringPrintf("%d", mFlags));
154     readMetadata();
155     readPartitions();
156     return OK;
157 }
158
159 status_t Disk::destroy() {
160     CHECK(mCreated);
161     destroyAllVolumes();
162     mCreated = false;
163     notifyEvent(ResponseCode::DiskDestroyed);
164     return OK;
165 }
166
167 void Disk::createPublicVolume(dev_t device) {
168     auto vol = std::shared_ptr<VolumeBase>(new PublicVolume(device));
169     if (mJustPartitioned) {
170         LOG(DEBUG) << "Device just partitioned; silently formatting";
171         vol->setSilent(true);
172         vol->create();
173         vol->format("auto");
174         vol->destroy();
175         vol->setSilent(false);
176     }
177
178     mVolumes.push_back(vol);
179     vol->setDiskId(getId());
180     vol->create();
181 }
182
183 void Disk::createPrivateVolume(dev_t device, const std::string& partGuid) {
184     std::string normalizedGuid;
185     if (NormalizeHex(partGuid, normalizedGuid)) {
186         LOG(WARNING) << "Invalid GUID " << partGuid;
187         return;
188     }
189
190     std::string keyRaw;
191     if (!ReadFileToString(BuildKeyPath(normalizedGuid), &keyRaw)) {
192         PLOG(ERROR) << "Failed to load key for GUID " << normalizedGuid;
193         return;
194     }
195
196     LOG(DEBUG) << "Found key for GUID " << normalizedGuid;
197
198     auto vol = std::shared_ptr<VolumeBase>(new PrivateVolume(device, keyRaw));
199     if (mJustPartitioned) {
200         LOG(DEBUG) << "Device just partitioned; silently formatting";
201         vol->setSilent(true);
202         vol->create();
203         vol->format("auto");
204         vol->destroy();
205         vol->setSilent(false);
206     }
207
208     mVolumes.push_back(vol);
209     vol->setDiskId(getId());
210     vol->setPartGuid(partGuid);
211     vol->create();
212 }
213
214 void Disk::destroyAllVolumes() {
215     for (const auto& vol : mVolumes) {
216         vol->destroy();
217     }
218     mVolumes.clear();
219 }
220
221 status_t Disk::readMetadata() {
222     mSize = -1;
223     mLabel.clear();
224
225     int fd = open(mDevPath.c_str(), O_RDONLY | O_CLOEXEC);
226     if (fd != -1) {
227         if (ioctl(fd, BLKGETSIZE64, &mSize)) {
228             mSize = -1;
229         }
230         close(fd);
231     }
232
233     unsigned int majorId = major(mDevice);
234     switch (majorId) {
235     case kMajorBlockLoop: {
236         mLabel = "Virtual";
237         break;
238     }
239     case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
240     case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
241     case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
242     case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
243         std::string path(mSysPath + "/device/vendor");
244         std::string tmp;
245         if (!ReadFileToString(path, &tmp)) {
246             PLOG(WARNING) << "Failed to read vendor from " << path;
247             return -errno;
248         }
249         mLabel = tmp;
250         break;
251     }
252     case kMajorBlockMmc: {
253         std::string path(mSysPath + "/device/manfid");
254         std::string tmp;
255         if (!ReadFileToString(path, &tmp)) {
256             PLOG(WARNING) << "Failed to read manufacturer from " << path;
257             return -errno;
258         }
259         uint64_t manfid = strtoll(tmp.c_str(), nullptr, 16);
260         // Our goal here is to give the user a meaningful label, ideally
261         // matching whatever is silk-screened on the card.  To reduce
262         // user confusion, this list doesn't contain white-label manfid.
263         switch (manfid) {
264         case 0x000003: mLabel = "SanDisk"; break;
265         case 0x00001b: mLabel = "Samsung"; break;
266         case 0x000028: mLabel = "Lexar"; break;
267         case 0x000074: mLabel = "Transcend"; break;
268         }
269         break;
270     }
271     default: {
272         if (isVirtioBlkDevice(majorId)) {
273             LOG(DEBUG) << "Recognized experimental block major ID " << majorId
274                     << " as virtio-blk (emulator's virtual SD card device)";
275             mLabel = "Virtual";
276             break;
277         }
278         LOG(WARNING) << "Unsupported block major type " << majorId;
279         return -ENOTSUP;
280     }
281     }
282
283     notifyEvent(ResponseCode::DiskSizeChanged, StringPrintf("%" PRIu64, mSize));
284     notifyEvent(ResponseCode::DiskLabelChanged, mLabel);
285     notifyEvent(ResponseCode::DiskSysPathChanged, mSysPath);
286     return OK;
287 }
288
289 status_t Disk::readPartitions() {
290     int8_t maxMinors = getMaxMinors();
291     if (maxMinors < 0) {
292         return -ENOTSUP;
293     }
294
295     destroyAllVolumes();
296
297     // Parse partition table
298
299     std::vector<std::string> cmd;
300     cmd.push_back(kSgdiskPath);
301     cmd.push_back("--android-dump");
302     cmd.push_back(mDevPath);
303
304     std::vector<std::string> output;
305     status_t res = ForkExecvp(cmd, output);
306     if (res != OK) {
307         LOG(WARNING) << "sgdisk failed to scan " << mDevPath;
308         notifyEvent(ResponseCode::DiskScanned);
309         mJustPartitioned = false;
310         return res;
311     }
312
313     Table table = Table::kUnknown;
314     bool foundParts = false;
315     for (const auto& line : output) {
316         char* cline = (char*) line.c_str();
317         char* token = strtok(cline, kSgdiskToken);
318         if (token == nullptr) continue;
319
320         if (!strcmp(token, "DISK")) {
321             const char* type = strtok(nullptr, kSgdiskToken);
322             if (!strcmp(type, "mbr")) {
323                 table = Table::kMbr;
324             } else if (!strcmp(type, "gpt")) {
325                 table = Table::kGpt;
326             }
327         } else if (!strcmp(token, "PART")) {
328             foundParts = true;
329             int i = strtol(strtok(nullptr, kSgdiskToken), nullptr, 10);
330             if (i <= 0 || i > maxMinors) {
331                 LOG(WARNING) << mId << " is ignoring partition " << i
332                         << " beyond max supported devices";
333                 continue;
334             }
335             dev_t partDevice = makedev(major(mDevice), minor(mDevice) + i);
336
337             if (table == Table::kMbr) {
338                 const char* type = strtok(nullptr, kSgdiskToken);
339
340                 switch (strtol(type, nullptr, 16)) {
341                 case 0x06: // FAT16
342                 case 0x0b: // W95 FAT32 (LBA)
343                 case 0x0c: // W95 FAT32 (LBA)
344                 case 0x0e: // W95 FAT16 (LBA)
345                     createPublicVolume(partDevice);
346                     break;
347                 }
348             } else if (table == Table::kGpt) {
349                 const char* typeGuid = strtok(nullptr, kSgdiskToken);
350                 const char* partGuid = strtok(nullptr, kSgdiskToken);
351
352                 if (!strcasecmp(typeGuid, kGptBasicData)) {
353                     createPublicVolume(partDevice);
354                 } else if (!strcasecmp(typeGuid, kGptAndroidExpand)) {
355                     createPrivateVolume(partDevice, partGuid);
356                 }
357             }
358         }
359     }
360
361     // Ugly last ditch effort, treat entire disk as partition
362     if (table == Table::kUnknown || !foundParts) {
363         LOG(WARNING) << mId << " has unknown partition table; trying entire device";
364
365         std::string fsType;
366         std::string unused;
367         if (ReadMetadataUntrusted(mDevPath, fsType, unused, unused) == OK) {
368             createPublicVolume(mDevice);
369         } else {
370             LOG(WARNING) << mId << " failed to identify, giving up";
371         }
372     }
373
374     notifyEvent(ResponseCode::DiskScanned);
375     mJustPartitioned = false;
376     return OK;
377 }
378
379 status_t Disk::unmountAll() {
380     for (const auto& vol : mVolumes) {
381         vol->unmount();
382     }
383     return OK;
384 }
385
386 status_t Disk::partitionPublic() {
387     int res;
388
389     // TODO: improve this code
390     destroyAllVolumes();
391     mJustPartitioned = true;
392
393     // First nuke any existing partition table
394     std::vector<std::string> cmd;
395     cmd.push_back(kSgdiskPath);
396     cmd.push_back("--zap-all");
397     cmd.push_back(mDevPath);
398
399     // Zap sometimes returns an error when it actually succeeded, so
400     // just log as warning and keep rolling forward.
401     if ((res = ForkExecvp(cmd)) != 0) {
402         LOG(WARNING) << "Failed to zap; status " << res;
403     }
404
405     struct disk_info dinfo;
406     memset(&dinfo, 0, sizeof(dinfo));
407
408     if (!(dinfo.part_lst = (struct part_info *) malloc(
409             MAX_NUM_PARTS * sizeof(struct part_info)))) {
410         return -1;
411     }
412
413     memset(dinfo.part_lst, 0, MAX_NUM_PARTS * sizeof(struct part_info));
414     dinfo.device = strdup(mDevPath.c_str());
415     dinfo.scheme = PART_SCHEME_MBR;
416     dinfo.sect_size = 512;
417     dinfo.skip_lba = 2048;
418     dinfo.num_lba = 0;
419     dinfo.num_parts = 1;
420
421     struct part_info *pinfo = &dinfo.part_lst[0];
422
423     pinfo->name = strdup("android_sdcard");
424     pinfo->flags |= PART_ACTIVE_FLAG;
425     pinfo->type = PC_PART_TYPE_FAT32;
426     pinfo->len_kb = -1;
427
428     int rc = apply_disk_config(&dinfo, 0);
429     if (rc) {
430         LOG(ERROR) << "Failed to apply disk configuration: " << rc;
431         goto out;
432     }
433
434 out:
435     free(pinfo->name);
436     free(dinfo.device);
437     free(dinfo.part_lst);
438
439     return rc;
440 }
441
442 status_t Disk::partitionPrivate() {
443     return partitionMixed(0);
444 }
445
446 status_t Disk::partitionMixed(int8_t ratio) {
447     int res;
448
449     if (e4crypt_is_native()) {
450         LOG(ERROR) << "Private volumes not yet supported on FBE devices";
451         return -EINVAL;
452     }
453
454     destroyAllVolumes();
455     mJustPartitioned = true;
456
457     // First nuke any existing partition table
458     std::vector<std::string> cmd;
459     cmd.push_back(kSgdiskPath);
460     cmd.push_back("--zap-all");
461     cmd.push_back(mDevPath);
462
463     // Zap sometimes returns an error when it actually succeeded, so
464     // just log as warning and keep rolling forward.
465     if ((res = ForkExecvp(cmd)) != 0) {
466         LOG(WARNING) << "Failed to zap; status " << res;
467     }
468
469     // We've had some success above, so generate both the private partition
470     // GUID and encryption key and persist them.
471     std::string partGuidRaw;
472     std::string keyRaw;
473     if (ReadRandomBytes(16, partGuidRaw) || ReadRandomBytes(16, keyRaw)) {
474         LOG(ERROR) << "Failed to generate GUID or key";
475         return -EIO;
476     }
477
478     std::string partGuid;
479     StrToHex(partGuidRaw, partGuid);
480
481     if (!WriteStringToFile(keyRaw, BuildKeyPath(partGuid))) {
482         LOG(ERROR) << "Failed to persist key";
483         return -EIO;
484     } else {
485         LOG(DEBUG) << "Persisted key for GUID " << partGuid;
486     }
487
488     // Now let's build the new GPT table. We heavily rely on sgdisk to
489     // force optimal alignment on the created partitions.
490     cmd.clear();
491     cmd.push_back(kSgdiskPath);
492
493     // If requested, create a public partition first. Mixed-mode partitioning
494     // like this is an experimental feature.
495     if (ratio > 0) {
496         if (ratio < 10 || ratio > 90) {
497             LOG(ERROR) << "Mixed partition ratio must be between 10-90%";
498             return -EINVAL;
499         }
500
501         uint64_t splitMb = ((mSize / 100) * ratio) / 1024 / 1024;
502         cmd.push_back(StringPrintf("--new=0:0:+%" PRId64 "M", splitMb));
503         cmd.push_back(StringPrintf("--typecode=0:%s", kGptBasicData));
504         cmd.push_back("--change-name=0:shared");
505     }
506
507     // Define a metadata partition which is designed for future use; there
508     // should only be one of these per physical device, even if there are
509     // multiple private volumes.
510     cmd.push_back("--new=0:0:+16M");
511     cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidMeta));
512     cmd.push_back("--change-name=0:android_meta");
513
514     // Define a single private partition filling the rest of disk.
515     cmd.push_back("--new=0:0:-0");
516     cmd.push_back(StringPrintf("--typecode=0:%s", kGptAndroidExpand));
517     cmd.push_back(StringPrintf("--partition-guid=0:%s", partGuid.c_str()));
518     cmd.push_back("--change-name=0:android_expand");
519
520     cmd.push_back(mDevPath);
521
522     if ((res = ForkExecvp(cmd)) != 0) {
523         LOG(ERROR) << "Failed to partition; status " << res;
524         return res;
525     }
526
527     return OK;
528 }
529
530 void Disk::notifyEvent(int event) {
531     VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
532             getId().c_str(), false);
533 }
534
535 void Disk::notifyEvent(int event, const std::string& value) {
536     VolumeManager::Instance()->getBroadcaster()->sendBroadcast(event,
537             StringPrintf("%s %s", getId().c_str(), value.c_str()).c_str(), false);
538 }
539
540 int Disk::getMaxMinors() {
541     // Figure out maximum partition devices supported
542     unsigned int majorId = major(mDevice);
543     switch (majorId) {
544     case kMajorBlockLoop: {
545         std::string tmp;
546         if (!ReadFileToString(kSysfsLoopMaxMinors, &tmp)) {
547             LOG(ERROR) << "Failed to read max minors";
548             return -errno;
549         }
550         return atoi(tmp.c_str());
551     }
552     case kMajorBlockScsiA: case kMajorBlockScsiB: case kMajorBlockScsiC: case kMajorBlockScsiD:
553     case kMajorBlockScsiE: case kMajorBlockScsiF: case kMajorBlockScsiG: case kMajorBlockScsiH:
554     case kMajorBlockScsiI: case kMajorBlockScsiJ: case kMajorBlockScsiK: case kMajorBlockScsiL:
555     case kMajorBlockScsiM: case kMajorBlockScsiN: case kMajorBlockScsiO: case kMajorBlockScsiP: {
556         // Per Documentation/devices.txt this is static
557         return 15;
558     }
559     case kMajorBlockMmc: {
560         // Per Documentation/devices.txt this is dynamic
561         std::string tmp;
562         if (!ReadFileToString(kSysfsMmcMaxMinors, &tmp)) {
563             LOG(ERROR) << "Failed to read max minors";
564             return -errno;
565         }
566         return atoi(tmp.c_str());
567     }
568     default: {
569         if (isVirtioBlkDevice(majorId)) {
570             // drivers/block/virtio_blk.c has "#define PART_BITS 4", so max is
571             // 2^4 - 1 = 15
572             return 15;
573         }
574     }
575     }
576
577     LOG(ERROR) << "Unsupported block major type " << majorId;
578     return -ENOTSUP;
579 }
580
581 }  // namespace vold
582 }  // namespace android