blob: 238e529e2db189c0eefdcb45cc7ae68d5652c116 [file] [log] [blame]
srs5694add79a62010-01-26 15:59:58 -05001//
2// C++ Interface: diskio (Unix components [Linux, FreeBSD, Mac OS X])
3//
4// Description: Class to handle low-level disk I/O for GPT fdisk
5//
6//
7// Author: Rod Smith <rodsmith@rodsbooks.com>, (C) 2009
8//
9// Copyright: See COPYING file that comes with this distribution
10//
11//
12// This program is copyright (c) 2009 by Roderick W. Smith. It is distributed
13// under the terms of the GNU GPL version 2, as detailed in the COPYING file.
14
15#define __STDC_LIMIT_MACROS
16#define __STDC_CONSTANT_MACROS
17
18#include <sys/ioctl.h>
srs5694fed16d02010-01-27 23:03:40 -050019#include <string.h>
srs5694add79a62010-01-26 15:59:58 -050020#include <string>
21#include <stdint.h>
22#include <errno.h>
23#include <fcntl.h>
24#include <sys/stat.h>
srs5694bf8950c2011-03-12 01:23:12 -050025
26#ifdef __linux__
27#include "linux/hdreg.h"
28#endif
29
srs5694add79a62010-01-26 15:59:58 -050030#include <iostream>
31
srs5694add79a62010-01-26 15:59:58 -050032#include "diskio.h"
33
34using namespace std;
35
36// Returns the official "real" name for a shortened version of same.
37// Trivial here; more important in Windows
38void DiskIO::MakeRealName(void) {
39 realFilename = userFilename;
40} // DiskIO::MakeRealName()
41
srs569455d92612010-03-07 22:16:07 -050042// Open the currently on-record file for reading. Returns 1 if the file is
43// already open or is opened by this call, 0 if opening the file doesn't
44// work.
srs5694add79a62010-01-26 15:59:58 -050045int DiskIO::OpenForRead(void) {
46 int shouldOpen = 1;
srs56948f1b2d62010-05-23 13:07:19 -040047 struct stat64 st;
srs5694add79a62010-01-26 15:59:58 -050048
49 if (isOpen) { // file is already open
50 if (openForWrite) {
51 Close();
52 } else {
53 shouldOpen = 0;
54 } // if/else
55 } // if
56
57 if (shouldOpen) {
58 fd = open(realFilename.c_str(), O_RDONLY);
59 if (fd == -1) {
srs569455d92612010-03-07 22:16:07 -050060 cerr << "Problem opening " << realFilename << " for reading! Error is " << errno << ".\n";
61 if (errno == EACCES) // User is probably not running as root
srs5694fed16d02010-01-27 23:03:40 -050062 cerr << "You must run this program as root or use sudo!\n";
srs569455d92612010-03-07 22:16:07 -050063 if (errno == ENOENT)
64 cerr << "The specified file does not exist!\n";
srs5694add79a62010-01-26 15:59:58 -050065 realFilename = "";
66 userFilename = "";
67 isOpen = 0;
68 openForWrite = 0;
69 } else {
srs56948f1b2d62010-05-23 13:07:19 -040070 isOpen = 0;
srs5694add79a62010-01-26 15:59:58 -050071 openForWrite = 0;
srs56948f1b2d62010-05-23 13:07:19 -040072 if (fstat64(fd, &st) == 0) {
73 if (S_ISDIR(st.st_mode))
74 cerr << "The specified path is a directory!\n";
75#ifndef __FreeBSD__
76 else if (S_ISCHR(st.st_mode))
77 cerr << "The specified path is a character device!\n";
78#endif
79 else if (S_ISFIFO(st.st_mode))
80 cerr << "The specified path is a FIFO!\n";
81 else if (S_ISSOCK(st.st_mode))
82 cerr << "The specified path is a socket!\n";
83 else
84 isOpen = 1;
85 } // if (fstat64()...)
srs5694add79a62010-01-26 15:59:58 -050086 } // if/else
87 } // if
88
89 return isOpen;
90} // DiskIO::OpenForRead(void)
91
92// An extended file-open function. This includes some system-specific checks.
93// Returns 1 if the file is open, 0 otherwise....
94int DiskIO::OpenForWrite(void) {
95 if ((isOpen) && (openForWrite))
96 return 1;
97
98 // Close the disk, in case it's already open for reading only....
99 Close();
100
101 // try to open the device; may fail....
102 fd = open(realFilename.c_str(), O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
103#ifdef __APPLE__
104 // MacOS X requires a shared lock under some circumstances....
105 if (fd < 0) {
srs5694fed16d02010-01-27 23:03:40 -0500106 fd = open(realFilename.c_str(), O_WRONLY | O_SHLOCK);
srs5694add79a62010-01-26 15:59:58 -0500107 } // if
108#endif
109 if (fd >= 0) {
110 isOpen = 1;
111 openForWrite = 1;
112 } else {
113 isOpen = 0;
114 openForWrite = 0;
115 } // if/else
116 return isOpen;
117} // DiskIO::OpenForWrite(void)
118
119// Close the disk device. Note that this does NOT erase the stored filenames,
120// so the file can be re-opened without specifying the filename.
121void DiskIO::Close(void) {
122 if (isOpen)
srs569408bb0da2010-02-19 17:19:55 -0500123 if (close(fd) < 0)
124 cerr << "Warning! Problem closing file!\n";
srs5694add79a62010-01-26 15:59:58 -0500125 isOpen = 0;
126 openForWrite = 0;
127} // DiskIO::Close()
128
129// Returns block size of device pointed to by fd file descriptor. If the ioctl
130// returns an error condition, print a warning but return a value of SECTOR_SIZE
srs569455d92612010-03-07 22:16:07 -0500131// (512). If the disk can't be opened at all, return a value of 0.
srs5694add79a62010-01-26 15:59:58 -0500132int DiskIO::GetBlockSize(void) {
133 int err = -1, blockSize = 0;
134
135 // If disk isn't open, try to open it....
136 if (!isOpen) {
137 OpenForRead();
138 } // if
139
140 if (isOpen) {
141#ifdef __APPLE__
142 err = ioctl(fd, DKIOCGETBLOCKSIZE, &blockSize);
143#endif
srs569408bb0da2010-02-19 17:19:55 -0500144#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694add79a62010-01-26 15:59:58 -0500145 err = ioctl(fd, DIOCGSECTORSIZE, &blockSize);
146#endif
147#ifdef __linux__
148 err = ioctl(fd, BLKSSZGET, &blockSize);
149#endif
150
151 if (err == -1) {
152 blockSize = SECTOR_SIZE;
153 // ENOTTY = inappropriate ioctl; probably being called on a disk image
154 // file, so don't display the warning message....
155 // 32-bit code returns EINVAL, I don't know why. I know I'm treading on
156 // thin ice here, but it should be OK in all but very weird cases....
157 if ((errno != ENOTTY) && (errno != EINVAL)) {
srs5694fed16d02010-01-27 23:03:40 -0500158 cerr << "\aError " << errno << " when determining sector size! Setting sector size to "
159 << SECTOR_SIZE << "\n";
srs569455d92612010-03-07 22:16:07 -0500160 cout << "Disk device is " << realFilename << "\n";
srs5694add79a62010-01-26 15:59:58 -0500161 } // if
162 } // if (err == -1)
163 } // if (isOpen)
164
165 return (blockSize);
166} // DiskIO::GetBlockSize()
167
srs5694bf8950c2011-03-12 01:23:12 -0500168// Returns the number of heads, according to the kernel, or 255 if the
169// correct value can't be determined.
170uint32_t DiskIO::GetNumHeads(void) {
171 uint32_t numHeads = 255;
172
173#ifdef HDIO_GETGEO
174 struct hd_geometry geometry;
175
176 // If disk isn't open, try to open it....
177 if (!isOpen)
178 OpenForRead();
179
180 if (!ioctl(fd, HDIO_GETGEO, &geometry))
181 numHeads = (uint32_t) geometry.heads;
182#endif
183 return numHeads;
184} // DiskIO::GetNumHeads();
185
186// Returns the number of sectors per track, according to the kernel, or 63
187// if the correct value can't be determined.
188uint32_t DiskIO::GetNumSecsPerTrack(void) {
189 uint32_t numSecs = 63;
190
191 #ifdef HDIO_GETGEO
192 struct hd_geometry geometry;
193
194 // If disk isn't open, try to open it....
195 if (!isOpen)
196 OpenForRead();
197
198 if (!ioctl(fd, HDIO_GETGEO, &geometry))
199 numSecs = (uint32_t) geometry.sectors;
200 #endif
201 return numSecs;
202} // DiskIO::GetNumSecsPerTrack()
203
srs5694add79a62010-01-26 15:59:58 -0500204// Resync disk caches so the OS uses the new partition table. This code varies
205// a lot from one OS to another.
206void DiskIO::DiskSync(void) {
207 int i, platformFound = 0;
208
209 // If disk isn't open, try to open it....
210 if (!isOpen) {
211 OpenForRead();
212 } // if
213
214 if (isOpen) {
215 sync();
216#ifdef __APPLE__
srs5694fed16d02010-01-27 23:03:40 -0500217 cout << "Warning: The kernel may continue to use old or deleted partitions.\n"
218 << "You should reboot or remove the drive.\n";
srs5694add79a62010-01-26 15:59:58 -0500219 /* don't know if this helps
220 * it definitely will get things on disk though:
221 * http://topiks.org/mac-os-x/0321278542/ch12lev1sec8.html */
222 i = ioctl(fd, DKIOCSYNCHRONIZECACHE);
223 platformFound++;
224#endif
srs569408bb0da2010-02-19 17:19:55 -0500225#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694add79a62010-01-26 15:59:58 -0500226 sleep(2);
227 i = ioctl(fd, DIOCGFLUSH);
srs5694fed16d02010-01-27 23:03:40 -0500228 cout << "Warning: The kernel may continue to use old or deleted partitions.\n"
229 << "You should reboot or remove the drive.\n";
srs5694add79a62010-01-26 15:59:58 -0500230 platformFound++;
231#endif
232#ifdef __linux__
233 sleep(2);
234 i = ioctl(fd, BLKRRPART);
235 if (i)
srs5694fed16d02010-01-27 23:03:40 -0500236 cout << "Warning: The kernel is still using the old partition table.\n"
237 << "The new table will be used at the next reboot.\n";
srs5694add79a62010-01-26 15:59:58 -0500238 platformFound++;
239#endif
240 if (platformFound == 0)
srs5694fed16d02010-01-27 23:03:40 -0500241 cerr << "Warning: Platform not recognized!\n";
srs5694add79a62010-01-26 15:59:58 -0500242 if (platformFound > 1)
srs5694fed16d02010-01-27 23:03:40 -0500243 cerr << "\nWarning: We seem to be running on multiple platforms!\n";
srs5694add79a62010-01-26 15:59:58 -0500244 } // if (isOpen)
245} // DiskIO::DiskSync()
246
247// Seek to the specified sector. Returns 1 on success, 0 on failure.
srs5694cb76c672010-02-11 22:22:22 -0500248// Note that seeking beyond the end of the file is NOT detected as a failure!
srs5694add79a62010-01-26 15:59:58 -0500249int DiskIO::Seek(uint64_t sector) {
250 int retval = 1;
251 off_t seekTo, sought;
252
253 // If disk isn't open, try to open it....
254 if (!isOpen) {
255 retval = OpenForRead();
256 } // if
257
258 if (isOpen) {
259 seekTo = sector * (uint64_t) GetBlockSize();
260 sought = lseek64(fd, seekTo, SEEK_SET);
261 if (sought != seekTo) {
262 retval = 0;
263 } // if
264 } // if
265 return retval;
266} // DiskIO::Seek()
267
268// A variant on the standard read() function. Done to work around
269// limitations in FreeBSD concerning the matching of the sector
270// size with the number of bytes read.
271// Returns the number of bytes read into buffer.
272int DiskIO::Read(void* buffer, int numBytes) {
srs5694cb76c672010-02-11 22:22:22 -0500273 int blockSize, numBlocks, retval = 0;
srs5694add79a62010-01-26 15:59:58 -0500274 char* tempSpace;
275
276 // If disk isn't open, try to open it....
277 if (!isOpen) {
278 OpenForRead();
279 } // if
280
281 if (isOpen) {
282 // Compute required space and allocate memory
283 blockSize = GetBlockSize();
284 if (numBytes <= blockSize) {
285 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500286 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500287 } else {
288 numBlocks = numBytes / blockSize;
srs5694cb76c672010-02-11 22:22:22 -0500289 if ((numBytes % blockSize) != 0)
290 numBlocks++;
291 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500292 } // if/else
293
294 // Read the data into temporary space, then copy it to buffer
295 retval = read(fd, tempSpace, numBlocks * blockSize);
296 memcpy(buffer, tempSpace, numBytes);
srs5694add79a62010-01-26 15:59:58 -0500297
298 // Adjust the return value, if necessary....
299 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
300 retval = numBytes;
301
srs5694cb76c672010-02-11 22:22:22 -0500302 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500303 } // if (isOpen)
304 return retval;
305} // DiskIO::Read()
306
307// A variant on the standard write() function. Done to work around
308// limitations in FreeBSD concerning the matching of the sector
309// size with the number of bytes read.
310// Returns the number of bytes written.
311int DiskIO::Write(void* buffer, int numBytes) {
312 int blockSize = 512, i, numBlocks, retval = 0;
313 char* tempSpace;
314
315 // If disk isn't open, try to open it....
316 if ((!isOpen) || (!openForWrite)) {
317 OpenForWrite();
318 } // if
319
320 if (isOpen) {
321 // Compute required space and allocate memory
322 blockSize = GetBlockSize();
323 if (numBytes <= blockSize) {
324 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500325 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500326 } else {
327 numBlocks = numBytes / blockSize;
328 if ((numBytes % blockSize) != 0) numBlocks++;
srs5694cb76c672010-02-11 22:22:22 -0500329 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500330 } // if/else
331
332 // Copy the data to my own buffer, then write it
srs5694add79a62010-01-26 15:59:58 -0500333 memcpy(tempSpace, buffer, numBytes);
334 for (i = numBytes; i < numBlocks * blockSize; i++) {
335 tempSpace[i] = 0;
336 } // for
337 retval = write(fd, tempSpace, numBlocks * blockSize);
338
339 // Adjust the return value, if necessary....
340 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
341 retval = numBytes;
342
srs5694cb76c672010-02-11 22:22:22 -0500343 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500344 } // if (isOpen)
345 return retval;
346} // DiskIO:Write()
347
348/**************************************************************************************
349 * *
350 * Below functions are lifted from various sources, as documented in comments before *
351 * each one. *
352 * *
353 **************************************************************************************/
354
355// The disksize function is taken from the Linux fdisk code and modified
356// greatly since then to enable FreeBSD and MacOS support, as well as to
357// return correct values for disk image files.
358uint64_t DiskIO::DiskSize(int *err) {
srs5694add79a62010-01-26 15:59:58 -0500359 uint64_t sectors = 0; // size in sectors
360 off_t bytes = 0; // size in bytes
361 struct stat64 st;
362 int platformFound = 0;
363
364 // If disk isn't open, try to open it....
365 if (!isOpen) {
366 OpenForRead();
367 } // if
368
369 if (isOpen) {
370 // Note to self: I recall testing a simplified version of
371 // this code, similar to what's in the __APPLE__ block,
372 // on Linux, but I had some problems. IIRC, it ran OK on 32-bit
373 // systems but not on 64-bit. Keep this in mind in case of
374 // 32/64-bit issues on MacOS....
375#ifdef __APPLE__
376 *err = ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors);
377 platformFound++;
378#endif
srs569408bb0da2010-02-19 17:19:55 -0500379#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694add79a62010-01-26 15:59:58 -0500380 *err = ioctl(fd, DIOCGMEDIASIZE, &bytes);
srs569408bb0da2010-02-19 17:19:55 -0500381 long long b = GetBlockSize();
srs5694add79a62010-01-26 15:59:58 -0500382 sectors = bytes / b;
383 platformFound++;
384#endif
385#ifdef __linux__
srs569408bb0da2010-02-19 17:19:55 -0500386 long sz;
387 long long b;
srs5694add79a62010-01-26 15:59:58 -0500388 *err = ioctl(fd, BLKGETSIZE, &sz);
389 if (*err) {
390 sectors = sz = 0;
391 } // if
srs569464cbd172011-03-01 22:03:54 -0500392 if ((!*err) || (errno == EFBIG)) {
srs5694add79a62010-01-26 15:59:58 -0500393 *err = ioctl(fd, BLKGETSIZE64, &b);
394 if (*err || b == 0 || b == sz)
395 sectors = sz;
396 else
397 sectors = (b >> 9);
398 } // if
399 // Unintuitively, the above returns values in 512-byte blocks, no
400 // matter what the underlying device's block size. Correct for this....
401 sectors /= (GetBlockSize() / 512);
402 platformFound++;
403#endif
404 if (platformFound != 1)
srs5694fed16d02010-01-27 23:03:40 -0500405 cerr << "Warning! We seem to be running on no known platform!\n";
srs5694add79a62010-01-26 15:59:58 -0500406
407 // The above methods have failed, so let's assume it's a regular
408 // file (a QEMU image, dd backup, or what have you) and see what
409 // fstat() gives us....
410 if ((sectors == 0) || (*err == -1)) {
411 if (fstat64(fd, &st) == 0) {
412 bytes = (off_t) st.st_size;
413 if ((bytes % UINT64_C(512)) != 0)
srs5694fed16d02010-01-27 23:03:40 -0500414 cerr << "Warning: File size is not a multiple of 512 bytes!"
415 << " Misbehavior is likely!\n\a";
srs5694add79a62010-01-26 15:59:58 -0500416 sectors = bytes / UINT64_C(512);
417 } // if
418 } // if
419 } // if (isOpen)
420 return sectors;
421} // DiskIO::DiskSize()