]> mj.ucw.cz Git - libucw.git/blob - lib/partmap.c
avoid compiler warnings with debugging turned off
[libucw.git] / lib / partmap.c
1 /*
2  *      UCW Library -- Mapping of File Parts
3  *
4  *      (c) 2003--2006 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 CONFIG_PARTMAP_IS_MMAP
24 #define PARTMAP_WINDOW ~(size_t)0
25 #else
26 #ifdef TEST
27 #define PARTMAP_WINDOW 4096
28 #else
29 #define PARTMAP_WINDOW 16777216
30 #endif
31 #endif
32
33 struct partmap *
34 partmap_open(byte *name, int writeable)
35 {
36   struct partmap *p = xmalloc_zero(sizeof(struct partmap));
37
38   p->fd = sh_open(name, writeable ? O_RDWR : O_RDONLY);
39   if (p->fd < 0)
40     die("open(%s): %m", name);
41   if ((p->file_size = sh_seek(p->fd, 0, SEEK_END)) < 0)
42     die("lseek(%s): %m", name);
43   p->writeable = writeable;
44 #ifdef CONFIG_PARTMAP_IS_MMAP
45   partmap_load(p, 0, p->file_size);
46 #endif
47   return p;
48 }
49
50 sh_off_t
51 partmap_size(struct partmap *p)
52 {
53   return p->file_size;
54 }
55
56 void
57 partmap_close(struct partmap *p)
58 {
59   if (p->start_map)
60     munmap(p->start_map, p->end_off - p->start_off);
61   close(p->fd);
62   xfree(p);
63 }
64
65 void
66 partmap_load(struct partmap *p, sh_off_t start, uns size)
67 {
68   if (p->start_map)
69     munmap(p->start_map, p->end_off - p->start_off);
70   sh_off_t end = start + size;
71   sh_off_t win_start = start/PAGE_SIZE * PAGE_SIZE;
72   size_t win_len = PARTMAP_WINDOW;
73   if ((sh_off_t) (win_start+win_len) > p->file_size)
74     win_len = ALIGN(p->file_size - win_start, PAGE_SIZE);
75   if ((sh_off_t) (win_start+win_len) < end)
76     die("partmap_map: Window is too small for mapping %d bytes", size);
77   p->start_map = sh_mmap(NULL, win_len, p->writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, p->fd, win_start);
78   if (p->start_map == MAP_FAILED)
79     die("mmap failed at position %Ld: %m", (long long)win_start);
80   p->start_off = win_start;
81   p->end_off = win_start+win_len;
82   madvise(p->start_map, win_len, MADV_SEQUENTIAL);
83 }
84
85 #ifdef TEST
86 int main(int argc, char **argv)
87 {
88   struct partmap *p = partmap_open(argv[1], 0);
89   uns l = partmap_size(p);
90   uns i;
91   for (i=0; i<l; i++)
92     putchar(*(char *)partmap_map(p, i, 1));
93   partmap_close(p);
94   return 0;
95 }
96 #endif