vserver 1.9.5.x5
[linux-2.6.git] / arch / um / drivers / ubd_kern.c
1 /* 
2  * Copyright (C) 2000 Jeff Dike (jdike@karaya.com)
3  * Licensed under the GPL
4  */
5
6 /* 2001-09-28...2002-04-17
7  * Partition stuff by James_McMechan@hotmail.com
8  * old style ubd by setting UBD_SHIFT to 0
9  * 2002-09-27...2002-10-18 massive tinkering for 2.5
10  * partitions have changed in 2.5
11  * 2003-01-29 more tinkering for 2.5.59-1
12  * This should now address the sysfs problems and has
13  * the symlink for devfs to allow for booting with
14  * the common /dev/ubd/discX/... names rather than
15  * only /dev/ubdN/discN this version also has lots of
16  * clean ups preparing for ubd-many.
17  * James McMechan
18  */
19
20 #define MAJOR_NR UBD_MAJOR
21 #define UBD_SHIFT 4
22
23 #include "linux/config.h"
24 #include "linux/module.h"
25 #include "linux/blkdev.h"
26 #include "linux/hdreg.h"
27 #include "linux/init.h"
28 #include "linux/devfs_fs_kernel.h"
29 #include "linux/cdrom.h"
30 #include "linux/proc_fs.h"
31 #include "linux/ctype.h"
32 #include "linux/capability.h"
33 #include "linux/mm.h"
34 #include "linux/vmalloc.h"
35 #include "linux/blkpg.h"
36 #include "linux/genhd.h"
37 #include "linux/spinlock.h"
38 #include "asm/segment.h"
39 #include "asm/uaccess.h"
40 #include "asm/irq.h"
41 #include "asm/types.h"
42 #include "asm/tlbflush.h"
43 #include "user_util.h"
44 #include "mem_user.h"
45 #include "kern_util.h"
46 #include "kern.h"
47 #include "mconsole_kern.h"
48 #include "init.h"
49 #include "irq_user.h"
50 #include "irq_kern.h"
51 #include "ubd_user.h"
52 #include "2_5compat.h"
53 #include "os.h"
54 #include "mem.h"
55 #include "mem_kern.h"
56 #include "cow.h"
57
58 enum ubd_req { UBD_READ, UBD_WRITE, UBD_MMAP };
59
60 struct io_thread_req {
61         enum ubd_req op;
62         int fds[2];
63         unsigned long offsets[2];
64         unsigned long long offset;
65         unsigned long length;
66         char *buffer;
67         int sectorsize;
68         unsigned long sector_mask;
69         unsigned long long cow_offset;
70         unsigned long bitmap_words[2];
71         int map_fd;
72         unsigned long long map_offset;
73         int error;
74 };
75
76 extern int open_ubd_file(char *file, struct openflags *openflags,
77                          char **backing_file_out, int *bitmap_offset_out,
78                          unsigned long *bitmap_len_out, int *data_offset_out,
79                          int *create_cow_out);
80 extern int create_cow_file(char *cow_file, char *backing_file,
81                            struct openflags flags, int sectorsize,
82                            int alignment, int *bitmap_offset_out,
83                            unsigned long *bitmap_len_out,
84                            int *data_offset_out);
85 extern int read_cow_bitmap(int fd, void *buf, int offset, int len);
86 extern void do_io(struct io_thread_req *req);
87
88 static inline int ubd_test_bit(__u64 bit, unsigned char *data)
89 {
90         __u64 n;
91         int bits, off;
92
93         bits = sizeof(data[0]) * 8;
94         n = bit / bits;
95         off = bit % bits;
96         return((data[n] & (1 << off)) != 0);
97 }
98
99 static inline void ubd_set_bit(__u64 bit, unsigned char *data)
100 {
101         __u64 n;
102         int bits, off;
103
104         bits = sizeof(data[0]) * 8;
105         n = bit / bits;
106         off = bit % bits;
107         data[n] |= (1 << off);
108 }
109 /*End stuff from ubd_user.h*/
110
111 #define DRIVER_NAME "uml-blkdev"
112
113 static DEFINE_SPINLOCK(ubd_io_lock);
114 static DEFINE_SPINLOCK(ubd_lock);
115
116 static void (*do_ubd)(void);
117
118 static int ubd_open(struct inode * inode, struct file * filp);
119 static int ubd_release(struct inode * inode, struct file * file);
120 static int ubd_ioctl(struct inode * inode, struct file * file,
121                      unsigned int cmd, unsigned long arg);
122
123 #define MAX_DEV (8)
124
125 /* Changed in early boot */
126 static int ubd_do_mmap = 0;
127 #define UBD_MMAP_BLOCK_SIZE PAGE_SIZE
128
129 static struct block_device_operations ubd_blops = {
130         .owner          = THIS_MODULE,
131         .open           = ubd_open,
132         .release        = ubd_release,
133         .ioctl          = ubd_ioctl,
134 };
135
136 /* Protected by the queue_lock */
137 static request_queue_t *ubd_queue;
138
139 /* Protected by ubd_lock */
140 static int fake_major = MAJOR_NR;
141
142 static struct gendisk *ubd_gendisk[MAX_DEV];
143 static struct gendisk *fake_gendisk[MAX_DEV];
144  
145 #ifdef CONFIG_BLK_DEV_UBD_SYNC
146 #define OPEN_FLAGS ((struct openflags) { .r = 1, .w = 1, .s = 1, .c = 0, \
147                                          .cl = 1 })
148 #else
149 #define OPEN_FLAGS ((struct openflags) { .r = 1, .w = 1, .s = 0, .c = 0, \
150                                          .cl = 1 })
151 #endif
152
153 /* Not protected - changed only in ubd_setup_common and then only to
154  * to enable O_SYNC.
155  */
156 static struct openflags global_openflags = OPEN_FLAGS;
157
158 struct cow {
159         char *file;
160         int fd;
161         unsigned long *bitmap;
162         unsigned long bitmap_len;
163         int bitmap_offset;
164         int data_offset;
165 };
166
167 struct ubd {
168         char *file;
169         int count;
170         int fd;
171         __u64 size;
172         struct openflags boot_openflags;
173         struct openflags openflags;
174         int no_cow;
175         struct cow cow;
176         struct platform_device pdev;
177
178         int map_writes;
179         int map_reads;
180         int nomap_writes;
181         int nomap_reads;
182         int write_maps;
183 };
184
185 #define DEFAULT_COW { \
186         .file =                 NULL, \
187         .fd =                   -1, \
188         .bitmap =               NULL, \
189         .bitmap_offset =        0, \
190         .data_offset =          0, \
191 }
192
193 #define DEFAULT_UBD { \
194         .file =                 NULL, \
195         .count =                0, \
196         .fd =                   -1, \
197         .size =                 -1, \
198         .boot_openflags =       OPEN_FLAGS, \
199         .openflags =            OPEN_FLAGS, \
200         .no_cow =               0, \
201         .cow =                  DEFAULT_COW, \
202         .map_writes             = 0, \
203         .map_reads              = 0, \
204         .nomap_writes           = 0, \
205         .nomap_reads            = 0, \
206         .write_maps             = 0, \
207 }
208
209 struct ubd ubd_dev[MAX_DEV] = { [ 0 ... MAX_DEV - 1 ] = DEFAULT_UBD };
210
211 static int ubd0_init(void)
212 {
213         struct ubd *dev = &ubd_dev[0];
214
215         if(dev->file == NULL)
216                 dev->file = "root_fs";
217         return(0);
218 }
219
220 __initcall(ubd0_init);
221
222 /* Only changed by fake_ide_setup which is a setup */
223 static int fake_ide = 0;
224 static struct proc_dir_entry *proc_ide_root = NULL;
225 static struct proc_dir_entry *proc_ide = NULL;
226
227 static void make_proc_ide(void)
228 {
229         proc_ide_root = proc_mkdir("ide", NULL);
230         proc_ide = proc_mkdir("ide0", proc_ide_root);
231 }
232
233 static int proc_ide_read_media(char *page, char **start, off_t off, int count,
234                                int *eof, void *data)
235 {
236         int len;
237
238         strcpy(page, "disk\n");
239         len = strlen("disk\n");
240         len -= off;
241         if (len < count){
242                 *eof = 1;
243                 if (len <= 0) return 0;
244         }
245         else len = count;
246         *start = page + off;
247         return len;
248 }
249
250 static void make_ide_entries(char *dev_name)
251 {
252         struct proc_dir_entry *dir, *ent;
253         char name[64];
254
255         if(proc_ide_root == NULL) make_proc_ide();
256
257         dir = proc_mkdir(dev_name, proc_ide);
258         if(!dir) return;
259
260         ent = create_proc_entry("media", S_IFREG|S_IRUGO, dir);
261         if(!ent) return;
262         ent->nlink = 1;
263         ent->data = NULL;
264         ent->read_proc = proc_ide_read_media;
265         ent->write_proc = NULL;
266         sprintf(name,"ide0/%s", dev_name);
267         proc_symlink(dev_name, proc_ide_root, name);
268 }
269
270 static int fake_ide_setup(char *str)
271 {
272         fake_ide = 1;
273         return(1);
274 }
275
276 __setup("fake_ide", fake_ide_setup);
277
278 __uml_help(fake_ide_setup,
279 "fake_ide\n"
280 "    Create ide0 entries that map onto ubd devices.\n\n"
281 );
282
283 static int parse_unit(char **ptr)
284 {
285         char *str = *ptr, *end;
286         int n = -1;
287
288         if(isdigit(*str)) {
289                 n = simple_strtoul(str, &end, 0);
290                 if(end == str)
291                         return(-1);
292                 *ptr = end;
293         }
294         else if (('a' <= *str) && (*str <= 'h')) {
295                 n = *str - 'a';
296                 str++;
297                 *ptr = str;
298         }
299         return(n);
300 }
301
302 static int ubd_setup_common(char *str, int *index_out)
303 {
304         struct ubd *dev;
305         struct openflags flags = global_openflags;
306         char *backing_file;
307         int n, err, i;
308
309         if(index_out) *index_out = -1;
310         n = *str;
311         if(n == '='){
312                 char *end;
313                 int major;
314
315                 str++;
316                 if(!strcmp(str, "mmap")){
317                         CHOOSE_MODE(printk("mmap not supported by the ubd "
318                                            "driver in tt mode\n"),
319                                     ubd_do_mmap = 1);
320                         return(0);
321                 }
322
323                 if(!strcmp(str, "sync")){
324                         global_openflags = of_sync(global_openflags);
325                         return(0);
326                 }
327                 major = simple_strtoul(str, &end, 0);
328                 if((*end != '\0') || (end == str)){
329                         printk(KERN_ERR 
330                                "ubd_setup : didn't parse major number\n");
331                         return(1);
332                 }
333
334                 err = 1;
335                 spin_lock(&ubd_lock);
336                 if(fake_major != MAJOR_NR){
337                         printk(KERN_ERR "Can't assign a fake major twice\n");
338                         goto out1;
339                 }
340  
341                 fake_major = major;
342
343                 printk(KERN_INFO "Setting extra ubd major number to %d\n",
344                        major);
345                 err = 0;
346         out1:
347                 spin_unlock(&ubd_lock);
348                 return(err);
349         }
350
351         n = parse_unit(&str);
352         if(n < 0){
353                 printk(KERN_ERR "ubd_setup : couldn't parse unit number "
354                        "'%s'\n", str);
355                 return(1);
356         }
357         if(n >= MAX_DEV){
358                 printk(KERN_ERR "ubd_setup : index %d out of range "
359                        "(%d devices, from 0 to %d)\n", n, MAX_DEV, MAX_DEV - 1);
360                 return(1);
361         }
362
363         err = 1;
364         spin_lock(&ubd_lock);
365
366         dev = &ubd_dev[n];
367         if(dev->file != NULL){
368                 printk(KERN_ERR "ubd_setup : device already configured\n");
369                 goto out;
370         }
371
372         if (index_out)
373                 *index_out = n;
374
375         for (i = 0; i < 4; i++) {
376                 switch (*str) {
377                 case 'r':
378                         flags.w = 0;
379                         break;
380                 case 's':
381                         flags.s = 1;
382                         break;
383                 case 'd':
384                         dev->no_cow = 1;
385                         break;
386                 case '=':
387                         str++;
388                         goto break_loop;
389                 default:
390                         printk(KERN_ERR "ubd_setup : Expected '=' or flag letter (r,s or d)\n");
391                         goto out;
392                 }
393                 str++;
394         }
395
396         if (*str == '=')
397                 printk(KERN_ERR "ubd_setup : Too many flags specified\n");
398         else
399                 printk(KERN_ERR "ubd_setup : Expected '='\n");
400         goto out;
401
402 break_loop:
403         err = 0;
404         backing_file = strchr(str, ',');
405
406         if (!backing_file) {
407                 backing_file = strchr(str, ':');
408         }
409
410         if(backing_file){
411                 if(dev->no_cow)
412                         printk(KERN_ERR "Can't specify both 'd' and a "
413                                "cow file\n");
414                 else {
415                         *backing_file = '\0';
416                         backing_file++;
417                 }
418         }
419         dev->file = str;
420         dev->cow.file = backing_file;
421         dev->boot_openflags = flags;
422 out:
423         spin_unlock(&ubd_lock);
424         return(err);
425 }
426
427 static int ubd_setup(char *str)
428 {
429         ubd_setup_common(str, NULL);
430         return(1);
431 }
432
433 __setup("ubd", ubd_setup);
434 __uml_help(ubd_setup,
435 "ubd<n><flags>=<filename>[(:|,)<filename2>]\n"
436 "    This is used to associate a device with a file in the underlying\n"
437 "    filesystem. When specifying two filenames, the first one is the\n"
438 "    COW name and the second is the backing file name. As separator you can\n"
439 "    use either a ':' or a ',': the first one allows writing things like;\n"
440 "       ubd0=~/Uml/root_cow:~/Uml/root_backing_file\n"
441 "    while with a ',' the shell would not expand the 2nd '~'.\n"
442 "    When using only one filename, UML will detect whether to thread it like\n"
443 "    a COW file or a backing file. To override this detection, add the 'd'\n"
444 "    flag:\n"
445 "       ubd0d=BackingFile\n"
446 "    Usually, there is a filesystem in the file, but \n"
447 "    that's not required. Swap devices containing swap files can be\n"
448 "    specified like this. Also, a file which doesn't contain a\n"
449 "    filesystem can have its contents read in the virtual \n"
450 "    machine by running 'dd' on the device. <n> must be in the range\n"
451 "    0 to 7. Appending an 'r' to the number will cause that device\n"
452 "    to be mounted read-only. For example ubd1r=./ext_fs. Appending\n"
453 "    an 's' will cause data to be written to disk on the host immediately.\n\n"
454 );
455
456 static int fakehd_set = 0;
457 static int fakehd(char *str)
458 {
459         printk(KERN_INFO "fakehd : Changing ubd name to \"hd\".\n");
460         fakehd_set = 1;
461         return 1;
462 }
463
464 __setup("fakehd", fakehd);
465 __uml_help(fakehd,
466 "fakehd\n"
467 "    Change the ubd device name to \"hd\".\n\n"
468 );
469
470 static void do_ubd_request(request_queue_t * q);
471
472 /* Only changed by ubd_init, which is an initcall. */
473 int thread_fd = -1;
474
475 /* Changed by ubd_handler, which is serialized because interrupts only
476  * happen on CPU 0.
477  */
478 int intr_count = 0;
479
480 /* call ubd_finish if you need to serialize */
481 static void __ubd_finish(struct request *req, int error)
482 {
483         int nsect;
484
485         if(error){
486                 end_request(req, 0);
487                 return;
488         }
489         nsect = req->current_nr_sectors;
490         req->sector += nsect;
491         req->buffer += nsect << 9;
492         req->errors = 0;
493         req->nr_sectors -= nsect;
494         req->current_nr_sectors = 0;
495         end_request(req, 1);
496 }
497
498 static inline void ubd_finish(struct request *req, int error)
499 {
500         spin_lock(&ubd_io_lock);
501         __ubd_finish(req, error);
502         spin_unlock(&ubd_io_lock);
503 }
504
505 /* Called without ubd_io_lock held */
506 static void ubd_handler(void)
507 {
508         struct io_thread_req req;
509         struct request *rq = elv_next_request(ubd_queue);
510         int n, err;
511
512         do_ubd = NULL;
513         intr_count++;
514         n = os_read_file(thread_fd, &req, sizeof(req));
515         if(n != sizeof(req)){
516                 printk(KERN_ERR "Pid %d - spurious interrupt in ubd_handler, "
517                        "err = %d\n", os_getpid(), -n);
518                 spin_lock(&ubd_io_lock);
519                 end_request(rq, 0);
520                 spin_unlock(&ubd_io_lock);
521                 return;
522         }
523         
524         if((req.op != UBD_MMAP) &&
525            ((req.offset != ((__u64) (rq->sector)) << 9) ||
526             (req.length != (rq->current_nr_sectors) << 9)))
527                 panic("I/O op mismatch");
528         
529         if(req.map_fd != -1){
530                 err = physmem_subst_mapping(req.buffer, req.map_fd,
531                                             req.map_offset, 1);
532                 if(err)
533                         printk("ubd_handler - physmem_subst_mapping failed, "
534                                "err = %d\n", -err);
535         }
536
537         ubd_finish(rq, req.error);
538         reactivate_fd(thread_fd, UBD_IRQ);      
539         do_ubd_request(ubd_queue);
540 }
541
542 static irqreturn_t ubd_intr(int irq, void *dev, struct pt_regs *unused)
543 {
544         ubd_handler();
545         return(IRQ_HANDLED);
546 }
547
548 /* Only changed by ubd_init, which is an initcall. */
549 static int io_pid = -1;
550
551 void kill_io_thread(void)
552 {
553         if(io_pid != -1) 
554                 os_kill_process(io_pid, 1);
555 }
556
557 __uml_exitcall(kill_io_thread);
558
559 static int ubd_file_size(struct ubd *dev, __u64 *size_out)
560 {
561         char *file;
562
563         file = dev->cow.file ? dev->cow.file : dev->file;
564         return(os_file_size(file, size_out));
565 }
566
567 static void ubd_close(struct ubd *dev)
568 {
569         if(ubd_do_mmap)
570                 physmem_forget_descriptor(dev->fd);
571         os_close_file(dev->fd);
572         if(dev->cow.file == NULL)
573                 return;
574
575         if(ubd_do_mmap)
576                 physmem_forget_descriptor(dev->cow.fd);
577         os_close_file(dev->cow.fd);
578         vfree(dev->cow.bitmap);
579         dev->cow.bitmap = NULL;
580 }
581
582 static int ubd_open_dev(struct ubd *dev)
583 {
584         struct openflags flags;
585         char **back_ptr;
586         int err, create_cow, *create_ptr;
587
588         dev->openflags = dev->boot_openflags;
589         create_cow = 0;
590         create_ptr = (dev->cow.file != NULL) ? &create_cow : NULL;
591         back_ptr = dev->no_cow ? NULL : &dev->cow.file;
592         dev->fd = open_ubd_file(dev->file, &dev->openflags, back_ptr,
593                                 &dev->cow.bitmap_offset, &dev->cow.bitmap_len, 
594                                 &dev->cow.data_offset, create_ptr);
595
596         if((dev->fd == -ENOENT) && create_cow){
597                 dev->fd = create_cow_file(dev->file, dev->cow.file, 
598                                           dev->openflags, 1 << 9, PAGE_SIZE,
599                                           &dev->cow.bitmap_offset, 
600                                           &dev->cow.bitmap_len,
601                                           &dev->cow.data_offset);
602                 if(dev->fd >= 0){
603                         printk(KERN_INFO "Creating \"%s\" as COW file for "
604                                "\"%s\"\n", dev->file, dev->cow.file);
605                 }
606         }
607
608         if(dev->fd < 0) return(dev->fd);
609
610         if(dev->cow.file != NULL){
611                 err = -ENOMEM;
612                 dev->cow.bitmap = (void *) vmalloc(dev->cow.bitmap_len);
613                 if(dev->cow.bitmap == NULL){
614                         printk(KERN_ERR "Failed to vmalloc COW bitmap\n");
615                         goto error;
616                 }
617                 flush_tlb_kernel_vm();
618
619                 err = read_cow_bitmap(dev->fd, dev->cow.bitmap, 
620                                       dev->cow.bitmap_offset, 
621                                       dev->cow.bitmap_len);
622                 if(err < 0)
623                         goto error;
624
625                 flags = dev->openflags;
626                 flags.w = 0;
627                 err = open_ubd_file(dev->cow.file, &flags, NULL, NULL, NULL, 
628                                     NULL, NULL);
629                 if(err < 0) goto error;
630                 dev->cow.fd = err;
631         }
632         return(0);
633  error:
634         os_close_file(dev->fd);
635         return(err);
636 }
637
638 static int ubd_new_disk(int major, u64 size, int unit,
639                         struct gendisk **disk_out)
640                         
641 {
642         struct gendisk *disk;
643         char from[sizeof("ubd/nnnnn\0")], to[sizeof("discnnnnn/disc\0")];
644         int err;
645
646         disk = alloc_disk(1 << UBD_SHIFT);
647         if(disk == NULL)
648                 return(-ENOMEM);
649
650         disk->major = major;
651         disk->first_minor = unit << UBD_SHIFT;
652         disk->fops = &ubd_blops;
653         set_capacity(disk, size / 512);
654         if(major == MAJOR_NR){
655                 sprintf(disk->disk_name, "ubd%c", 'a' + unit);
656                 sprintf(disk->devfs_name, "ubd/disc%d", unit);
657                 sprintf(from, "ubd/%d", unit);
658                 sprintf(to, "disc%d/disc", unit);
659                 err = devfs_mk_symlink(from, to);
660                 if(err)
661                         printk("ubd_new_disk failed to make link from %s to "
662                                "%s, error = %d\n", from, to, err);
663         }
664         else {
665                 sprintf(disk->disk_name, "ubd_fake%d", unit);
666                 sprintf(disk->devfs_name, "ubd_fake/disc%d", unit);
667         }
668
669         /* sysfs register (not for ide fake devices) */
670         if (major == MAJOR_NR) {
671                 ubd_dev[unit].pdev.id   = unit;
672                 ubd_dev[unit].pdev.name = DRIVER_NAME;
673                 platform_device_register(&ubd_dev[unit].pdev);
674                 disk->driverfs_dev = &ubd_dev[unit].pdev.dev;
675         }
676
677         disk->private_data = &ubd_dev[unit];
678         disk->queue = ubd_queue;
679         add_disk(disk);
680
681         *disk_out = disk;
682         return 0;
683 }
684
685 #define ROUND_BLOCK(n) ((n + ((1 << 9) - 1)) & (-1 << 9))
686
687 static int ubd_add(int n)
688 {
689         struct ubd *dev = &ubd_dev[n];
690         int err;
691
692         if(dev->file == NULL)
693                 return(-ENODEV);
694
695         if (ubd_open_dev(dev))
696                 return(-ENODEV);
697
698         err = ubd_file_size(dev, &dev->size);
699         if(err < 0)
700                 return(err);
701
702         dev->size = ROUND_BLOCK(dev->size);
703
704         err = ubd_new_disk(MAJOR_NR, dev->size, n, &ubd_gendisk[n]);
705         if(err) 
706                 return(err);
707  
708         if(fake_major != MAJOR_NR)
709                 ubd_new_disk(fake_major, dev->size, n, 
710                              &fake_gendisk[n]);
711
712         /* perhaps this should also be under the "if (fake_major)" above */
713         /* using the fake_disk->disk_name and also the fakehd_set name */
714         if (fake_ide)
715                 make_ide_entries(ubd_gendisk[n]->disk_name);
716
717         ubd_close(dev);
718         return 0;
719 }
720
721 static int ubd_config(char *str)
722 {
723         int n, err;
724
725         str = uml_strdup(str);
726         if(str == NULL){
727                 printk(KERN_ERR "ubd_config failed to strdup string\n");
728                 return(1);
729         }
730         err = ubd_setup_common(str, &n);
731         if(err){
732                 kfree(str);
733                 return(-1);
734         }
735         if(n == -1) return(0);
736
737         spin_lock(&ubd_lock);
738         err = ubd_add(n);
739         if(err)
740                 ubd_dev[n].file = NULL;
741         spin_unlock(&ubd_lock);
742
743         return(err);
744 }
745
746 static int ubd_get_config(char *name, char *str, int size, char **error_out)
747 {
748         struct ubd *dev;
749         char *end;
750         int n, len = 0;
751
752         n = simple_strtoul(name, &end, 0);
753         if((*end != '\0') || (end == name)){
754                 *error_out = "ubd_get_config : didn't parse device number";
755                 return(-1);
756         }
757
758         if((n >= MAX_DEV) || (n < 0)){
759                 *error_out = "ubd_get_config : device number out of range";
760                 return(-1);
761         }
762
763         dev = &ubd_dev[n];
764         spin_lock(&ubd_lock);
765
766         if(dev->file == NULL){
767                 CONFIG_CHUNK(str, size, len, "", 1);
768                 goto out;
769         }
770
771         CONFIG_CHUNK(str, size, len, dev->file, 0);
772
773         if(dev->cow.file != NULL){
774                 CONFIG_CHUNK(str, size, len, ",", 0);
775                 CONFIG_CHUNK(str, size, len, dev->cow.file, 1);
776         }
777         else CONFIG_CHUNK(str, size, len, "", 1);
778
779  out:
780         spin_unlock(&ubd_lock);
781         return(len);
782 }
783
784 static int ubd_remove(char *str)
785 {
786         struct ubd *dev;
787         int n, err = -ENODEV;
788
789         n = parse_unit(&str);
790
791         if((n < 0) || (n >= MAX_DEV))
792                 return(err);
793
794         dev = &ubd_dev[n];
795         if(dev->count > 0)
796                 return(-EBUSY); /* you cannot remove a open disk */
797
798         err = 0;
799         spin_lock(&ubd_lock);
800
801         if(ubd_gendisk[n] == NULL)
802                 goto out;
803
804         del_gendisk(ubd_gendisk[n]);
805         put_disk(ubd_gendisk[n]);
806         ubd_gendisk[n] = NULL;
807
808         if(fake_gendisk[n] != NULL){
809                 del_gendisk(fake_gendisk[n]);
810                 put_disk(fake_gendisk[n]);
811                 fake_gendisk[n] = NULL;
812         }
813
814         platform_device_unregister(&dev->pdev);
815         *dev = ((struct ubd) DEFAULT_UBD);
816         err = 0;
817  out:
818         spin_unlock(&ubd_lock);
819         return(err);
820 }
821
822 static struct mc_device ubd_mc = {
823         .name           = "ubd",
824         .config         = ubd_config,
825         .get_config     = ubd_get_config,
826         .remove         = ubd_remove,
827 };
828
829 static int ubd_mc_init(void)
830 {
831         mconsole_register_dev(&ubd_mc);
832         return 0;
833 }
834
835 __initcall(ubd_mc_init);
836
837 static struct device_driver ubd_driver = {
838         .name  = DRIVER_NAME,
839         .bus   = &platform_bus_type,
840 };
841
842 int ubd_init(void)
843 {
844         int i;
845
846         devfs_mk_dir("ubd");
847         if (register_blkdev(MAJOR_NR, "ubd"))
848                 return -1;
849
850         ubd_queue = blk_init_queue(do_ubd_request, &ubd_io_lock);
851         if (!ubd_queue) {
852                 unregister_blkdev(MAJOR_NR, "ubd");
853                 return -1;
854         }
855                 
856         if (fake_major != MAJOR_NR) {
857                 char name[sizeof("ubd_nnn\0")];
858
859                 snprintf(name, sizeof(name), "ubd_%d", fake_major);
860                 devfs_mk_dir(name);
861                 if (register_blkdev(fake_major, "ubd"))
862                         return -1;
863         }
864         driver_register(&ubd_driver);
865         for (i = 0; i < MAX_DEV; i++) 
866                 ubd_add(i);
867         return 0;
868 }
869
870 late_initcall(ubd_init);
871
872 int ubd_driver_init(void){
873         unsigned long stack;
874         int err;
875
876         /* Set by CONFIG_BLK_DEV_UBD_SYNC or ubd=sync.*/
877         if(global_openflags.s){
878                 printk(KERN_INFO "ubd: Synchronous mode\n");
879                 /* Letting ubd=sync be like using ubd#s= instead of ubd#= is
880                  * enough. So use anyway the io thread. */
881         }
882         stack = alloc_stack(0, 0);
883         io_pid = start_io_thread(stack + PAGE_SIZE - sizeof(void *), 
884                                  &thread_fd);
885         if(io_pid < 0){
886                 printk(KERN_ERR 
887                        "ubd : Failed to start I/O thread (errno = %d) - "
888                        "falling back to synchronous I/O\n", -io_pid);
889                 io_pid = -1;
890                 return(0);
891         }
892         err = um_request_irq(UBD_IRQ, thread_fd, IRQ_READ, ubd_intr, 
893                              SA_INTERRUPT, "ubd", ubd_dev);
894         if(err != 0)
895                 printk(KERN_ERR "um_request_irq failed - errno = %d\n", -err);
896         return(err);
897 }
898
899 device_initcall(ubd_driver_init);
900
901 static int ubd_open(struct inode *inode, struct file *filp)
902 {
903         struct gendisk *disk = inode->i_bdev->bd_disk;
904         struct ubd *dev = disk->private_data;
905         int err = 0;
906
907         if(dev->count == 0){
908                 err = ubd_open_dev(dev);
909                 if(err){
910                         printk(KERN_ERR "%s: Can't open \"%s\": errno = %d\n",
911                                disk->disk_name, dev->file, -err);
912                         goto out;
913                 }
914         }
915         dev->count++;
916         if((filp->f_mode & FMODE_WRITE) && !dev->openflags.w){
917                 if(--dev->count == 0) ubd_close(dev);
918                 err = -EROFS;
919         }
920  out:
921         return(err);
922 }
923
924 static int ubd_release(struct inode * inode, struct file * file)
925 {
926         struct gendisk *disk = inode->i_bdev->bd_disk;
927         struct ubd *dev = disk->private_data;
928
929         if(--dev->count == 0)
930                 ubd_close(dev);
931         return(0);
932 }
933
934 static void cowify_bitmap(__u64 io_offset, int length, unsigned long *cow_mask,
935                           __u64 *cow_offset, unsigned long *bitmap,
936                           __u64 bitmap_offset, unsigned long *bitmap_words,
937                           __u64 bitmap_len)
938 {
939         __u64 sector = io_offset >> 9;
940         int i, update_bitmap = 0;
941
942         for(i = 0; i < length >> 9; i++){
943                 if(cow_mask != NULL)
944                         ubd_set_bit(i, (unsigned char *) cow_mask);
945                 if(ubd_test_bit(sector + i, (unsigned char *) bitmap))
946                         continue;
947
948                 update_bitmap = 1;
949                 ubd_set_bit(sector + i, (unsigned char *) bitmap);
950         }
951
952         if(!update_bitmap)
953                 return;
954
955         *cow_offset = sector / (sizeof(unsigned long) * 8);
956
957         /* This takes care of the case where we're exactly at the end of the
958          * device, and *cow_offset + 1 is off the end.  So, just back it up
959          * by one word.  Thanks to Lynn Kerby for the fix and James McMechan
960          * for the original diagnosis.
961          */
962         if(*cow_offset == ((bitmap_len + sizeof(unsigned long) - 1) /
963                            sizeof(unsigned long) - 1))
964                 (*cow_offset)--;
965
966         bitmap_words[0] = bitmap[*cow_offset];
967         bitmap_words[1] = bitmap[*cow_offset + 1];
968
969         *cow_offset *= sizeof(unsigned long);
970         *cow_offset += bitmap_offset;
971 }
972
973 static void cowify_req(struct io_thread_req *req, unsigned long *bitmap,
974                        __u64 bitmap_offset, __u64 bitmap_len)
975 {
976         __u64 sector = req->offset >> 9;
977         int i;
978
979         if(req->length > (sizeof(req->sector_mask) * 8) << 9)
980                 panic("Operation too long");
981
982         if(req->op == UBD_READ) {
983                 for(i = 0; i < req->length >> 9; i++){
984                         if(ubd_test_bit(sector + i, (unsigned char *) bitmap))
985                                 ubd_set_bit(i, (unsigned char *) 
986                                             &req->sector_mask);
987                 }
988         }
989         else cowify_bitmap(req->offset, req->length, &req->sector_mask,
990                            &req->cow_offset, bitmap, bitmap_offset,
991                            req->bitmap_words, bitmap_len);
992 }
993
994 static int mmap_fd(struct request *req, struct ubd *dev, __u64 offset)
995 {
996         __u64 sector;
997         unsigned char *bitmap;
998         int bit, i;
999
1000         /* mmap must have been requested on the command line */
1001         if(!ubd_do_mmap)
1002                 return(-1);
1003
1004         /* The buffer must be page aligned */
1005         if(((unsigned long) req->buffer % UBD_MMAP_BLOCK_SIZE) != 0)
1006                 return(-1);
1007
1008         /* The request must be a page long */
1009         if((req->current_nr_sectors << 9) != PAGE_SIZE)
1010                 return(-1);
1011
1012         if(dev->cow.file == NULL)
1013                 return(dev->fd);
1014
1015         sector = offset >> 9;
1016         bitmap = (unsigned char *) dev->cow.bitmap;
1017         bit = ubd_test_bit(sector, bitmap);
1018
1019         for(i = 1; i < req->current_nr_sectors; i++){
1020                 if(ubd_test_bit(sector + i, bitmap) != bit)
1021                         return(-1);
1022         }
1023
1024         if(bit || (rq_data_dir(req) == WRITE))
1025                 offset += dev->cow.data_offset;
1026
1027         /* The data on disk must be page aligned */
1028         if((offset % UBD_MMAP_BLOCK_SIZE) != 0)
1029                 return(-1);
1030
1031         return(bit ? dev->fd : dev->cow.fd);
1032 }
1033
1034 static int prepare_mmap_request(struct ubd *dev, int fd, __u64 offset,
1035                                 struct request *req,
1036                                 struct io_thread_req *io_req)
1037 {
1038         int err;
1039
1040         if(rq_data_dir(req) == WRITE){
1041                 /* Writes are almost no-ops since the new data is already in the
1042                  * host page cache
1043                  */
1044                 dev->map_writes++;
1045                 if(dev->cow.file != NULL)
1046                         cowify_bitmap(io_req->offset, io_req->length,
1047                                       &io_req->sector_mask, &io_req->cow_offset,
1048                                       dev->cow.bitmap, dev->cow.bitmap_offset,
1049                                       io_req->bitmap_words,
1050                                       dev->cow.bitmap_len);
1051         }
1052         else {
1053                 int w;
1054
1055                 if((dev->cow.file != NULL) && (fd == dev->cow.fd))
1056                         w = 0;
1057                 else w = dev->openflags.w;
1058
1059                 if((dev->cow.file != NULL) && (fd == dev->fd))
1060                         offset += dev->cow.data_offset;
1061
1062                 err = physmem_subst_mapping(req->buffer, fd, offset, w);
1063                 if(err){
1064                         printk("physmem_subst_mapping failed, err = %d\n",
1065                                -err);
1066                         return(1);
1067                 }
1068                 dev->map_reads++;
1069         }
1070         io_req->op = UBD_MMAP;
1071         io_req->buffer = req->buffer;
1072         return(0);
1073 }
1074
1075 /* Called with ubd_io_lock held */
1076 static int prepare_request(struct request *req, struct io_thread_req *io_req)
1077 {
1078         struct gendisk *disk = req->rq_disk;
1079         struct ubd *dev = disk->private_data;
1080         __u64 offset;
1081         int len, fd;
1082
1083         if(req->rq_status == RQ_INACTIVE) return(1);
1084
1085         if((rq_data_dir(req) == WRITE) && !dev->openflags.w){
1086                 printk("Write attempted on readonly ubd device %s\n", 
1087                        disk->disk_name);
1088                 end_request(req, 0);
1089                 return(1);
1090         }
1091
1092         offset = ((__u64) req->sector) << 9;
1093         len = req->current_nr_sectors << 9;
1094
1095         io_req->fds[0] = (dev->cow.file != NULL) ? dev->cow.fd : dev->fd;
1096         io_req->fds[1] = dev->fd;
1097         io_req->map_fd = -1;
1098         io_req->cow_offset = -1;
1099         io_req->offset = offset;
1100         io_req->length = len;
1101         io_req->error = 0;
1102         io_req->sector_mask = 0;
1103
1104         fd = mmap_fd(req, dev, io_req->offset);
1105         if(fd > 0){
1106                 /* If mmapping is otherwise OK, but the first access to the
1107                  * page is a write, then it's not mapped in yet.  So we have
1108                  * to write the data to disk first, then we can map the disk
1109                  * page in and continue normally from there.
1110                  */
1111                 if((rq_data_dir(req) == WRITE) && !is_remapped(req->buffer)){
1112                         io_req->map_fd = dev->fd;
1113                         io_req->map_offset = io_req->offset +
1114                                 dev->cow.data_offset;
1115                         dev->write_maps++;
1116                 }
1117                 else return(prepare_mmap_request(dev, fd, io_req->offset, req,
1118                                                  io_req));
1119         }
1120
1121         if(rq_data_dir(req) == READ)
1122                 dev->nomap_reads++;
1123         else dev->nomap_writes++;
1124
1125         io_req->op = (rq_data_dir(req) == READ) ? UBD_READ : UBD_WRITE;
1126         io_req->offsets[0] = 0;
1127         io_req->offsets[1] = dev->cow.data_offset;
1128         io_req->buffer = req->buffer;
1129         io_req->sectorsize = 1 << 9;
1130
1131         if(dev->cow.file != NULL)
1132                 cowify_req(io_req, dev->cow.bitmap, dev->cow.bitmap_offset,
1133                            dev->cow.bitmap_len);
1134
1135         return(0);
1136 }
1137
1138 /* Called with ubd_io_lock held */
1139 static void do_ubd_request(request_queue_t *q)
1140 {
1141         struct io_thread_req io_req;
1142         struct request *req;
1143         int err, n;
1144
1145         if(thread_fd == -1){
1146                 while((req = elv_next_request(q)) != NULL){
1147                         err = prepare_request(req, &io_req);
1148                         if(!err){
1149                                 do_io(&io_req);
1150                                 __ubd_finish(req, io_req.error);
1151                         }
1152                 }
1153         }
1154         else {
1155                 if(do_ubd || (req = elv_next_request(q)) == NULL)
1156                         return;
1157                 err = prepare_request(req, &io_req);
1158                 if(!err){
1159                         do_ubd = ubd_handler;
1160                         n = os_write_file(thread_fd, (char *) &io_req,
1161                                          sizeof(io_req));
1162                         if(n != sizeof(io_req))
1163                                 printk("write to io thread failed, "
1164                                        "errno = %d\n", -n);
1165                 }
1166         }
1167 }
1168
1169 static int ubd_ioctl(struct inode * inode, struct file * file,
1170                      unsigned int cmd, unsigned long arg)
1171 {
1172         struct hd_geometry __user *loc = (struct hd_geometry __user *) arg;
1173         struct ubd *dev = inode->i_bdev->bd_disk->private_data;
1174         struct hd_driveid ubd_id = {
1175                 .cyls           = 0,
1176                 .heads          = 128,
1177                 .sectors        = 32,
1178         };
1179
1180         switch (cmd) {
1181                 struct hd_geometry g;
1182                 struct cdrom_volctrl volume;
1183         case HDIO_GETGEO:
1184                 if(!loc) return(-EINVAL);
1185                 g.heads = 128;
1186                 g.sectors = 32;
1187                 g.cylinders = dev->size / (128 * 32 * 512);
1188                 g.start = get_start_sect(inode->i_bdev);
1189                 return(copy_to_user(loc, &g, sizeof(g)) ? -EFAULT : 0);
1190
1191         case HDIO_GET_IDENTITY:
1192                 ubd_id.cyls = dev->size / (128 * 32 * 512);
1193                 if(copy_to_user((char __user *) arg, (char *) &ubd_id,
1194                                  sizeof(ubd_id)))
1195                         return(-EFAULT);
1196                 return(0);
1197                 
1198         case CDROMVOLREAD:
1199                 if(copy_from_user(&volume, (char __user *) arg, sizeof(volume)))
1200                         return(-EFAULT);
1201                 volume.channel0 = 255;
1202                 volume.channel1 = 255;
1203                 volume.channel2 = 255;
1204                 volume.channel3 = 255;
1205                 if(copy_to_user((char __user *) arg, &volume, sizeof(volume)))
1206                         return(-EFAULT);
1207                 return(0);
1208         }
1209         return(-EINVAL);
1210 }
1211
1212 static int ubd_check_remapped(int fd, unsigned long address, int is_write,
1213                               __u64 offset)
1214 {
1215         __u64 bitmap_offset;
1216         unsigned long new_bitmap[2];
1217         int i, err, n;
1218
1219         /* If it's not a write access, we can't do anything about it */
1220         if(!is_write)
1221                 return(0);
1222
1223         /* We have a write */
1224         for(i = 0; i < sizeof(ubd_dev) / sizeof(ubd_dev[0]); i++){
1225                 struct ubd *dev = &ubd_dev[i];
1226
1227                 if((dev->fd != fd) && (dev->cow.fd != fd))
1228                         continue;
1229
1230                 /* It's a write to a ubd device */
1231
1232                 if(!dev->openflags.w){
1233                         /* It's a write access on a read-only device - probably
1234                          * shouldn't happen.  If the kernel is trying to change
1235                          * something with no intention of writing it back out,
1236                          * then this message will clue us in that this needs
1237                          * fixing
1238                          */
1239                         printk("Write access to mapped page from readonly ubd "
1240                                "device %d\n", i);
1241                         return(0);
1242                 }
1243
1244                 /* It's a write to a writeable ubd device - it must be COWed
1245                  * because, otherwise, the page would have been mapped in
1246                  * writeable
1247                  */
1248
1249                 if(!dev->cow.file)
1250                         panic("Write fault on writeable non-COW ubd device %d",
1251                               i);
1252
1253                 /* It should also be an access to the backing file since the
1254                  * COW pages should be mapped in read-write
1255                  */
1256
1257                 if(fd == dev->fd)
1258                         panic("Write fault on a backing page of ubd "
1259                               "device %d\n", i);
1260
1261                 /* So, we do the write, copying the backing data to the COW
1262                  * file...
1263                  */
1264
1265                 err = os_seek_file(dev->fd, offset + dev->cow.data_offset);
1266                 if(err < 0)
1267                         panic("Couldn't seek to %lld in COW file of ubd "
1268                               "device %d, err = %d",
1269                               offset + dev->cow.data_offset, i, -err);
1270
1271                 n = os_write_file(dev->fd, (void *) address, PAGE_SIZE);
1272                 if(n != PAGE_SIZE)
1273                         panic("Couldn't copy data to COW file of ubd "
1274                               "device %d, err = %d", i, -n);
1275
1276                 /* ... updating the COW bitmap... */
1277
1278                 cowify_bitmap(offset, PAGE_SIZE, NULL, &bitmap_offset,
1279                               dev->cow.bitmap, dev->cow.bitmap_offset,
1280                               new_bitmap, dev->cow.bitmap_len);
1281
1282                 err = os_seek_file(dev->fd, bitmap_offset);
1283                 if(err < 0)
1284                         panic("Couldn't seek to %lld in COW file of ubd "
1285                               "device %d, err = %d", bitmap_offset, i, -err);
1286
1287                 n = os_write_file(dev->fd, new_bitmap, sizeof(new_bitmap));
1288                 if(n != sizeof(new_bitmap))
1289                         panic("Couldn't update bitmap  of ubd device %d, "
1290                               "err = %d", i, -n);
1291
1292                 /* Maybe we can map the COW page in, and maybe we can't.  If
1293                  * it is a pre-V3 COW file, we can't, since the alignment will
1294                  * be wrong.  If it is a V3 or later COW file which has been
1295                  * moved to a system with a larger page size, then maybe we
1296                  * can't, depending on the exact location of the page.
1297                  */
1298
1299                 offset += dev->cow.data_offset;
1300
1301                 /* Remove the remapping, putting the original anonymous page
1302                  * back.  If the COW file can be mapped in, that is done.
1303                  * Otherwise, the COW page is read in.
1304                  */
1305
1306                 if(!physmem_remove_mapping((void *) address))
1307                         panic("Address 0x%lx not remapped by ubd device %d",
1308                               address, i);
1309                 if((offset % UBD_MMAP_BLOCK_SIZE) == 0)
1310                         physmem_subst_mapping((void *) address, dev->fd,
1311                                               offset, 1);
1312                 else {
1313                         err = os_seek_file(dev->fd, offset);
1314                         if(err < 0)
1315                                 panic("Couldn't seek to %lld in COW file of "
1316                                       "ubd device %d, err = %d", offset, i,
1317                                       -err);
1318
1319                         n = os_read_file(dev->fd, (void *) address, PAGE_SIZE);
1320                         if(n != PAGE_SIZE)
1321                                 panic("Failed to read page from offset %llx of "
1322                                       "COW file of ubd device %d, err = %d",
1323                                       offset, i, -n);
1324                 }
1325
1326                 return(1);
1327         }
1328
1329         /* It's not a write on a ubd device */
1330         return(0);
1331 }
1332
1333 static struct remapper ubd_remapper = {
1334         .list   = LIST_HEAD_INIT(ubd_remapper.list),
1335         .proc   = ubd_check_remapped,
1336 };
1337
1338 static int ubd_remapper_setup(void)
1339 {
1340         if(ubd_do_mmap)
1341                 register_remapper(&ubd_remapper);
1342
1343         return(0);
1344 }
1345
1346 __initcall(ubd_remapper_setup);
1347
1348 static int same_backing_files(char *from_cmdline, char *from_cow, char *cow)
1349 {
1350         struct uml_stat buf1, buf2;
1351         int err;
1352
1353         if(from_cmdline == NULL) return(1);
1354         if(!strcmp(from_cmdline, from_cow)) return(1);
1355
1356         err = os_stat_file(from_cmdline, &buf1);
1357         if(err < 0){
1358                 printk("Couldn't stat '%s', err = %d\n", from_cmdline, -err);
1359                 return(1);
1360         }
1361         err = os_stat_file(from_cow, &buf2);
1362         if(err < 0){
1363                 printk("Couldn't stat '%s', err = %d\n", from_cow, -err);
1364                 return(1);
1365         }
1366         if((buf1.ust_dev == buf2.ust_dev) && (buf1.ust_ino == buf2.ust_ino))
1367                 return(1);
1368
1369         printk("Backing file mismatch - \"%s\" requested,\n"
1370                "\"%s\" specified in COW header of \"%s\"\n",
1371                from_cmdline, from_cow, cow);
1372         return(0);
1373 }
1374
1375 static int backing_file_mismatch(char *file, __u64 size, time_t mtime)
1376 {
1377         unsigned long modtime;
1378         long long actual;
1379         int err;
1380
1381         err = os_file_modtime(file, &modtime);
1382         if(err < 0){
1383                 printk("Failed to get modification time of backing file "
1384                        "\"%s\", err = %d\n", file, -err);
1385                 return(err);
1386         }
1387
1388         err = os_file_size(file, &actual);
1389         if(err < 0){
1390                 printk("Failed to get size of backing file \"%s\", "
1391                        "err = %d\n", file, -err);
1392                 return(err);
1393         }
1394
1395         if(actual != size){
1396                 /*__u64 can be a long on AMD64 and with %lu GCC complains; so
1397                  * the typecast.*/
1398                 printk("Size mismatch (%llu vs %llu) of COW header vs backing "
1399                        "file\n", (unsigned long long) size, actual);
1400                 return(-EINVAL);
1401         }
1402         if(modtime != mtime){
1403                 printk("mtime mismatch (%ld vs %ld) of COW header vs backing "
1404                        "file\n", mtime, modtime);
1405                 return(-EINVAL);
1406         }
1407         return(0);
1408 }
1409
1410 int read_cow_bitmap(int fd, void *buf, int offset, int len)
1411 {
1412         int err;
1413
1414         err = os_seek_file(fd, offset);
1415         if(err < 0)
1416                 return(err);
1417
1418         err = os_read_file(fd, buf, len);
1419         if(err < 0)
1420                 return(err);
1421
1422         return(0);
1423 }
1424
1425 int open_ubd_file(char *file, struct openflags *openflags,
1426                   char **backing_file_out, int *bitmap_offset_out,
1427                   unsigned long *bitmap_len_out, int *data_offset_out,
1428                   int *create_cow_out)
1429 {
1430         time_t mtime;
1431         unsigned long long size;
1432         __u32 version, align;
1433         char *backing_file;
1434         int fd, err, sectorsize, same, mode = 0644;
1435
1436         fd = os_open_file(file, *openflags, mode);
1437         if(fd < 0){
1438                 if((fd == -ENOENT) && (create_cow_out != NULL))
1439                         *create_cow_out = 1;
1440                 if(!openflags->w ||
1441                    ((fd != -EROFS) && (fd != -EACCES))) return(fd);
1442                 openflags->w = 0;
1443                 fd = os_open_file(file, *openflags, mode);
1444                 if(fd < 0)
1445                         return(fd);
1446         }
1447
1448         err = os_lock_file(fd, openflags->w);
1449         if(err < 0){
1450                 printk("Failed to lock '%s', err = %d\n", file, -err);
1451                 goto out_close;
1452         }
1453
1454         if(backing_file_out == NULL) return(fd);
1455
1456         err = read_cow_header(file_reader, &fd, &version, &backing_file, &mtime,
1457                               &size, &sectorsize, &align, bitmap_offset_out);
1458         if(err && (*backing_file_out != NULL)){
1459                 printk("Failed to read COW header from COW file \"%s\", "
1460                        "errno = %d\n", file, -err);
1461                 goto out_close;
1462         }
1463         if(err) return(fd);
1464
1465         if(backing_file_out == NULL) return(fd);
1466
1467         same = same_backing_files(*backing_file_out, backing_file, file);
1468
1469         if(!same && !backing_file_mismatch(*backing_file_out, size, mtime)){
1470                 printk("Switching backing file to '%s'\n", *backing_file_out);
1471                 err = write_cow_header(file, fd, *backing_file_out,
1472                                        sectorsize, align, &size);
1473                 if(err){
1474                         printk("Switch failed, errno = %d\n", -err);
1475                         return(err);
1476                 }
1477         }
1478         else {
1479                 *backing_file_out = backing_file;
1480                 err = backing_file_mismatch(*backing_file_out, size, mtime);
1481                 if(err) goto out_close;
1482         }
1483
1484         cow_sizes(version, size, sectorsize, align, *bitmap_offset_out,
1485                   bitmap_len_out, data_offset_out);
1486
1487         return(fd);
1488  out_close:
1489         os_close_file(fd);
1490         return(err);
1491 }
1492
1493 int create_cow_file(char *cow_file, char *backing_file, struct openflags flags,
1494                     int sectorsize, int alignment, int *bitmap_offset_out,
1495                     unsigned long *bitmap_len_out, int *data_offset_out)
1496 {
1497         int err, fd;
1498
1499         flags.c = 1;
1500         fd = open_ubd_file(cow_file, &flags, NULL, NULL, NULL, NULL, NULL);
1501         if(fd < 0){
1502                 err = fd;
1503                 printk("Open of COW file '%s' failed, errno = %d\n", cow_file,
1504                        -err);
1505                 goto out;
1506         }
1507
1508         err = init_cow_file(fd, cow_file, backing_file, sectorsize, alignment,
1509                             bitmap_offset_out, bitmap_len_out,
1510                             data_offset_out);
1511         if(!err)
1512                 return(fd);
1513         os_close_file(fd);
1514  out:
1515         return(err);
1516 }
1517
1518 static int update_bitmap(struct io_thread_req *req)
1519 {
1520         int n;
1521
1522         if(req->cow_offset == -1)
1523                 return(0);
1524
1525         n = os_seek_file(req->fds[1], req->cow_offset);
1526         if(n < 0){
1527                 printk("do_io - bitmap lseek failed : err = %d\n", -n);
1528                 return(1);
1529         }
1530
1531         n = os_write_file(req->fds[1], &req->bitmap_words,
1532                           sizeof(req->bitmap_words));
1533         if(n != sizeof(req->bitmap_words)){
1534                 printk("do_io - bitmap update failed, err = %d fd = %d\n", -n,
1535                        req->fds[1]);
1536                 return(1);
1537         }
1538
1539         return(0);
1540 }
1541
1542 void do_io(struct io_thread_req *req)
1543 {
1544         char *buf;
1545         unsigned long len;
1546         int n, nsectors, start, end, bit;
1547         int err;
1548         __u64 off;
1549
1550         if(req->op == UBD_MMAP){
1551                 /* Touch the page to force the host to do any necessary IO to
1552                  * get it into memory
1553                  */
1554                 n = *((volatile int *) req->buffer);
1555                 req->error = update_bitmap(req);
1556                 return;
1557         }
1558
1559         nsectors = req->length / req->sectorsize;
1560         start = 0;
1561         do {
1562                 bit = ubd_test_bit(start, (unsigned char *) &req->sector_mask);
1563                 end = start;
1564                 while((end < nsectors) &&
1565                       (ubd_test_bit(end, (unsigned char *)
1566                                     &req->sector_mask) == bit))
1567                         end++;
1568
1569                 off = req->offset + req->offsets[bit] +
1570                         start * req->sectorsize;
1571                 len = (end - start) * req->sectorsize;
1572                 buf = &req->buffer[start * req->sectorsize];
1573
1574                 err = os_seek_file(req->fds[bit], off);
1575                 if(err < 0){
1576                         printk("do_io - lseek failed : err = %d\n", -err);
1577                         req->error = 1;
1578                         return;
1579                 }
1580                 if(req->op == UBD_READ){
1581                         n = 0;
1582                         do {
1583                                 buf = &buf[n];
1584                                 len -= n;
1585                                 n = os_read_file(req->fds[bit], buf, len);
1586                                 if (n < 0) {
1587                                         printk("do_io - read failed, err = %d "
1588                                                "fd = %d\n", -n, req->fds[bit]);
1589                                         req->error = 1;
1590                                         return;
1591                                 }
1592                         } while((n < len) && (n != 0));
1593                         if (n < len) memset(&buf[n], 0, len - n);
1594                 }
1595                 else {
1596                         n = os_write_file(req->fds[bit], buf, len);
1597                         if(n != len){
1598                                 printk("do_io - write failed err = %d "
1599                                        "fd = %d\n", -n, req->fds[bit]);
1600                                 req->error = 1;
1601                                 return;
1602                         }
1603                 }
1604
1605                 start = end;
1606         } while(start < nsectors);
1607
1608         req->error = update_bitmap(req);
1609 }
1610
1611 /* Changed in start_io_thread, which is serialized by being called only
1612  * from ubd_init, which is an initcall.
1613  */
1614 int kernel_fd = -1;
1615
1616 /* Only changed by the io thread */
1617 int io_count = 0;
1618
1619 int io_thread(void *arg)
1620 {
1621         struct io_thread_req req;
1622         int n;
1623
1624         ignore_sigwinch_sig();
1625         while(1){
1626                 n = os_read_file(kernel_fd, &req, sizeof(req));
1627                 if(n != sizeof(req)){
1628                         if(n < 0)
1629                                 printk("io_thread - read failed, fd = %d, "
1630                                        "err = %d\n", kernel_fd, -n);
1631                         else {
1632                                 printk("io_thread - short read, fd = %d, "
1633                                        "length = %d\n", kernel_fd, n);
1634                         }
1635                         continue;
1636                 }
1637                 io_count++;
1638                 do_io(&req);
1639                 n = os_write_file(kernel_fd, &req, sizeof(req));
1640                 if(n != sizeof(req))
1641                         printk("io_thread - write failed, fd = %d, err = %d\n",
1642                                kernel_fd, -n);
1643         }
1644 }
1645
1646 /*
1647  * Overrides for Emacs so that we follow Linus's tabbing style.
1648  * Emacs will notice this stuff at the end of the file and automatically
1649  * adjust the settings for this buffer only.  This must remain at the end
1650  * of the file.
1651  * ---------------------------------------------------------------------------
1652  * Local variables:
1653  * c-file-style: "linux"
1654  * End:
1655  */