blob: 03fc3c86ff0a4ac8b149f4cc61e8622809480926 [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__
srs569400b6d7a2011-06-26 22:40:06 -0400233 sleep(1); // Theoretically unnecessary, but ioctl() fails sometimes if omitted....
234 fsync(fd);
srs5694add79a62010-01-26 15:59:58 -0500235 i = ioctl(fd, BLKRRPART);
236 if (i)
srs5694fed16d02010-01-27 23:03:40 -0500237 cout << "Warning: The kernel is still using the old partition table.\n"
238 << "The new table will be used at the next reboot.\n";
srs5694add79a62010-01-26 15:59:58 -0500239 platformFound++;
240#endif
241 if (platformFound == 0)
srs5694fed16d02010-01-27 23:03:40 -0500242 cerr << "Warning: Platform not recognized!\n";
srs5694add79a62010-01-26 15:59:58 -0500243 if (platformFound > 1)
srs5694fed16d02010-01-27 23:03:40 -0500244 cerr << "\nWarning: We seem to be running on multiple platforms!\n";
srs5694add79a62010-01-26 15:59:58 -0500245 } // if (isOpen)
246} // DiskIO::DiskSync()
247
248// Seek to the specified sector. Returns 1 on success, 0 on failure.
srs5694cb76c672010-02-11 22:22:22 -0500249// Note that seeking beyond the end of the file is NOT detected as a failure!
srs5694add79a62010-01-26 15:59:58 -0500250int DiskIO::Seek(uint64_t sector) {
251 int retval = 1;
252 off_t seekTo, sought;
253
254 // If disk isn't open, try to open it....
255 if (!isOpen) {
256 retval = OpenForRead();
257 } // if
258
259 if (isOpen) {
260 seekTo = sector * (uint64_t) GetBlockSize();
261 sought = lseek64(fd, seekTo, SEEK_SET);
262 if (sought != seekTo) {
263 retval = 0;
264 } // if
265 } // if
266 return retval;
267} // DiskIO::Seek()
268
269// A variant on the standard read() function. Done to work around
270// limitations in FreeBSD concerning the matching of the sector
271// size with the number of bytes read.
272// Returns the number of bytes read into buffer.
273int DiskIO::Read(void* buffer, int numBytes) {
srs5694cb76c672010-02-11 22:22:22 -0500274 int blockSize, numBlocks, retval = 0;
srs5694add79a62010-01-26 15:59:58 -0500275 char* tempSpace;
276
277 // If disk isn't open, try to open it....
278 if (!isOpen) {
279 OpenForRead();
280 } // if
281
282 if (isOpen) {
283 // Compute required space and allocate memory
284 blockSize = GetBlockSize();
285 if (numBytes <= blockSize) {
286 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500287 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500288 } else {
289 numBlocks = numBytes / blockSize;
srs5694cb76c672010-02-11 22:22:22 -0500290 if ((numBytes % blockSize) != 0)
291 numBlocks++;
292 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500293 } // if/else
srs56946aae2a92011-06-10 01:16:51 -0400294 if (tempSpace == NULL) {
295 cerr << "Unable to allocate memory in DiskIO::Read()! Terminating!\n";
296 exit(1);
297 } // if
srs5694add79a62010-01-26 15:59:58 -0500298
299 // Read the data into temporary space, then copy it to buffer
300 retval = read(fd, tempSpace, numBlocks * blockSize);
301 memcpy(buffer, tempSpace, numBytes);
srs5694add79a62010-01-26 15:59:58 -0500302
303 // Adjust the return value, if necessary....
304 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
305 retval = numBytes;
306
srs5694cb76c672010-02-11 22:22:22 -0500307 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500308 } // if (isOpen)
309 return retval;
310} // DiskIO::Read()
311
312// A variant on the standard write() function. Done to work around
313// limitations in FreeBSD concerning the matching of the sector
314// size with the number of bytes read.
315// Returns the number of bytes written.
316int DiskIO::Write(void* buffer, int numBytes) {
317 int blockSize = 512, i, numBlocks, retval = 0;
318 char* tempSpace;
319
320 // If disk isn't open, try to open it....
321 if ((!isOpen) || (!openForWrite)) {
322 OpenForWrite();
323 } // if
324
325 if (isOpen) {
326 // Compute required space and allocate memory
327 blockSize = GetBlockSize();
328 if (numBytes <= blockSize) {
329 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500330 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500331 } else {
332 numBlocks = numBytes / blockSize;
333 if ((numBytes % blockSize) != 0) numBlocks++;
srs5694cb76c672010-02-11 22:22:22 -0500334 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500335 } // if/else
srs56946aae2a92011-06-10 01:16:51 -0400336 if (tempSpace == NULL) {
337 cerr << "Unable to allocate memory in DiskIO::Write()! Terminating!\n";
338 exit(1);
339 } // if
340
srs5694add79a62010-01-26 15:59:58 -0500341 // Copy the data to my own buffer, then write it
srs5694add79a62010-01-26 15:59:58 -0500342 memcpy(tempSpace, buffer, numBytes);
343 for (i = numBytes; i < numBlocks * blockSize; i++) {
344 tempSpace[i] = 0;
345 } // for
346 retval = write(fd, tempSpace, numBlocks * blockSize);
347
348 // Adjust the return value, if necessary....
349 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
350 retval = numBytes;
351
srs5694cb76c672010-02-11 22:22:22 -0500352 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500353 } // if (isOpen)
354 return retval;
355} // DiskIO:Write()
356
357/**************************************************************************************
358 * *
359 * Below functions are lifted from various sources, as documented in comments before *
360 * each one. *
361 * *
362 **************************************************************************************/
363
364// The disksize function is taken from the Linux fdisk code and modified
365// greatly since then to enable FreeBSD and MacOS support, as well as to
366// return correct values for disk image files.
367uint64_t DiskIO::DiskSize(int *err) {
srs5694add79a62010-01-26 15:59:58 -0500368 uint64_t sectors = 0; // size in sectors
369 off_t bytes = 0; // size in bytes
370 struct stat64 st;
371 int platformFound = 0;
372
373 // If disk isn't open, try to open it....
374 if (!isOpen) {
375 OpenForRead();
376 } // if
377
378 if (isOpen) {
379 // Note to self: I recall testing a simplified version of
380 // this code, similar to what's in the __APPLE__ block,
381 // on Linux, but I had some problems. IIRC, it ran OK on 32-bit
382 // systems but not on 64-bit. Keep this in mind in case of
383 // 32/64-bit issues on MacOS....
384#ifdef __APPLE__
385 *err = ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors);
386 platformFound++;
387#endif
srs569408bb0da2010-02-19 17:19:55 -0500388#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694add79a62010-01-26 15:59:58 -0500389 *err = ioctl(fd, DIOCGMEDIASIZE, &bytes);
srs569408bb0da2010-02-19 17:19:55 -0500390 long long b = GetBlockSize();
srs5694add79a62010-01-26 15:59:58 -0500391 sectors = bytes / b;
392 platformFound++;
393#endif
394#ifdef __linux__
srs569408bb0da2010-02-19 17:19:55 -0500395 long sz;
396 long long b;
srs5694add79a62010-01-26 15:59:58 -0500397 *err = ioctl(fd, BLKGETSIZE, &sz);
398 if (*err) {
399 sectors = sz = 0;
400 } // if
srs569464cbd172011-03-01 22:03:54 -0500401 if ((!*err) || (errno == EFBIG)) {
srs5694add79a62010-01-26 15:59:58 -0500402 *err = ioctl(fd, BLKGETSIZE64, &b);
403 if (*err || b == 0 || b == sz)
404 sectors = sz;
405 else
406 sectors = (b >> 9);
407 } // if
408 // Unintuitively, the above returns values in 512-byte blocks, no
409 // matter what the underlying device's block size. Correct for this....
410 sectors /= (GetBlockSize() / 512);
411 platformFound++;
412#endif
413 if (platformFound != 1)
srs5694fed16d02010-01-27 23:03:40 -0500414 cerr << "Warning! We seem to be running on no known platform!\n";
srs5694add79a62010-01-26 15:59:58 -0500415
416 // The above methods have failed, so let's assume it's a regular
417 // file (a QEMU image, dd backup, or what have you) and see what
418 // fstat() gives us....
419 if ((sectors == 0) || (*err == -1)) {
420 if (fstat64(fd, &st) == 0) {
srs56949a46b042011-03-15 00:34:10 -0400421 bytes = st.st_size;
srs5694add79a62010-01-26 15:59:58 -0500422 if ((bytes % UINT64_C(512)) != 0)
srs5694fed16d02010-01-27 23:03:40 -0500423 cerr << "Warning: File size is not a multiple of 512 bytes!"
424 << " Misbehavior is likely!\n\a";
srs5694add79a62010-01-26 15:59:58 -0500425 sectors = bytes / UINT64_C(512);
426 } // if
427 } // if
428 } // if (isOpen)
429 return sectors;
430} // DiskIO::DiskSize()