sync with tizen_2.2
[sdk/emulator/qemu.git] / block / raw-win32.c
1 /*
2  * Block driver for RAW files (win32)
3  *
4  * Copyright (c) 2006 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu-common.h"
25 #include "qemu-timer.h"
26 #include "block_int.h"
27 #include "module.h"
28 #include <windows.h>
29 #include <winioctl.h>
30
31 #define FTYPE_FILE 0
32 #define FTYPE_CD     1
33 #define FTYPE_HARDDISK 2
34
35 typedef struct BDRVRawState {
36     HANDLE hfile;
37     int type;
38     char drive_path[16]; /* format: "d:\" */
39 } BDRVRawState;
40
41 int qemu_ftruncate64(int fd, int64_t length)
42 {
43     LARGE_INTEGER li;
44     DWORD dw;
45     LONG high;
46     HANDLE h;
47     BOOL res;
48
49     if ((GetVersion() & 0x80000000UL) && (length >> 32) != 0)
50         return -1;
51
52     h = (HANDLE)_get_osfhandle(fd);
53
54     /* get current position, ftruncate do not change position */
55     li.HighPart = 0;
56     li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_CURRENT);
57     if (li.LowPart == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
58         return -1;
59     }
60
61     high = length >> 32;
62     dw = SetFilePointer(h, (DWORD) length, &high, FILE_BEGIN);
63     if (dw == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
64         return -1;
65     }
66     res = SetEndOfFile(h);
67
68     /* back to old position */
69     SetFilePointer(h, li.LowPart, &li.HighPart, FILE_BEGIN);
70     return res ? 0 : -1;
71 }
72
73 static int set_sparse(int fd)
74 {
75     DWORD returned;
76     return (int) DeviceIoControl((HANDLE)_get_osfhandle(fd), FSCTL_SET_SPARSE,
77                                  NULL, 0, NULL, 0, &returned, NULL);
78 }
79
80 static int raw_open(BlockDriverState *bs, const char *filename, int flags)
81 {
82     BDRVRawState *s = bs->opaque;
83     int access_flags;
84     DWORD overlapped;
85
86     s->type = FTYPE_FILE;
87
88 #ifndef CONFIG_MARU
89     if (flags & BDRV_O_RDWR) {
90         access_flags = GENERIC_READ | GENERIC_WRITE;
91     } else {
92         access_flags = GENERIC_READ;
93     }
94
95     overlapped = FILE_ATTRIBUTE_NORMAL;
96     if (flags & BDRV_O_NOCACHE)
97         overlapped |= FILE_FLAG_NO_BUFFERING;
98     if (!(flags & BDRV_O_CACHE_WB))
99         overlapped |= FILE_FLAG_WRITE_THROUGH;
100     s->hfile = CreateFile(filename,
101                           access_flags,
102                           FILE_SHARE_READ, NULL,
103                           OPEN_EXISTING, overlapped, NULL);
104         if (s->hfile == INVALID_HANDLE_VALUE) {
105         int err = GetLastError();
106
107         if (err == ERROR_ACCESS_DENIED)
108             return -EACCES;
109         return -1;
110     }
111
112 #else
113 #include <errno.h>
114         int open_flags = O_BINARY;
115         open_flags &= ~O_ACCMODE;
116         if (flags & BDRV_O_RDWR) {
117                 open_flags |= O_RDWR;
118         } else {
119                 open_flags |= O_RDONLY;
120         }
121
122         /* Use O_DSYNC for write-through caching, no flags for write-back caching,
123      * and O_DIRECT for no caching. */
124         /*
125         if ((flags & BDRV_O_NOCACHE)) {
126                 open_flags |= O_DIRECT;
127         }
128     if (!(flags & BDRV_O_CACHE_WB)) {
129         open_flags |= O_DSYNC;
130         }
131         */
132
133         int ret = qemu_open(filename, open_flags, 0644);
134         if (ret < 0) {
135                 error_report("raw_open failed(%d) \n", ret);
136                 return -errno;
137         }
138         s->hfile = (HANDLE)_get_osfhandle(ret);
139
140 #endif
141        return 0;
142 }
143
144 static int raw_read(BlockDriverState *bs, int64_t sector_num,
145                     uint8_t *buf, int nb_sectors)
146 {
147     BDRVRawState *s = bs->opaque;
148     OVERLAPPED ov;
149     DWORD ret_count;
150     int ret;
151     int64_t offset = sector_num * 512;
152     int count = nb_sectors * 512;
153
154     memset(&ov, 0, sizeof(ov));
155     ov.Offset = offset;
156     ov.OffsetHigh = offset >> 32;
157     ret = ReadFile(s->hfile, buf, count, &ret_count, &ov);
158     if (!ret)
159         return ret_count;
160     if (ret_count == count)
161         ret_count = 0;
162     return ret_count;
163 }
164
165 static int raw_write(BlockDriverState *bs, int64_t sector_num,
166                      const uint8_t *buf, int nb_sectors)
167 {
168     BDRVRawState *s = bs->opaque;
169     OVERLAPPED ov;
170     DWORD ret_count;
171     int ret;
172     int64_t offset = sector_num * 512;
173     int count = nb_sectors * 512;
174
175     memset(&ov, 0, sizeof(ov));
176     ov.Offset = offset;
177     ov.OffsetHigh = offset >> 32;
178     ret = WriteFile(s->hfile, buf, count, &ret_count, &ov);
179     if (!ret)
180         return ret_count;
181     if (ret_count == count)
182         ret_count = 0;
183     return ret_count;
184 }
185
186 static int raw_flush(BlockDriverState *bs)
187 {
188     BDRVRawState *s = bs->opaque;
189     int ret;
190
191     ret = FlushFileBuffers(s->hfile);
192     if (ret == 0) {
193         return -EIO;
194     }
195
196     return 0;
197 }
198
199 static void raw_close(BlockDriverState *bs)
200 {
201     BDRVRawState *s = bs->opaque;
202     CloseHandle(s->hfile);
203 }
204
205 static int raw_truncate(BlockDriverState *bs, int64_t offset)
206 {
207     BDRVRawState *s = bs->opaque;
208     LONG low, high;
209
210     low = offset;
211     high = offset >> 32;
212     if (!SetFilePointer(s->hfile, low, &high, FILE_BEGIN))
213         return -EIO;
214     if (!SetEndOfFile(s->hfile))
215         return -EIO;
216     return 0;
217 }
218
219 static int64_t raw_getlength(BlockDriverState *bs)
220 {
221     BDRVRawState *s = bs->opaque;
222     LARGE_INTEGER l;
223     ULARGE_INTEGER available, total, total_free;
224     DISK_GEOMETRY_EX dg;
225     DWORD count;
226     BOOL status;
227
228     switch(s->type) {
229     case FTYPE_FILE:
230         l.LowPart = GetFileSize(s->hfile, (PDWORD)&l.HighPart);
231         if (l.LowPart == 0xffffffffUL && GetLastError() != NO_ERROR)
232             return -EIO;
233         break;
234     case FTYPE_CD:
235         if (!GetDiskFreeSpaceEx(s->drive_path, &available, &total, &total_free))
236             return -EIO;
237         l.QuadPart = total.QuadPart;
238         break;
239     case FTYPE_HARDDISK:
240         status = DeviceIoControl(s->hfile, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX,
241                                  NULL, 0, &dg, sizeof(dg), &count, NULL);
242         if (status != 0) {
243             l = dg.DiskSize;
244         }
245         break;
246     default:
247         return -EIO;
248     }
249     return l.QuadPart;
250 }
251
252 static int64_t raw_get_allocated_file_size(BlockDriverState *bs)
253 {
254     typedef DWORD (WINAPI * get_compressed_t)(const char *filename,
255                                               DWORD * high);
256     get_compressed_t get_compressed;
257     struct _stati64 st;
258     const char *filename = bs->filename;
259     /* WinNT support GetCompressedFileSize to determine allocate size */
260     get_compressed =
261         (get_compressed_t) GetProcAddress(GetModuleHandle("kernel32"),
262                                             "GetCompressedFileSizeA");
263     if (get_compressed) {
264         DWORD high, low;
265         low = get_compressed(filename, &high);
266         if (low != 0xFFFFFFFFlu || GetLastError() == NO_ERROR) {
267             return (((int64_t) high) << 32) + low;
268         }
269     }
270
271     if (_stati64(filename, &st) < 0) {
272         return -1;
273     }
274     return st.st_size;
275 }
276
277 static int raw_create(const char *filename, QEMUOptionParameter *options)
278 {
279     int fd;
280     int64_t total_size = 0;
281
282     /* Read out options */
283     while (options && options->name) {
284         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
285             total_size = options->value.n / 512;
286         }
287         options++;
288     }
289
290     fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,
291                    0644);
292     if (fd < 0)
293         return -EIO;
294     set_sparse(fd);
295     ftruncate(fd, total_size * 512);
296     qemu_close(fd);
297     return 0;
298 }
299
300 static QEMUOptionParameter raw_create_options[] = {
301     {
302         .name = BLOCK_OPT_SIZE,
303         .type = OPT_SIZE,
304         .help = "Virtual disk size"
305     },
306     { NULL }
307 };
308
309 static BlockDriver bdrv_file = {
310     .format_name        = "file",
311     .protocol_name      = "file",
312     .instance_size      = sizeof(BDRVRawState),
313     .bdrv_file_open     = raw_open,
314     .bdrv_close         = raw_close,
315     .bdrv_create        = raw_create,
316
317     .bdrv_read              = raw_read,
318     .bdrv_write             = raw_write,
319     .bdrv_co_flush_to_disk  = raw_flush,
320
321     .bdrv_truncate      = raw_truncate,
322     .bdrv_getlength     = raw_getlength,
323     .bdrv_get_allocated_file_size
324                         = raw_get_allocated_file_size,
325
326     .create_options = raw_create_options,
327 };
328
329 /***********************************************/
330 /* host device */
331
332 static int find_cdrom(char *cdrom_name, int cdrom_name_size)
333 {
334     char drives[256], *pdrv = drives;
335     UINT type;
336
337     memset(drives, 0, sizeof(drives));
338     GetLogicalDriveStrings(sizeof(drives), drives);
339     while(pdrv[0] != '\0') {
340         type = GetDriveType(pdrv);
341         switch(type) {
342         case DRIVE_CDROM:
343             snprintf(cdrom_name, cdrom_name_size, "\\\\.\\%c:", pdrv[0]);
344             return 0;
345             break;
346         }
347         pdrv += lstrlen(pdrv) + 1;
348     }
349     return -1;
350 }
351
352 static int find_device_type(BlockDriverState *bs, const char *filename)
353 {
354     BDRVRawState *s = bs->opaque;
355     UINT type;
356     const char *p;
357
358     if (strstart(filename, "\\\\.\\", &p) ||
359         strstart(filename, "//./", &p)) {
360         if (stristart(p, "PhysicalDrive", NULL))
361             return FTYPE_HARDDISK;
362         snprintf(s->drive_path, sizeof(s->drive_path), "%c:\\", p[0]);
363         type = GetDriveType(s->drive_path);
364         switch (type) {
365         case DRIVE_REMOVABLE:
366         case DRIVE_FIXED:
367             return FTYPE_HARDDISK;
368         case DRIVE_CDROM:
369             return FTYPE_CD;
370         default:
371             return FTYPE_FILE;
372         }
373     } else {
374         return FTYPE_FILE;
375     }
376 }
377
378 static int hdev_probe_device(const char *filename)
379 {
380     if (strstart(filename, "/dev/cdrom", NULL))
381         return 100;
382     if (is_windows_drive(filename))
383         return 100;
384     return 0;
385 }
386
387 static int hdev_open(BlockDriverState *bs, const char *filename, int flags)
388 {
389     BDRVRawState *s = bs->opaque;
390     int access_flags, create_flags;
391     DWORD overlapped;
392     char device_name[64];
393
394     if (strstart(filename, "/dev/cdrom", NULL)) {
395         if (find_cdrom(device_name, sizeof(device_name)) < 0)
396             return -ENOENT;
397         filename = device_name;
398     } else {
399         /* transform drive letters into device name */
400         if (((filename[0] >= 'a' && filename[0] <= 'z') ||
401              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
402             filename[1] == ':' && filename[2] == '\0') {
403             snprintf(device_name, sizeof(device_name), "\\\\.\\%c:", filename[0]);
404             filename = device_name;
405         }
406     }
407     s->type = find_device_type(bs, filename);
408
409 #ifndef CONFIG_MARU
410         if (flags & BDRV_O_RDWR) {
411         access_flags = GENERIC_READ | GENERIC_WRITE;
412     } else {
413         access_flags = GENERIC_READ;
414     }
415     create_flags = OPEN_EXISTING;
416
417     overlapped = FILE_ATTRIBUTE_NORMAL;
418     if (flags & BDRV_O_NOCACHE)
419         overlapped |= FILE_FLAG_NO_BUFFERING;
420     if (!(flags & BDRV_O_CACHE_WB))
421         overlapped |= FILE_FLAG_WRITE_THROUGH;
422
423     s->hfile = CreateFile(filename,
424                           access_flags,
425                           FILE_SHARE_READ, NULL,
426                           create_flags, overlapped, NULL);
427         if (s->hfile == INVALID_HANDLE_VALUE) {
428         int err = GetLastError();
429
430         if (err == ERROR_ACCESS_DENIED)
431             return -EACCES;
432         return -1;
433     }
434
435 #else
436         /*
437     s->hfile = CreateFile(g_win32_locale_filename_from_utf8(filename),
438                           access_flags,
439                           FILE_SHARE_READ, NULL,
440                           create_flags, overlapped, NULL);
441         */
442 #include <errno.h>
443
444         int open_flags = O_BINARY;
445         open_flags &= ~O_ACCMODE;
446         if (flags & BDRV_O_RDWR) {
447                 open_flags |= O_RDWR;
448         } else {
449                 open_flags |= O_RDONLY;
450         }
451
452         /* Use O_DSYNC for write-through caching, no flags for write-back caching,
453      * and O_DIRECT for no caching. */
454         /*
455         if ((flags & BDRV_O_NOCACHE)) {
456                 open_flags |= O_DIRECT;
457         }
458     if (!(flags & BDRV_O_CACHE_WB)) {
459         open_flags |= O_DSYNC;
460         }
461         */
462
463         int ret = qemu_open(filename, open_flags, 0644);
464         if (ret < 0) {
465                 error_report("raw_open failed(%d) \n", ret);
466                 return -errno;
467         }
468         s->hfile = (HANDLE)_get_osfhandle(ret);
469
470 #endif
471        return 0;
472 }
473
474 static int hdev_has_zero_init(BlockDriverState *bs)
475 {
476     return 0;
477 }
478
479 static BlockDriver bdrv_host_device = {
480     .format_name        = "host_device",
481     .protocol_name      = "host_device",
482     .instance_size      = sizeof(BDRVRawState),
483     .bdrv_probe_device  = hdev_probe_device,
484     .bdrv_file_open     = hdev_open,
485     .bdrv_close         = raw_close,
486     .bdrv_has_zero_init = hdev_has_zero_init,
487
488     .bdrv_read              = raw_read,
489     .bdrv_write             = raw_write,
490     .bdrv_co_flush_to_disk  = raw_flush,
491
492     .bdrv_getlength     = raw_getlength,
493     .bdrv_get_allocated_file_size
494                         = raw_get_allocated_file_size,
495 };
496
497 static void bdrv_file_init(void)
498 {
499     bdrv_register(&bdrv_file);
500     bdrv_register(&bdrv_host_device);
501 }
502
503 block_init(bdrv_file_init);