2 * UCW Library -- FastIO on files with run-time parametrization
4 * (c) 2007 Pavel Charvat <pchar@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
13 #include "lib/fastbuf.h"
18 struct fb_params fbpar_def = {
24 struct cf_section fbpar_cf = {
25 # define F(x) PTR_TO(struct fb_params, x)
26 CF_TYPE(struct fb_params),
28 CF_LOOKUP("Type", (int *)F(type), ((byte *[]){"std", "direct", "mmap", NULL})),
29 CF_UNS("BufSize", F(buffer_size)),
30 CF_UNS("KeepBackBuf", F(keep_back_buf)),
31 CF_UNS("ReadAhead", F(read_ahead)),
32 CF_UNS("WriteBack", F(write_back)),
38 static struct cf_section fbpar_global_cf = {
40 CF_SECTION("Defaults", &fbpar_def, &fbpar_cf),
45 static void CONSTRUCTOR
46 fbpar_global_init(void)
48 cf_declare_section("FBParam", &fbpar_global_cf, 0);
51 static struct fastbuf *
52 bopen_fd_internal(int fd, struct fb_params *params, uns mode, byte *name)
56 sprintf(name = buf, "fd%d", fd);
61 fb = bfdopen_internal(fd, name,
62 params->buffer_size ? : fbpar_def.buffer_size);
63 if (params->keep_back_buf)
64 bconfig(fb, BCONFIG_KEEP_BACK_BUF, 1);
67 fb = fbdir_open_fd_internal(fd, name, params->asio,
68 params->buffer_size ? : fbpar_def.buffer_size,
69 params->read_ahead ? : fbpar_def.read_ahead,
70 params->write_back ? : fbpar_def.write_back);
71 if (!~mode && !fbdir_cheat && ((int)(mode = fcntl(fd, F_GETFL)) < 0 || fcntl(fd, F_SETFL, mode | O_DIRECT)) < 0)
72 log(L_WARN, "Cannot set O_DIRECT on fd %d: %m", fd);
75 if (!~mode && (int)(mode = fcntl(fd, F_GETFL)) < 0)
76 die("Cannot get flags of fd %d: %m", fd);
77 return bfmmopen_internal(fd, name, mode);
83 static struct fastbuf *
84 bopen_file_internal(byte *name, int mode, struct fb_params *params, int try)
86 if (params->type == FB_DIRECT && !fbdir_cheat)
88 if (params->type == FB_MMAP && (mode & O_ACCMODE) == O_WRONLY)
89 mode = (mode & ~O_ACCMODE) | O_RDWR;
90 int fd = sh_open(name, mode, 0666);
95 die("Unable to %s file %s: %m", (mode & O_CREAT) ? "create" : "open", name);
96 struct fastbuf *fb = bopen_fd_internal(fd, params, mode, name);
99 bseek(fb, 0, SEEK_END);
104 bopen_file(byte *name, int mode, struct fb_params *params)
106 return bopen_file_internal(name, mode, params ? : &fbpar_def, 0);
110 bopen_file_try(byte *name, int mode, struct fb_params *params)
112 return bopen_file_internal(name, mode, params ? : &fbpar_def, 1);
116 bopen_fd(int fd, struct fb_params *params)
118 return bopen_fd_internal(fd, params ? : &fbpar_def, ~0U, NULL);
122 bopen_tmp_file(struct fb_params *params)
124 byte buf[TEMP_FILE_NAME_LEN];
126 struct fastbuf *fb = bopen_file_internal(buf, O_RDWR | O_CREAT | O_TRUNC, params, 0);
127 bconfig(fb, BCONFIG_IS_TEMP_FILE, 1);