]> mj.ucw.cz Git - libucw.git/blob - lib/partmap.c
partmap.h deserves its own header
[libucw.git] / lib / partmap.c
1 /*
2  *      UCW Library -- Mapping of File Parts
3  *
4  *      (c) 2003 Martin Mares <mj@ucw.cz>
5  *      (c) 2003--2005 Robert Spalek <robert@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include "lib/lib.h"
12 #include "lib/lfs.h"
13 #include "lib/partmap.h"
14
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <fcntl.h>
18 #include <unistd.h>
19 #include <sys/stat.h>
20 #include <sys/mman.h>
21 #include <sys/user.h>
22
23 #ifdef TEST
24 #define PARTMAP_WINDOW 4096
25 #else
26 #define PARTMAP_WINDOW 16777216
27 #endif
28
29 struct partmap *
30 partmap_open(byte *name, int writeable)
31 {
32   struct partmap *p = xmalloc_zero(sizeof(struct partmap));
33
34   p->fd = sh_open(name, writeable ? O_RDWR : O_RDONLY);
35   if (p->fd < 0)
36     die("open(%s): %m", name);
37   if ((p->file_size = sh_seek(p->fd, 0, SEEK_END)) < 0)
38     die("lseek(%s): %m", name);
39   p->writeable = writeable;
40   return p;
41 }
42
43 sh_off_t
44 partmap_size(struct partmap *p)
45 {
46   return p->file_size;
47 }
48
49 void
50 partmap_close(struct partmap *p)
51 {
52   if (p->start_map)
53     munmap(p->start_map, p->end_off - p->start_off);
54   close(p->fd);
55   xfree(p);
56 }
57
58 void
59 partmap_load(struct partmap *p, sh_off_t start, uns size)
60 {
61   if (p->start_map)
62     munmap(p->start_map, p->end_off - p->start_off);
63   sh_off_t end = start + size;
64   sh_off_t win_start = start/PAGE_SIZE * PAGE_SIZE;
65   uns win_len = PARTMAP_WINDOW;
66   if ((sh_off_t) (win_start+win_len) > p->file_size)
67     win_len = ALIGN(p->file_size - win_start, PAGE_SIZE);
68   if ((sh_off_t) (win_start+win_len) < end)
69     die("partmap_map: Window is too small for mapping %d bytes", size);
70   p->start_map = sh_mmap(NULL, win_len, p->writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, p->fd, win_start);
71   if (p->start_map == MAP_FAILED)
72     die("mmap failed at position %Ld: %m", (long long)win_start);
73   p->start_off = win_start;
74   p->end_off = win_start+win_len;
75 }
76
77 #ifdef TEST
78 int main(int argc, char **argv)
79 {
80   struct partmap *p = partmap_open(argv[1], 0);
81   uns l = partmap_size(p);
82   uns i;
83   for (i=0; i<l; i++)
84     putchar(*(char *)partmap_map(p, i, 1));
85   partmap_close(p);
86   return 0;
87 }
88 #endif