blob: 388a04d91495591b07d26035635b4be48e8bad6e [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>
Roderick W. Smith24bba6e2013-10-12 19:07:16 -040022#include <unistd.h>
srs5694add79a62010-01-26 15:59:58 -050023#include <errno.h>
24#include <fcntl.h>
25#include <sys/stat.h>
srs569434882942012-03-23 12:49:15 -040026#include <unistd.h>
srs5694bf8950c2011-03-12 01:23:12 -050027
28#ifdef __linux__
29#include "linux/hdreg.h"
30#endif
31
srs5694add79a62010-01-26 15:59:58 -050032#include <iostream>
33
srs5694add79a62010-01-26 15:59:58 -050034#include "diskio.h"
35
36using namespace std;
37
38// Returns the official "real" name for a shortened version of same.
39// Trivial here; more important in Windows
40void DiskIO::MakeRealName(void) {
41 realFilename = userFilename;
42} // DiskIO::MakeRealName()
43
srs569455d92612010-03-07 22:16:07 -050044// Open the currently on-record file for reading. Returns 1 if the file is
45// already open or is opened by this call, 0 if opening the file doesn't
46// work.
srs5694add79a62010-01-26 15:59:58 -050047int DiskIO::OpenForRead(void) {
48 int shouldOpen = 1;
srs56948f1b2d62010-05-23 13:07:19 -040049 struct stat64 st;
srs5694add79a62010-01-26 15:59:58 -050050
51 if (isOpen) { // file is already open
52 if (openForWrite) {
53 Close();
54 } else {
55 shouldOpen = 0;
56 } // if/else
57 } // if
58
59 if (shouldOpen) {
60 fd = open(realFilename.c_str(), O_RDONLY);
61 if (fd == -1) {
srs569455d92612010-03-07 22:16:07 -050062 cerr << "Problem opening " << realFilename << " for reading! Error is " << errno << ".\n";
63 if (errno == EACCES) // User is probably not running as root
srs5694fed16d02010-01-27 23:03:40 -050064 cerr << "You must run this program as root or use sudo!\n";
srs569455d92612010-03-07 22:16:07 -050065 if (errno == ENOENT)
66 cerr << "The specified file does not exist!\n";
srs5694add79a62010-01-26 15:59:58 -050067 realFilename = "";
68 userFilename = "";
69 isOpen = 0;
70 openForWrite = 0;
71 } else {
srs56948f1b2d62010-05-23 13:07:19 -040072 isOpen = 0;
srs5694add79a62010-01-26 15:59:58 -050073 openForWrite = 0;
srs56948f1b2d62010-05-23 13:07:19 -040074 if (fstat64(fd, &st) == 0) {
75 if (S_ISDIR(st.st_mode))
76 cerr << "The specified path is a directory!\n";
Roderick W. Smithe09ef882013-07-08 22:56:00 -040077#if !defined(__FreeBSD__) && !defined(__APPLE__)
srs56948f1b2d62010-05-23 13:07:19 -040078 else if (S_ISCHR(st.st_mode))
79 cerr << "The specified path is a character device!\n";
80#endif
81 else if (S_ISFIFO(st.st_mode))
82 cerr << "The specified path is a FIFO!\n";
83 else if (S_ISSOCK(st.st_mode))
84 cerr << "The specified path is a socket!\n";
85 else
86 isOpen = 1;
87 } // if (fstat64()...)
srs5694add79a62010-01-26 15:59:58 -050088 } // if/else
89 } // if
90
91 return isOpen;
92} // DiskIO::OpenForRead(void)
93
94// An extended file-open function. This includes some system-specific checks.
95// Returns 1 if the file is open, 0 otherwise....
96int DiskIO::OpenForWrite(void) {
97 if ((isOpen) && (openForWrite))
98 return 1;
99
100 // Close the disk, in case it's already open for reading only....
101 Close();
102
103 // try to open the device; may fail....
104 fd = open(realFilename.c_str(), O_WRONLY | O_CREAT, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
105#ifdef __APPLE__
106 // MacOS X requires a shared lock under some circumstances....
107 if (fd < 0) {
Roderick W. Smithe09ef882013-07-08 22:56:00 -0400108 cerr << "Warning: Devices opened with shared lock will not have their\npartition table automatically reloaded!\n";
srs5694fed16d02010-01-27 23:03:40 -0500109 fd = open(realFilename.c_str(), O_WRONLY | O_SHLOCK);
srs5694add79a62010-01-26 15:59:58 -0500110 } // if
111#endif
112 if (fd >= 0) {
113 isOpen = 1;
114 openForWrite = 1;
115 } else {
116 isOpen = 0;
117 openForWrite = 0;
118 } // if/else
119 return isOpen;
120} // DiskIO::OpenForWrite(void)
121
122// Close the disk device. Note that this does NOT erase the stored filenames,
123// so the file can be re-opened without specifying the filename.
124void DiskIO::Close(void) {
125 if (isOpen)
srs569408bb0da2010-02-19 17:19:55 -0500126 if (close(fd) < 0)
127 cerr << "Warning! Problem closing file!\n";
srs5694add79a62010-01-26 15:59:58 -0500128 isOpen = 0;
129 openForWrite = 0;
130} // DiskIO::Close()
131
132// Returns block size of device pointed to by fd file descriptor. If the ioctl
133// returns an error condition, print a warning but return a value of SECTOR_SIZE
srs569455d92612010-03-07 22:16:07 -0500134// (512). If the disk can't be opened at all, return a value of 0.
srs5694add79a62010-01-26 15:59:58 -0500135int DiskIO::GetBlockSize(void) {
136 int err = -1, blockSize = 0;
srs56940741fa22013-01-09 12:55:40 -0500137#ifdef __sun__
138 struct dk_minfo minfo;
139#endif
srs5694add79a62010-01-26 15:59:58 -0500140
141 // If disk isn't open, try to open it....
142 if (!isOpen) {
143 OpenForRead();
144 } // if
145
146 if (isOpen) {
147#ifdef __APPLE__
148 err = ioctl(fd, DKIOCGETBLOCKSIZE, &blockSize);
149#endif
srs56940741fa22013-01-09 12:55:40 -0500150#ifdef __sun__
151 err = ioctl(fd, DKIOCGMEDIAINFO, &minfo);
152 if (err == 0)
153 blockSize = minfo.dki_lbsize;
154#endif
srs569408bb0da2010-02-19 17:19:55 -0500155#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694add79a62010-01-26 15:59:58 -0500156 err = ioctl(fd, DIOCGSECTORSIZE, &blockSize);
157#endif
158#ifdef __linux__
159 err = ioctl(fd, BLKSSZGET, &blockSize);
160#endif
161
162 if (err == -1) {
163 blockSize = SECTOR_SIZE;
164 // ENOTTY = inappropriate ioctl; probably being called on a disk image
165 // file, so don't display the warning message....
166 // 32-bit code returns EINVAL, I don't know why. I know I'm treading on
167 // thin ice here, but it should be OK in all but very weird cases....
168 if ((errno != ENOTTY) && (errno != EINVAL)) {
srs5694fed16d02010-01-27 23:03:40 -0500169 cerr << "\aError " << errno << " when determining sector size! Setting sector size to "
170 << SECTOR_SIZE << "\n";
srs569455d92612010-03-07 22:16:07 -0500171 cout << "Disk device is " << realFilename << "\n";
srs5694add79a62010-01-26 15:59:58 -0500172 } // if
173 } // if (err == -1)
174 } // if (isOpen)
175
176 return (blockSize);
177} // DiskIO::GetBlockSize()
178
srs5694bf8950c2011-03-12 01:23:12 -0500179// Returns the number of heads, according to the kernel, or 255 if the
180// correct value can't be determined.
181uint32_t DiskIO::GetNumHeads(void) {
182 uint32_t numHeads = 255;
183
184#ifdef HDIO_GETGEO
185 struct hd_geometry geometry;
186
187 // If disk isn't open, try to open it....
188 if (!isOpen)
189 OpenForRead();
190
191 if (!ioctl(fd, HDIO_GETGEO, &geometry))
192 numHeads = (uint32_t) geometry.heads;
193#endif
194 return numHeads;
195} // DiskIO::GetNumHeads();
196
197// Returns the number of sectors per track, according to the kernel, or 63
198// if the correct value can't be determined.
199uint32_t DiskIO::GetNumSecsPerTrack(void) {
200 uint32_t numSecs = 63;
201
202 #ifdef HDIO_GETGEO
203 struct hd_geometry geometry;
204
205 // If disk isn't open, try to open it....
206 if (!isOpen)
207 OpenForRead();
208
209 if (!ioctl(fd, HDIO_GETGEO, &geometry))
210 numSecs = (uint32_t) geometry.sectors;
211 #endif
212 return numSecs;
213} // DiskIO::GetNumSecsPerTrack()
214
srs5694add79a62010-01-26 15:59:58 -0500215// Resync disk caches so the OS uses the new partition table. This code varies
216// a lot from one OS to another.
srs5694a17fe692011-09-10 20:30:20 -0400217// Returns 1 on success, 0 if the kernel continues to use the old partition table.
218// (Note that for most OSes, the default of 0 is returned because I've not yet
219// looked into how to test for success in the underlying system calls...)
220int DiskIO::DiskSync(void) {
221 int i, retval = 0, platformFound = 0;
srs5694add79a62010-01-26 15:59:58 -0500222
223 // If disk isn't open, try to open it....
224 if (!isOpen) {
225 OpenForRead();
226 } // if
227
228 if (isOpen) {
229 sync();
srs56940741fa22013-01-09 12:55:40 -0500230#if defined(__APPLE__) || defined(__sun__)
srs5694fed16d02010-01-27 23:03:40 -0500231 cout << "Warning: The kernel may continue to use old or deleted partitions.\n"
232 << "You should reboot or remove the drive.\n";
srs5694add79a62010-01-26 15:59:58 -0500233 /* don't know if this helps
234 * it definitely will get things on disk though:
235 * http://topiks.org/mac-os-x/0321278542/ch12lev1sec8.html */
srs56940741fa22013-01-09 12:55:40 -0500236#ifdef __sun__
237 i = ioctl(fd, DKIOCFLUSHWRITECACHE);
238#else
srs5694add79a62010-01-26 15:59:58 -0500239 i = ioctl(fd, DKIOCSYNCHRONIZECACHE);
srs56940741fa22013-01-09 12:55:40 -0500240#endif
srs5694add79a62010-01-26 15:59:58 -0500241 platformFound++;
242#endif
srs569408bb0da2010-02-19 17:19:55 -0500243#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694add79a62010-01-26 15:59:58 -0500244 sleep(2);
245 i = ioctl(fd, DIOCGFLUSH);
srs5694fed16d02010-01-27 23:03:40 -0500246 cout << "Warning: The kernel may continue to use old or deleted partitions.\n"
247 << "You should reboot or remove the drive.\n";
srs5694add79a62010-01-26 15:59:58 -0500248 platformFound++;
249#endif
250#ifdef __linux__
srs569400b6d7a2011-06-26 22:40:06 -0400251 sleep(1); // Theoretically unnecessary, but ioctl() fails sometimes if omitted....
252 fsync(fd);
srs5694add79a62010-01-26 15:59:58 -0500253 i = ioctl(fd, BLKRRPART);
srs5694a17fe692011-09-10 20:30:20 -0400254 if (i) {
srs5694fed16d02010-01-27 23:03:40 -0500255 cout << "Warning: The kernel is still using the old partition table.\n"
256 << "The new table will be used at the next reboot.\n";
srs5694a17fe692011-09-10 20:30:20 -0400257 } else {
258 retval = 1;
259 } // if/else
srs5694add79a62010-01-26 15:59:58 -0500260 platformFound++;
261#endif
262 if (platformFound == 0)
srs5694fed16d02010-01-27 23:03:40 -0500263 cerr << "Warning: Platform not recognized!\n";
srs5694add79a62010-01-26 15:59:58 -0500264 if (platformFound > 1)
srs5694fed16d02010-01-27 23:03:40 -0500265 cerr << "\nWarning: We seem to be running on multiple platforms!\n";
srs5694add79a62010-01-26 15:59:58 -0500266 } // if (isOpen)
srs5694a17fe692011-09-10 20:30:20 -0400267 return retval;
srs5694add79a62010-01-26 15:59:58 -0500268} // DiskIO::DiskSync()
269
270// Seek to the specified sector. Returns 1 on success, 0 on failure.
srs5694cb76c672010-02-11 22:22:22 -0500271// Note that seeking beyond the end of the file is NOT detected as a failure!
srs5694add79a62010-01-26 15:59:58 -0500272int DiskIO::Seek(uint64_t sector) {
273 int retval = 1;
274 off_t seekTo, sought;
275
276 // If disk isn't open, try to open it....
277 if (!isOpen) {
278 retval = OpenForRead();
279 } // if
280
281 if (isOpen) {
282 seekTo = sector * (uint64_t) GetBlockSize();
283 sought = lseek64(fd, seekTo, SEEK_SET);
284 if (sought != seekTo) {
285 retval = 0;
286 } // if
287 } // if
288 return retval;
289} // DiskIO::Seek()
290
291// A variant on the standard read() function. Done to work around
292// limitations in FreeBSD concerning the matching of the sector
293// size with the number of bytes read.
294// Returns the number of bytes read into buffer.
295int DiskIO::Read(void* buffer, int numBytes) {
srs5694cb76c672010-02-11 22:22:22 -0500296 int blockSize, numBlocks, retval = 0;
srs5694add79a62010-01-26 15:59:58 -0500297 char* tempSpace;
298
299 // If disk isn't open, try to open it....
300 if (!isOpen) {
301 OpenForRead();
302 } // if
303
304 if (isOpen) {
305 // Compute required space and allocate memory
306 blockSize = GetBlockSize();
307 if (numBytes <= blockSize) {
308 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500309 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500310 } else {
311 numBlocks = numBytes / blockSize;
srs5694cb76c672010-02-11 22:22:22 -0500312 if ((numBytes % blockSize) != 0)
313 numBlocks++;
314 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500315 } // if/else
srs56946aae2a92011-06-10 01:16:51 -0400316 if (tempSpace == NULL) {
317 cerr << "Unable to allocate memory in DiskIO::Read()! Terminating!\n";
318 exit(1);
319 } // if
srs5694add79a62010-01-26 15:59:58 -0500320
321 // Read the data into temporary space, then copy it to buffer
322 retval = read(fd, tempSpace, numBlocks * blockSize);
323 memcpy(buffer, tempSpace, numBytes);
srs5694add79a62010-01-26 15:59:58 -0500324
325 // Adjust the return value, if necessary....
326 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
327 retval = numBytes;
328
srs5694cb76c672010-02-11 22:22:22 -0500329 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500330 } // if (isOpen)
331 return retval;
332} // DiskIO::Read()
333
334// A variant on the standard write() function. Done to work around
335// limitations in FreeBSD concerning the matching of the sector
336// size with the number of bytes read.
337// Returns the number of bytes written.
338int DiskIO::Write(void* buffer, int numBytes) {
339 int blockSize = 512, i, numBlocks, retval = 0;
340 char* tempSpace;
341
342 // If disk isn't open, try to open it....
343 if ((!isOpen) || (!openForWrite)) {
344 OpenForWrite();
345 } // if
346
347 if (isOpen) {
348 // Compute required space and allocate memory
349 blockSize = GetBlockSize();
350 if (numBytes <= blockSize) {
351 numBlocks = 1;
srs5694cb76c672010-02-11 22:22:22 -0500352 tempSpace = new char [blockSize];
srs5694add79a62010-01-26 15:59:58 -0500353 } else {
354 numBlocks = numBytes / blockSize;
355 if ((numBytes % blockSize) != 0) numBlocks++;
srs5694cb76c672010-02-11 22:22:22 -0500356 tempSpace = new char [numBlocks * blockSize];
srs5694add79a62010-01-26 15:59:58 -0500357 } // if/else
srs56946aae2a92011-06-10 01:16:51 -0400358 if (tempSpace == NULL) {
359 cerr << "Unable to allocate memory in DiskIO::Write()! Terminating!\n";
360 exit(1);
361 } // if
362
srs5694add79a62010-01-26 15:59:58 -0500363 // Copy the data to my own buffer, then write it
srs5694add79a62010-01-26 15:59:58 -0500364 memcpy(tempSpace, buffer, numBytes);
365 for (i = numBytes; i < numBlocks * blockSize; i++) {
366 tempSpace[i] = 0;
367 } // for
368 retval = write(fd, tempSpace, numBlocks * blockSize);
369
370 // Adjust the return value, if necessary....
371 if (((numBlocks * blockSize) != numBytes) && (retval > 0))
372 retval = numBytes;
373
srs5694cb76c672010-02-11 22:22:22 -0500374 delete[] tempSpace;
srs5694add79a62010-01-26 15:59:58 -0500375 } // if (isOpen)
376 return retval;
377} // DiskIO:Write()
378
379/**************************************************************************************
380 * *
381 * Below functions are lifted from various sources, as documented in comments before *
382 * each one. *
383 * *
384 **************************************************************************************/
385
386// The disksize function is taken from the Linux fdisk code and modified
387// greatly since then to enable FreeBSD and MacOS support, as well as to
388// return correct values for disk image files.
389uint64_t DiskIO::DiskSize(int *err) {
srs5694add79a62010-01-26 15:59:58 -0500390 uint64_t sectors = 0; // size in sectors
391 off_t bytes = 0; // size in bytes
392 struct stat64 st;
393 int platformFound = 0;
srs56940741fa22013-01-09 12:55:40 -0500394#ifdef __sun__
395 struct dk_minfo minfo;
396#endif
srs5694add79a62010-01-26 15:59:58 -0500397
398 // If disk isn't open, try to open it....
399 if (!isOpen) {
400 OpenForRead();
401 } // if
402
403 if (isOpen) {
404 // Note to self: I recall testing a simplified version of
405 // this code, similar to what's in the __APPLE__ block,
406 // on Linux, but I had some problems. IIRC, it ran OK on 32-bit
407 // systems but not on 64-bit. Keep this in mind in case of
408 // 32/64-bit issues on MacOS....
409#ifdef __APPLE__
410 *err = ioctl(fd, DKIOCGETBLOCKCOUNT, &sectors);
411 platformFound++;
412#endif
srs56940741fa22013-01-09 12:55:40 -0500413#ifdef __sun__
414 *err = ioctl(fd, DKIOCGMEDIAINFO, &minfo);
415 if (*err == 0)
416 sectors = minfo.dki_capacity;
417 platformFound++;
418#endif
srs569408bb0da2010-02-19 17:19:55 -0500419#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
srs5694add79a62010-01-26 15:59:58 -0500420 *err = ioctl(fd, DIOCGMEDIASIZE, &bytes);
srs569408bb0da2010-02-19 17:19:55 -0500421 long long b = GetBlockSize();
srs5694add79a62010-01-26 15:59:58 -0500422 sectors = bytes / b;
423 platformFound++;
424#endif
425#ifdef __linux__
srs569408bb0da2010-02-19 17:19:55 -0500426 long sz;
427 long long b;
srs5694add79a62010-01-26 15:59:58 -0500428 *err = ioctl(fd, BLKGETSIZE, &sz);
429 if (*err) {
430 sectors = sz = 0;
431 } // if
srs569464cbd172011-03-01 22:03:54 -0500432 if ((!*err) || (errno == EFBIG)) {
srs5694add79a62010-01-26 15:59:58 -0500433 *err = ioctl(fd, BLKGETSIZE64, &b);
434 if (*err || b == 0 || b == sz)
435 sectors = sz;
436 else
437 sectors = (b >> 9);
438 } // if
439 // Unintuitively, the above returns values in 512-byte blocks, no
440 // matter what the underlying device's block size. Correct for this....
441 sectors /= (GetBlockSize() / 512);
442 platformFound++;
443#endif
444 if (platformFound != 1)
srs5694fed16d02010-01-27 23:03:40 -0500445 cerr << "Warning! We seem to be running on no known platform!\n";
srs5694add79a62010-01-26 15:59:58 -0500446
447 // The above methods have failed, so let's assume it's a regular
448 // file (a QEMU image, dd backup, or what have you) and see what
449 // fstat() gives us....
450 if ((sectors == 0) || (*err == -1)) {
451 if (fstat64(fd, &st) == 0) {
srs56949a46b042011-03-15 00:34:10 -0400452 bytes = st.st_size;
srs5694add79a62010-01-26 15:59:58 -0500453 if ((bytes % UINT64_C(512)) != 0)
srs5694fed16d02010-01-27 23:03:40 -0500454 cerr << "Warning: File size is not a multiple of 512 bytes!"
455 << " Misbehavior is likely!\n\a";
srs5694add79a62010-01-26 15:59:58 -0500456 sectors = bytes / UINT64_C(512);
457 } // if
458 } // if
459 } // if (isOpen)
460 return sectors;
461} // DiskIO::DiskSize()