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