-
Notifications
You must be signed in to change notification settings - Fork 9
/
device-linux.c
56 lines (50 loc) · 1.18 KB
/
device-linux.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Copyright (c) 2008 David Caldwell and Jim Radford, All Rights Reserved.
#include <fcntl.h>
#include <unistd.h>
#include <stdint.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <linux/fs.h>
#include <sys/ioctl.h>
#include <err.h>
#include "xmem.h"
#include "device.h"
static unsigned int sector_size(int fd)
{
uint32_t size;
if (ioctl(fd, BLKSSZGET, &size) == -1)
return 0;
return size;
}
static unsigned long long byte_count(int fd)
{
uint64_t count;
if (ioctl(fd, BLKGETSIZE64, &count) == -1)
return 0;
return count;
}
struct device *open_disk_device(char *name)
{
int fd = open(name, O_RDWR | O_EXCL);
if (fd < 0) {
if (errno == ENOENT) return NULL;
if (errno == EBUSY)
fd = open(name, O_RDWR);
}
if (fd < 0)
return NULL;
unsigned int ss = sector_size(fd);
unsigned long long bc = byte_count(fd);
struct device dev = {
.fd = fd,
.name = xstrdup(name),
.sector_size = ss,
.sector_count = ss ? bc/ss : 0,
};
return xmemdup(&dev, sizeof(dev));
}
char *device_help()
{
return " <device> is /dev/sd* style device (full path)\n";
}