blob: 327a498582006807860182e74b5d4a700f3bee02 [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
srs56946aae2a92011-06-10 01:16:51 -0400293 if (tempSpace == NULL) {
294 cerr << "Unable to allocate memory in DiskIO::Read()! Terminating!\n";
295 exit(1);
296 } // if
srs5694add79a62010-01-26 15:59:58 -0500297
298 // Read the data into temporary space, then copy it to buffer
299 retval = read(fd, tempSpace, numBlocks * blockSize);
300 memcpy(buffer, tempSpace, numBytes);
srs5694add79a62010-01-26 15:59:58 -0500301
302 // Adjust the return value, if necessary....
303 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
304 retval = numBytes;
305
srs5694cb76c672010-02-11 22:22:22 -0500306 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500307 } // if (isOpen)
308 return retval;
309} // DiskIO::Read()
310
311// A variant on the standard write() function. Done to work around
312// limitations in FreeBSD concerning the matching of the sector
313// size with the number of bytes read.
314// Returns the number of bytes written.
315int DiskIO::Write(void* buffer, int numBytes) {
316 int blockSize = 512, i, numBlocks, retval = 0;
317 char* tempSpace;
318
319 // If disk isn't open, try to open it....
320 if ((!isOpen) || (!openForWrite)) {
321 OpenForWrite();
322 } // if
323
324 if (isOpen) {
325 // Compute required space and allocate memory
326 blockSize = GetBlockSize();
327 if (numBytes <= blockSize) {
328 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500329 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500330 } else {
331 numBlocks = numBytes / blockSize;
332 if ((numBytes % blockSize) != 0) numBlocks++;
srs5694cb76c672010-02-11 22:22:22 -0500333 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500334 } // if/else
srs56946aae2a92011-06-10 01:16:51 -0400335 if (tempSpace == NULL) {
336 cerr << "Unable to allocate memory in DiskIO::Write()! Terminating!\n";
337 exit(1);
338 } // if
339
srs5694add79a62010-01-26 15:59:58 -0500340 // Copy the data to my own buffer, then write it
srs5694add79a62010-01-26 15:59:58 -0500341 memcpy(tempSpace, buffer, numBytes);
342 for (i = numBytes; i < numBlocks * blockSize; i++) {
343 tempSpace[i] = 0;
344 } // for
345 retval = write(fd, tempSpace, numBlocks * blockSize);
346
347 // Adjust the return value, if necessary....
348 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
349 retval = numBytes;
350
srs5694cb76c672010-02-11 22:22:22 -0500351 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500352 } // if (isOpen)
353 return retval;
354} // DiskIO:Write()
355
356/**************************************************************************************
357 * *
358 * Below functions are lifted from various sources, as documented in comments before *
359 * each one. *
360 * *
361 **************************************************************************************/
362
363// The disksize function is taken from the Linux fdisk code and modified
364// greatly since then to enable FreeBSD and MacOS support, as well as to
365// return correct values for disk image files.
366uint64_t DiskIO::DiskSize(int *err) {
srs5694add79a62010-01-26 15:59:58 -0500367 uint64_t sectors = 0; // size in sectors
368 off_t bytes = 0; // size in bytes
369 struct stat64 st;
370 int platformFound = 0;
371
372 // If disk isn't open, try to open it....
373 if (!isOpen) {
374 OpenForRead();
375 } // if
376
377 if (isOpen) {
378 // Note to self: I recall testing a simplified version of
379 // this code, similar to what's in the __APPLE__ block,
380 // on Linux, but I had some problems. IIRC, it ran OK on 32-bit
381 // systems but not on 64-bit. Keep this in mind in case of
382 // 32/64-bit issues on MacOS....
383#ifdef __APPLE__
384 *err = ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors);
385 platformFound++;
386#endif
srs569408bb0da2010-02-19 17:19:55 -0500387#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694add79a62010-01-26 15:59:58 -0500388 *err = ioctl(fd, DIOCGMEDIASIZE, &bytes);
srs569408bb0da2010-02-19 17:19:55 -0500389 long long b = GetBlockSize();
srs5694add79a62010-01-26 15:59:58 -0500390 sectors = bytes / b;
391 platformFound++;
392#endif
393#ifdef __linux__
srs569408bb0da2010-02-19 17:19:55 -0500394 long sz;
395 long long b;
srs5694add79a62010-01-26 15:59:58 -0500396 *err = ioctl(fd, BLKGETSIZE, &sz);
397 if (*err) {
398 sectors = sz = 0;
399 } // if
srs569464cbd172011-03-01 22:03:54 -0500400 if ((!*err) || (errno == EFBIG)) {
srs5694add79a62010-01-26 15:59:58 -0500401 *err = ioctl(fd, BLKGETSIZE64, &b);
402 if (*err || b == 0 || b == sz)
403 sectors = sz;
404 else
405 sectors = (b >> 9);
406 } // if
407 // Unintuitively, the above returns values in 512-byte blocks, no
408 // matter what the underlying device's block size. Correct for this....
409 sectors /= (GetBlockSize() / 512);
410 platformFound++;
411#endif
412 if (platformFound != 1)
srs5694fed16d02010-01-27 23:03:40 -0500413 cerr << "Warning! We seem to be running on no known platform!\n";
srs5694add79a62010-01-26 15:59:58 -0500414
415 // The above methods have failed, so let's assume it's a regular
416 // file (a QEMU image, dd backup, or what have you) and see what
417 // fstat() gives us....
418 if ((sectors == 0) || (*err == -1)) {
419 if (fstat64(fd, &st) == 0) {
srs56949a46b042011-03-15 00:34:10 -0400420 bytes = st.st_size;
srs5694add79a62010-01-26 15:59:58 -0500421 if ((bytes % UINT64_C(512)) != 0)
srs5694fed16d02010-01-27 23:03:40 -0500422 cerr << "Warning: File size is not a multiple of 512 bytes!"
423 << " Misbehavior is likely!\n\a";
srs5694add79a62010-01-26 15:59:58 -0500424 sectors = bytes / UINT64_C(512);
425 } // if
426 } // if
427 } // if (isOpen)
428 return sectors;
429} // DiskIO::DiskSize()