]> mj.ucw.cz Git - libucw.git/blob - lib/partmap.c
partmap_map() inlined and added an even faster version of it
[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
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18 #include <sys/stat.h>
19 #include <sys/mman.h>
20 #include <sys/user.h>
21
22 #ifdef TEST
23 #define PARTMAP_WINDOW 4096
24 #else
25 #define PARTMAP_WINDOW 16777216
26 #endif
27
28 struct partmap *
29 partmap_open(byte *name, int writeable)
30 {
31   struct partmap *p = xmalloc_zero(sizeof(struct partmap));
32
33   p->fd = sh_open(name, writeable ? O_RDWR : O_RDONLY);
34   if (p->fd < 0)
35     die("open(%s): %m", name);
36   if ((p->file_size = sh_seek(p->fd, 0, SEEK_END)) < 0)
37     die("lseek(%s): %m", name);
38   p->writeable = writeable;
39   return p;
40 }
41
42 sh_off_t
43 partmap_size(struct partmap *p)
44 {
45   return p->file_size;
46 }
47
48 void
49 partmap_close(struct partmap *p)
50 {
51   if (p->start_map)
52     munmap(p->start_map, p->end_off - p->start_off);
53   close(p->fd);
54   xfree(p);
55 }
56
57 void
58 partmap_load(struct partmap *p, sh_off_t start, uns size)
59 {
60   if (p->start_map)
61     munmap(p->start_map, p->end_off - p->start_off);
62   sh_off_t end = start + size;
63   sh_off_t win_start = start/PAGE_SIZE * PAGE_SIZE;
64   uns win_len = PARTMAP_WINDOW;
65   if ((sh_off_t) (win_start+win_len) > p->file_size)
66     win_len = ALIGN(p->file_size - win_start, PAGE_SIZE);
67   if ((sh_off_t) (win_start+win_len) < end)
68     die("partmap_map: Window is too small for mapping %d bytes", size);
69   p->start_map = sh_mmap(NULL, win_len, p->writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, p->fd, win_start);
70   if (p->start_map == MAP_FAILED)
71     die("mmap failed at position %Ld: %m", (long long)win_start);
72   p->start_off = win_start;
73   p->end_off = win_start+win_len;
74 }
75
76 #ifdef TEST
77 int main(int argc, char **argv)
78 {
79   struct partmap *p = partmap_open(argv[1], 0);
80   uns l = partmap_size(p);
81   uns i;
82   for (i=0; i<l; i++)
83     putchar(*(char *)partmap_map(p, i, 1));
84   partmap_close(p);
85   return 0;
86 }
87 #endif