vserver 1.9.3
[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
57 static spinlock_t ubd_io_lock = SPIN_LOCK_UNLOCKED;
58 static spinlock_t ubd_lock = SPIN_LOCK_UNLOCKED;
59
60 static void (*do_ubd)(void);
61
62 static int ubd_open(struct inode * inode, struct file * filp);
63 static int ubd_release(struct inode * inode, struct file * file);
64 static int ubd_ioctl(struct inode * inode, struct file * file,
65                      unsigned int cmd, unsigned long arg);
66
67 #define MAX_DEV (8)
68
69 /* Changed in early boot */
70 static int ubd_do_mmap = 0;
71 #define UBD_MMAP_BLOCK_SIZE PAGE_SIZE
72
73 static struct block_device_operations ubd_blops = {
74         .owner          = THIS_MODULE,
75         .open           = ubd_open,
76         .release        = ubd_release,
77         .ioctl          = ubd_ioctl,
78 };
79
80 /* Protected by the queue_lock */
81 static request_queue_t *ubd_queue;
82
83 /* Protected by ubd_lock */
84 static int fake_major = MAJOR_NR;
85
86 static struct gendisk *ubd_gendisk[MAX_DEV];
87 static struct gendisk *fake_gendisk[MAX_DEV];
88  
89 #ifdef CONFIG_BLK_DEV_UBD_SYNC
90 #define OPEN_FLAGS ((struct openflags) { .r = 1, .w = 1, .s = 1, .c = 0, \
91                                          .cl = 1 })
92 #else
93 #define OPEN_FLAGS ((struct openflags) { .r = 1, .w = 1, .s = 0, .c = 0, \
94                                          .cl = 1 })
95 #endif
96
97 /* Not protected - changed only in ubd_setup_common and then only to
98  * to enable O_SYNC.
99  */
100 static struct openflags global_openflags = OPEN_FLAGS;
101
102 struct cow {
103         char *file;
104         int fd;
105         unsigned long *bitmap;
106         unsigned long bitmap_len;
107         int bitmap_offset;
108         int data_offset;
109 };
110
111 struct ubd {
112         char *file;
113         int count;
114         int fd;
115         __u64 size;
116         struct openflags boot_openflags;
117         struct openflags openflags;
118         int no_cow;
119         struct cow cow;
120
121         int map_writes;
122         int map_reads;
123         int nomap_writes;
124         int nomap_reads;
125         int write_maps;
126 };
127
128 #define DEFAULT_COW { \
129         .file =                 NULL, \
130         .fd =                   -1, \
131         .bitmap =               NULL, \
132         .bitmap_offset =        0, \
133         .data_offset =          0, \
134 }
135
136 #define DEFAULT_UBD { \
137         .file =                 NULL, \
138         .count =                0, \
139         .fd =                   -1, \
140         .size =                 -1, \
141         .boot_openflags =       OPEN_FLAGS, \
142         .openflags =            OPEN_FLAGS, \
143         .no_cow =               0, \
144         .cow =                  DEFAULT_COW, \
145         .map_writes             = 0, \
146         .map_reads              = 0, \
147         .nomap_writes           = 0, \
148         .nomap_reads            = 0, \
149         .write_maps             = 0, \
150 }
151
152 struct ubd ubd_dev[MAX_DEV] = { [ 0 ... MAX_DEV - 1 ] = DEFAULT_UBD };
153
154 static int ubd0_init(void)
155 {
156         struct ubd *dev = &ubd_dev[0];
157
158         if(dev->file == NULL)
159                 dev->file = "root_fs";
160         return(0);
161 }
162
163 __initcall(ubd0_init);
164
165 /* Only changed by fake_ide_setup which is a setup */
166 static int fake_ide = 0;
167 static struct proc_dir_entry *proc_ide_root = NULL;
168 static struct proc_dir_entry *proc_ide = NULL;
169
170 static void make_proc_ide(void)
171 {
172         proc_ide_root = proc_mkdir("ide", 0);
173         proc_ide = proc_mkdir("ide0", proc_ide_root);
174 }
175
176 static int proc_ide_read_media(char *page, char **start, off_t off, int count,
177                                int *eof, void *data)
178 {
179         int len;
180
181         strcpy(page, "disk\n");
182         len = strlen("disk\n");
183         len -= off;
184         if (len < count){
185                 *eof = 1;
186                 if (len <= 0) return 0;
187         }
188         else len = count;
189         *start = page + off;
190         return len;
191 }
192
193 static void make_ide_entries(char *dev_name)
194 {
195         struct proc_dir_entry *dir, *ent;
196         char name[64];
197
198         if(proc_ide_root == NULL) make_proc_ide();
199
200         dir = proc_mkdir(dev_name, proc_ide);
201         if(!dir) return;
202
203         ent = create_proc_entry("media", S_IFREG|S_IRUGO, dir);
204         if(!ent) return;
205         ent->nlink = 1;
206         ent->data = NULL;
207         ent->read_proc = proc_ide_read_media;
208         ent->write_proc = NULL;
209         sprintf(name,"ide0/%s", dev_name);
210         proc_symlink(dev_name, proc_ide_root, name);
211 }
212
213 static int fake_ide_setup(char *str)
214 {
215         fake_ide = 1;
216         return(1);
217 }
218
219 __setup("fake_ide", fake_ide_setup);
220
221 __uml_help(fake_ide_setup,
222 "fake_ide\n"
223 "    Create ide0 entries that map onto ubd devices.\n\n"
224 );
225
226 static int parse_unit(char **ptr)
227 {
228         char *str = *ptr, *end;
229         int n = -1;
230
231         if(isdigit(*str)) {
232                 n = simple_strtoul(str, &end, 0);
233                 if(end == str)
234                         return(-1);
235                 *ptr = end;
236         }
237         else if (('a' <= *str) && (*str <= 'h')) {
238                 n = *str - 'a';
239                 str++;
240                 *ptr = str;
241         }
242         return(n);
243 }
244
245 static int ubd_setup_common(char *str, int *index_out)
246 {
247         struct ubd *dev;
248         struct openflags flags = global_openflags;
249         char *backing_file;
250         int n, err;
251
252         if(index_out) *index_out = -1;
253         n = *str;
254         if(n == '='){
255                 char *end;
256                 int major;
257
258                 str++;
259                 if(!strcmp(str, "mmap")){
260                         CHOOSE_MODE(printk("mmap not supported by the ubd "
261                                            "driver in tt mode\n"),
262                                     ubd_do_mmap = 1);
263                         return(0);
264                 }
265
266                 if(!strcmp(str, "sync")){
267                         global_openflags.s = 1;
268                         return(0);
269                 }
270                 major = simple_strtoul(str, &end, 0);
271                 if((*end != '\0') || (end == str)){
272                         printk(KERN_ERR 
273                                "ubd_setup : didn't parse major number\n");
274                         return(1);
275                 }
276
277                 err = 1;
278                 spin_lock(&ubd_lock);
279                 if(fake_major != MAJOR_NR){
280                         printk(KERN_ERR "Can't assign a fake major twice\n");
281                         goto out1;
282                 }
283  
284                 fake_major = major;
285
286                 printk(KERN_INFO "Setting extra ubd major number to %d\n",
287                        major);
288                 err = 0;
289         out1:
290                 spin_unlock(&ubd_lock);
291                 return(err);
292         }
293
294         n = parse_unit(&str);
295         if(n < 0){
296                 printk(KERN_ERR "ubd_setup : couldn't parse unit number "
297                        "'%s'\n", str);
298                 return(1);
299         }
300         if(n >= MAX_DEV){
301                 printk(KERN_ERR "ubd_setup : index %d out of range "
302                        "(%d devices, from 0 to %d)\n", n, MAX_DEV, MAX_DEV - 1);
303                 return(1);
304         }
305
306         err = 1;
307         spin_lock(&ubd_lock);
308
309         dev = &ubd_dev[n];
310         if(dev->file != NULL){
311                 printk(KERN_ERR "ubd_setup : device already configured\n");
312                 goto out2;
313         }
314
315         if(index_out) *index_out = n;
316
317         if (*str == 'r'){
318                 flags.w = 0;
319                 str++;
320         }
321         if (*str == 's'){
322                 flags.s = 1;
323                 str++;
324         }
325         if (*str == 'd'){
326                 dev->no_cow = 1;
327                 str++;
328         }
329
330         if(*str++ != '='){
331                 printk(KERN_ERR "ubd_setup : Expected '='\n");
332                 goto out2;
333         }
334
335         err = 0;
336         backing_file = strchr(str, ',');
337         if(backing_file){
338                 if(dev->no_cow)
339                         printk(KERN_ERR "Can't specify both 'd' and a "
340                                "cow file\n");
341                 else {
342                         *backing_file = '\0';
343                         backing_file++;
344                 }
345         }
346         dev->file = str;
347         dev->cow.file = backing_file;
348         dev->boot_openflags = flags;
349  out2:
350         spin_unlock(&ubd_lock);
351         return(err);
352 }
353
354 static int ubd_setup(char *str)
355 {
356         ubd_setup_common(str, NULL);
357         return(1);
358 }
359
360 __setup("ubd", ubd_setup);
361 __uml_help(ubd_setup,
362 "ubd<n>=<filename>\n"
363 "    This is used to associate a device with a file in the underlying\n"
364 "    filesystem. Usually, there is a filesystem in the file, but \n"
365 "    that's not required. Swap devices containing swap files can be\n"
366 "    specified like this. Also, a file which doesn't contain a\n"
367 "    filesystem can have its contents read in the virtual \n"
368 "    machine by running dd on the device. n must be in the range\n"
369 "    0 to 7. Appending an 'r' to the number will cause that device\n"
370 "    to be mounted read-only. For example ubd1r=./ext_fs. Appending\n"
371 "    an 's' (has to be _after_ 'r', if there is one) will cause data\n"
372 "    to be written to disk on the host immediately.\n\n"
373 );
374
375 static int fakehd_set = 0;
376 static int fakehd(char *str)
377 {
378         printk(KERN_INFO "fakehd : Changing ubd name to \"hd\".\n");
379         fakehd_set = 1;
380         return 1;
381 }
382
383 __setup("fakehd", fakehd);
384 __uml_help(fakehd,
385 "fakehd\n"
386 "    Change the ubd device name to \"hd\".\n\n"
387 );
388
389 static void do_ubd_request(request_queue_t * q);
390
391 /* Only changed by ubd_init, which is an initcall. */
392 int thread_fd = -1;
393
394 /* Changed by ubd_handler, which is serialized because interrupts only
395  * happen on CPU 0.
396  */
397 int intr_count = 0;
398
399 /* call ubd_finish if you need to serialize */
400 static void __ubd_finish(struct request *req, int error)
401 {
402         int nsect;
403
404         if(error){
405                 end_request(req, 0);
406                 return;
407         }
408         nsect = req->current_nr_sectors;
409         req->sector += nsect;
410         req->buffer += nsect << 9;
411         req->errors = 0;
412         req->nr_sectors -= nsect;
413         req->current_nr_sectors = 0;
414         end_request(req, 1);
415 }
416
417 static inline void ubd_finish(struct request *req, int error)
418 {
419         spin_lock(&ubd_io_lock);
420         __ubd_finish(req, error);
421         spin_unlock(&ubd_io_lock);
422 }
423
424 /* Called without ubd_io_lock held */
425 static void ubd_handler(void)
426 {
427         struct io_thread_req req;
428         struct request *rq = elv_next_request(ubd_queue);
429         int n, err;
430
431         do_ubd = NULL;
432         intr_count++;
433         n = read_ubd_fs(thread_fd, &req, sizeof(req));
434         if(n != sizeof(req)){
435                 printk(KERN_ERR "Pid %d - spurious interrupt in ubd_handler, "
436                        "err = %d\n", os_getpid(), -n);
437                 spin_lock(&ubd_io_lock);
438                 end_request(rq, 0);
439                 spin_unlock(&ubd_io_lock);
440                 return;
441         }
442         
443         if((req.op != UBD_MMAP) &&
444            ((req.offset != ((__u64) (rq->sector)) << 9) ||
445             (req.length != (rq->current_nr_sectors) << 9)))
446                 panic("I/O op mismatch");
447         
448         if(req.map_fd != -1){
449                 err = physmem_subst_mapping(req.buffer, req.map_fd,
450                                             req.map_offset, 1);
451                 if(err)
452                         printk("ubd_handler - physmem_subst_mapping failed, "
453                                "err = %d\n", -err);
454         }
455
456         ubd_finish(rq, req.error);
457         reactivate_fd(thread_fd, UBD_IRQ);      
458         do_ubd_request(ubd_queue);
459 }
460
461 static irqreturn_t ubd_intr(int irq, void *dev, struct pt_regs *unused)
462 {
463         ubd_handler();
464         return(IRQ_HANDLED);
465 }
466
467 /* Only changed by ubd_init, which is an initcall. */
468 static int io_pid = -1;
469
470 void kill_io_thread(void)
471 {
472         if(io_pid != -1) 
473                 os_kill_process(io_pid, 1);
474 }
475
476 __uml_exitcall(kill_io_thread);
477
478 static int ubd_file_size(struct ubd *dev, __u64 *size_out)
479 {
480         char *file;
481
482         file = dev->cow.file ? dev->cow.file : dev->file;
483         return(os_file_size(file, size_out));
484 }
485
486 static void ubd_close(struct ubd *dev)
487 {
488         if(ubd_do_mmap)
489                 physmem_forget_descriptor(dev->fd);
490         os_close_file(dev->fd);
491         if(dev->cow.file == NULL)
492                 return;
493
494         if(ubd_do_mmap)
495                 physmem_forget_descriptor(dev->cow.fd);
496         os_close_file(dev->cow.fd);
497         vfree(dev->cow.bitmap);
498         dev->cow.bitmap = NULL;
499 }
500
501 static int ubd_open_dev(struct ubd *dev)
502 {
503         struct openflags flags;
504         char **back_ptr;
505         int err, create_cow, *create_ptr;
506
507         dev->openflags = dev->boot_openflags;
508         create_cow = 0;
509         create_ptr = (dev->cow.file != NULL) ? &create_cow : NULL;
510         back_ptr = dev->no_cow ? NULL : &dev->cow.file;
511         dev->fd = open_ubd_file(dev->file, &dev->openflags, back_ptr,
512                                 &dev->cow.bitmap_offset, &dev->cow.bitmap_len, 
513                                 &dev->cow.data_offset, create_ptr);
514
515         if((dev->fd == -ENOENT) && create_cow){
516                 dev->fd = create_cow_file(dev->file, dev->cow.file, 
517                                           dev->openflags, 1 << 9, PAGE_SIZE,
518                                           &dev->cow.bitmap_offset, 
519                                           &dev->cow.bitmap_len,
520                                           &dev->cow.data_offset);
521                 if(dev->fd >= 0){
522                         printk(KERN_INFO "Creating \"%s\" as COW file for "
523                                "\"%s\"\n", dev->file, dev->cow.file);
524                 }
525         }
526
527         if(dev->fd < 0) return(dev->fd);
528
529         if(dev->cow.file != NULL){
530                 err = -ENOMEM;
531                 dev->cow.bitmap = (void *) vmalloc(dev->cow.bitmap_len);
532                 if(dev->cow.bitmap == NULL){
533                         printk(KERN_ERR "Failed to vmalloc COW bitmap\n");
534                         goto error;
535                 }
536                 flush_tlb_kernel_vm();
537
538                 err = read_cow_bitmap(dev->fd, dev->cow.bitmap, 
539                                       dev->cow.bitmap_offset, 
540                                       dev->cow.bitmap_len);
541                 if(err < 0)
542                         goto error;
543
544                 flags = dev->openflags;
545                 flags.w = 0;
546                 err = open_ubd_file(dev->cow.file, &flags, NULL, NULL, NULL, 
547                                     NULL, NULL);
548                 if(err < 0) goto error;
549                 dev->cow.fd = err;
550         }
551         return(0);
552  error:
553         os_close_file(dev->fd);
554         return(err);
555 }
556
557 static int ubd_new_disk(int major, u64 size, int unit,
558                         struct gendisk **disk_out)
559                         
560 {
561         struct gendisk *disk;
562         char from[sizeof("ubd/nnnnn\0")], to[sizeof("discnnnnn/disc\0")];
563         int err;
564
565         disk = alloc_disk(1 << UBD_SHIFT);
566         if(disk == NULL)
567                 return(-ENOMEM);
568
569         disk->major = major;
570         disk->first_minor = unit << UBD_SHIFT;
571         disk->fops = &ubd_blops;
572         set_capacity(disk, size / 512);
573         if(major == MAJOR_NR){
574                 sprintf(disk->disk_name, "ubd%c", 'a' + unit);
575                 sprintf(disk->devfs_name, "ubd/disc%d", unit);
576                 sprintf(from, "ubd/%d", unit);
577                 sprintf(to, "disc%d/disc", unit);
578                 err = devfs_mk_symlink(from, to);
579                 if(err)
580                         printk("ubd_new_disk failed to make link from %s to "
581                                "%s, error = %d\n", from, to, err);
582         }
583         else {
584                 sprintf(disk->disk_name, "ubd_fake%d", unit);
585                 sprintf(disk->devfs_name, "ubd_fake/disc%d", unit);
586         }
587
588         disk->private_data = &ubd_dev[unit];
589         disk->queue = ubd_queue;
590         add_disk(disk);
591
592         *disk_out = disk;
593         return 0;
594 }
595
596 static int ubd_add(int n)
597 {
598         struct ubd *dev = &ubd_dev[n];
599         int err;
600
601         if(dev->file == NULL)
602                 return(-ENODEV);
603
604         if (ubd_open_dev(dev))
605                 return(-ENODEV);
606
607         err = ubd_file_size(dev, &dev->size);
608         if(err < 0)
609                 return(err);
610
611         err = ubd_new_disk(MAJOR_NR, dev->size, n, &ubd_gendisk[n]);
612         if(err) 
613                 return(err);
614  
615         if(fake_major != MAJOR_NR)
616                 ubd_new_disk(fake_major, dev->size, n, 
617                              &fake_gendisk[n]);
618
619         /* perhaps this should also be under the "if (fake_major)" above */
620         /* using the fake_disk->disk_name and also the fakehd_set name */
621         if (fake_ide)
622                 make_ide_entries(ubd_gendisk[n]->disk_name);
623
624         ubd_close(dev);
625         return 0;
626 }
627
628 static int ubd_config(char *str)
629 {
630         int n, err;
631
632         str = uml_strdup(str);
633         if(str == NULL){
634                 printk(KERN_ERR "ubd_config failed to strdup string\n");
635                 return(1);
636         }
637         err = ubd_setup_common(str, &n);
638         if(err){
639                 kfree(str);
640                 return(-1);
641         }
642         if(n == -1) return(0);
643
644         spin_lock(&ubd_lock);
645         err = ubd_add(n);
646         if(err)
647                 ubd_dev[n].file = NULL;
648         spin_unlock(&ubd_lock);
649
650         return(err);
651 }
652
653 static int ubd_get_config(char *name, char *str, int size, char **error_out)
654 {
655         struct ubd *dev;
656         char *end;
657         int n, len = 0;
658
659         n = simple_strtoul(name, &end, 0);
660         if((*end != '\0') || (end == name)){
661                 *error_out = "ubd_get_config : didn't parse device number";
662                 return(-1);
663         }
664
665         if((n >= MAX_DEV) || (n < 0)){
666                 *error_out = "ubd_get_config : device number out of range";
667                 return(-1);
668         }
669
670         dev = &ubd_dev[n];
671         spin_lock(&ubd_lock);
672
673         if(dev->file == NULL){
674                 CONFIG_CHUNK(str, size, len, "", 1);
675                 goto out;
676         }
677
678         CONFIG_CHUNK(str, size, len, dev->file, 0);
679
680         if(dev->cow.file != NULL){
681                 CONFIG_CHUNK(str, size, len, ",", 0);
682                 CONFIG_CHUNK(str, size, len, dev->cow.file, 1);
683         }
684         else CONFIG_CHUNK(str, size, len, "", 1);
685
686  out:
687         spin_unlock(&ubd_lock);
688         return(len);
689 }
690
691 static int ubd_remove(char *str)
692 {
693         struct ubd *dev;
694         int n, err = -ENODEV;
695
696         n = parse_unit(&str);
697
698         if((n < 0) || (n >= MAX_DEV))
699                 return(err);
700
701         dev = &ubd_dev[n];
702         if(dev->count > 0)
703                 return(-EBUSY); /* you cannot remove a open disk */
704
705         err = 0;
706         spin_lock(&ubd_lock);
707
708         if(ubd_gendisk[n] == NULL)
709                 goto out;
710
711         del_gendisk(ubd_gendisk[n]);
712         put_disk(ubd_gendisk[n]);
713         ubd_gendisk[n] = NULL;
714
715         if(fake_gendisk[n] != NULL){
716                 del_gendisk(fake_gendisk[n]);
717                 put_disk(fake_gendisk[n]);
718                 fake_gendisk[n] = NULL;
719         }
720
721         *dev = ((struct ubd) DEFAULT_UBD);
722         err = 0;
723  out:
724         spin_unlock(&ubd_lock);
725         return(err);
726 }
727
728 static struct mc_device ubd_mc = {
729         .name           = "ubd",
730         .config         = ubd_config,
731         .get_config     = ubd_get_config,
732         .remove         = ubd_remove,
733 };
734
735 static int ubd_mc_init(void)
736 {
737         mconsole_register_dev(&ubd_mc);
738         return 0;
739 }
740
741 __initcall(ubd_mc_init);
742
743 int ubd_init(void)
744 {
745         int i;
746
747         devfs_mk_dir("ubd");
748         if (register_blkdev(MAJOR_NR, "ubd"))
749                 return -1;
750
751         ubd_queue = blk_init_queue(do_ubd_request, &ubd_io_lock);
752         if (!ubd_queue) {
753                 unregister_blkdev(MAJOR_NR, "ubd");
754                 return -1;
755         }
756                 
757         if (fake_major != MAJOR_NR) {
758                 char name[sizeof("ubd_nnn\0")];
759
760                 snprintf(name, sizeof(name), "ubd_%d", fake_major);
761                 devfs_mk_dir(name);
762                 if (register_blkdev(fake_major, "ubd"))
763                         return -1;
764         }
765         for (i = 0; i < MAX_DEV; i++) 
766                 ubd_add(i);
767         return 0;
768 }
769
770 late_initcall(ubd_init);
771
772 int ubd_driver_init(void){
773         unsigned long stack;
774         int err;
775
776         /* Set by CONFIG_BLK_DEV_UBD_SYNC or ubd=sync.*/
777         if(global_openflags.s){
778                 printk(KERN_INFO "ubd: Synchronous mode\n");
779                 /* Letting ubd=sync be like using ubd#s= instead of ubd#= is
780                  * enough. So use anyway the io thread. */
781         }
782         stack = alloc_stack(0, 0);
783         io_pid = start_io_thread(stack + PAGE_SIZE - sizeof(void *), 
784                                  &thread_fd);
785         if(io_pid < 0){
786                 printk(KERN_ERR 
787                        "ubd : Failed to start I/O thread (errno = %d) - "
788                        "falling back to synchronous I/O\n", -io_pid);
789                 io_pid = -1;
790                 return(0);
791         }
792         err = um_request_irq(UBD_IRQ, thread_fd, IRQ_READ, ubd_intr, 
793                              SA_INTERRUPT, "ubd", ubd_dev);
794         if(err != 0)
795                 printk(KERN_ERR "um_request_irq failed - errno = %d\n", -err);
796         return(err);
797 }
798
799 device_initcall(ubd_driver_init);
800
801 static int ubd_open(struct inode *inode, struct file *filp)
802 {
803         struct gendisk *disk = inode->i_bdev->bd_disk;
804         struct ubd *dev = disk->private_data;
805         int err = 0;
806
807         if(dev->count == 0){
808                 err = ubd_open_dev(dev);
809                 if(err){
810                         printk(KERN_ERR "%s: Can't open \"%s\": errno = %d\n",
811                                disk->disk_name, dev->file, -err);
812                         goto out;
813                 }
814         }
815         dev->count++;
816         if((filp->f_mode & FMODE_WRITE) && !dev->openflags.w){
817                 if(--dev->count == 0) ubd_close(dev);
818                 err = -EROFS;
819         }
820  out:
821         return(err);
822 }
823
824 static int ubd_release(struct inode * inode, struct file * file)
825 {
826         struct gendisk *disk = inode->i_bdev->bd_disk;
827         struct ubd *dev = disk->private_data;
828
829         if(--dev->count == 0)
830                 ubd_close(dev);
831         return(0);
832 }
833
834 static void cowify_bitmap(__u64 io_offset, int length, unsigned long *cow_mask,
835                           __u64 *cow_offset, unsigned long *bitmap,
836                           __u64 bitmap_offset, unsigned long *bitmap_words,
837                           __u64 bitmap_len)
838 {
839         __u64 sector = io_offset >> 9;
840         int i, update_bitmap = 0;
841
842         for(i = 0; i < length >> 9; i++){
843                 if(cow_mask != NULL)
844                         ubd_set_bit(i, (unsigned char *) cow_mask);
845                 if(ubd_test_bit(sector + i, (unsigned char *) bitmap))
846                         continue;
847
848                 update_bitmap = 1;
849                 ubd_set_bit(sector + i, (unsigned char *) bitmap);
850         }
851
852         if(!update_bitmap)
853                 return;
854
855         *cow_offset = sector / (sizeof(unsigned long) * 8);
856
857         /* This takes care of the case where we're exactly at the end of the
858          * device, and *cow_offset + 1 is off the end.  So, just back it up
859          * by one word.  Thanks to Lynn Kerby for the fix and James McMechan
860          * for the original diagnosis.
861          */
862         if(*cow_offset == ((bitmap_len + sizeof(unsigned long) - 1) /
863                            sizeof(unsigned long) - 1))
864                 (*cow_offset)--;
865
866         bitmap_words[0] = bitmap[*cow_offset];
867         bitmap_words[1] = bitmap[*cow_offset + 1];
868
869         *cow_offset *= sizeof(unsigned long);
870         *cow_offset += bitmap_offset;
871 }
872
873 static void cowify_req(struct io_thread_req *req, unsigned long *bitmap,
874                        __u64 bitmap_offset, __u64 bitmap_len)
875 {
876         __u64 sector = req->offset >> 9;
877         int i;
878
879         if(req->length > (sizeof(req->sector_mask) * 8) << 9)
880                 panic("Operation too long");
881
882         if(req->op == UBD_READ) {
883                 for(i = 0; i < req->length >> 9; i++){
884                         if(ubd_test_bit(sector + i, (unsigned char *) bitmap))
885                                 ubd_set_bit(i, (unsigned char *) 
886                                             &req->sector_mask);
887                 }
888         }
889         else cowify_bitmap(req->offset, req->length, &req->sector_mask,
890                            &req->cow_offset, bitmap, bitmap_offset,
891                            req->bitmap_words, bitmap_len);
892 }
893
894 static int mmap_fd(struct request *req, struct ubd *dev, __u64 offset)
895 {
896         __u64 sector;
897         unsigned char *bitmap;
898         int bit, i;
899
900         /* mmap must have been requested on the command line */
901         if(!ubd_do_mmap)
902                 return(-1);
903
904         /* The buffer must be page aligned */
905         if(((unsigned long) req->buffer % UBD_MMAP_BLOCK_SIZE) != 0)
906                 return(-1);
907
908         /* The request must be a page long */
909         if((req->current_nr_sectors << 9) != PAGE_SIZE)
910                 return(-1);
911
912         if(dev->cow.file == NULL)
913                 return(dev->fd);
914
915         sector = offset >> 9;
916         bitmap = (unsigned char *) dev->cow.bitmap;
917         bit = ubd_test_bit(sector, bitmap);
918
919         for(i = 1; i < req->current_nr_sectors; i++){
920                 if(ubd_test_bit(sector + i, bitmap) != bit)
921                         return(-1);
922         }
923
924         if(bit || (rq_data_dir(req) == WRITE))
925                 offset += dev->cow.data_offset;
926
927         /* The data on disk must be page aligned */
928         if((offset % UBD_MMAP_BLOCK_SIZE) != 0)
929                 return(-1);
930
931         return(bit ? dev->fd : dev->cow.fd);
932 }
933
934 static int prepare_mmap_request(struct ubd *dev, int fd, __u64 offset,
935                                 struct request *req,
936                                 struct io_thread_req *io_req)
937 {
938         int err;
939
940         if(rq_data_dir(req) == WRITE){
941                 /* Writes are almost no-ops since the new data is already in the
942                  * host page cache
943                  */
944                 dev->map_writes++;
945                 if(dev->cow.file != NULL)
946                         cowify_bitmap(io_req->offset, io_req->length,
947                                       &io_req->sector_mask, &io_req->cow_offset,
948                                       dev->cow.bitmap, dev->cow.bitmap_offset,
949                                       io_req->bitmap_words,
950                                       dev->cow.bitmap_len);
951         }
952         else {
953                 int w;
954
955                 if((dev->cow.file != NULL) && (fd == dev->cow.fd))
956                         w = 0;
957                 else w = dev->openflags.w;
958
959                 if((dev->cow.file != NULL) && (fd == dev->fd))
960                         offset += dev->cow.data_offset;
961
962                 err = physmem_subst_mapping(req->buffer, fd, offset, w);
963                 if(err){
964                         printk("physmem_subst_mapping failed, err = %d\n",
965                                -err);
966                         return(1);
967                 }
968                 dev->map_reads++;
969         }
970         io_req->op = UBD_MMAP;
971         io_req->buffer = req->buffer;
972         return(0);
973 }
974
975 /* Called with ubd_io_lock held */
976 static int prepare_request(struct request *req, struct io_thread_req *io_req)
977 {
978         struct gendisk *disk = req->rq_disk;
979         struct ubd *dev = disk->private_data;
980         __u64 offset;
981         int len, fd;
982
983         if(req->rq_status == RQ_INACTIVE) return(1);
984
985         if((rq_data_dir(req) == WRITE) && !dev->openflags.w){
986                 printk("Write attempted on readonly ubd device %s\n", 
987                        disk->disk_name);
988                 end_request(req, 0);
989                 return(1);
990         }
991
992         offset = ((__u64) req->sector) << 9;
993         len = req->current_nr_sectors << 9;
994
995         io_req->fds[0] = (dev->cow.file != NULL) ? dev->cow.fd : dev->fd;
996         io_req->fds[1] = dev->fd;
997         io_req->map_fd = -1;
998         io_req->cow_offset = -1;
999         io_req->offset = offset;
1000         io_req->length = len;
1001         io_req->error = 0;
1002         io_req->sector_mask = 0;
1003
1004         fd = mmap_fd(req, dev, io_req->offset);
1005         if(fd > 0){
1006                 /* If mmapping is otherwise OK, but the first access to the
1007                  * page is a write, then it's not mapped in yet.  So we have
1008                  * to write the data to disk first, then we can map the disk
1009                  * page in and continue normally from there.
1010                  */
1011                 if((rq_data_dir(req) == WRITE) && !is_remapped(req->buffer)){
1012                         io_req->map_fd = dev->fd;
1013                         io_req->map_offset = io_req->offset +
1014                                 dev->cow.data_offset;
1015                         dev->write_maps++;
1016                 }
1017                 else return(prepare_mmap_request(dev, fd, io_req->offset, req,
1018                                                  io_req));
1019         }
1020
1021         if(rq_data_dir(req) == READ)
1022                 dev->nomap_reads++;
1023         else dev->nomap_writes++;
1024
1025         io_req->op = (rq_data_dir(req) == READ) ? UBD_READ : UBD_WRITE;
1026         io_req->offsets[0] = 0;
1027         io_req->offsets[1] = dev->cow.data_offset;
1028         io_req->buffer = req->buffer;
1029         io_req->sectorsize = 1 << 9;
1030
1031         if(dev->cow.file != NULL)
1032                 cowify_req(io_req, dev->cow.bitmap, dev->cow.bitmap_offset,
1033                            dev->cow.bitmap_len);
1034
1035         return(0);
1036 }
1037
1038 /* Called with ubd_io_lock held */
1039 static void do_ubd_request(request_queue_t *q)
1040 {
1041         struct io_thread_req io_req;
1042         struct request *req;
1043         int err, n;
1044
1045         if(thread_fd == -1){
1046                 while((req = elv_next_request(q)) != NULL){
1047                         err = prepare_request(req, &io_req);
1048                         if(!err){
1049                                 do_io(&io_req);
1050                                 __ubd_finish(req, io_req.error);
1051                         }
1052                 }
1053         }
1054         else {
1055                 if(do_ubd || (req = elv_next_request(q)) == NULL)
1056                         return;
1057                 err = prepare_request(req, &io_req);
1058                 if(!err){
1059                         do_ubd = ubd_handler;
1060                         n = write_ubd_fs(thread_fd, (char *) &io_req, 
1061                                          sizeof(io_req));
1062                         if(n != sizeof(io_req))
1063                                 printk("write to io thread failed, "
1064                                        "errno = %d\n", -n);
1065                 }
1066         }
1067 }
1068
1069 static int ubd_ioctl(struct inode * inode, struct file * file,
1070                      unsigned int cmd, unsigned long arg)
1071 {
1072         struct hd_geometry *loc = (struct hd_geometry *) arg;
1073         struct ubd *dev = inode->i_bdev->bd_disk->private_data;
1074         struct hd_driveid ubd_id = {
1075                 .cyls           = 0,
1076                 .heads          = 128,
1077                 .sectors        = 32,
1078         };
1079
1080         switch (cmd) {
1081                 struct hd_geometry g;
1082                 struct cdrom_volctrl volume;
1083         case HDIO_GETGEO:
1084                 if(!loc) return(-EINVAL);
1085                 g.heads = 128;
1086                 g.sectors = 32;
1087                 g.cylinders = dev->size / (128 * 32 * 512);
1088                 g.start = get_start_sect(inode->i_bdev);
1089                 return(copy_to_user(loc, &g, sizeof(g)) ? -EFAULT : 0);
1090
1091         case HDIO_GET_IDENTITY:
1092                 ubd_id.cyls = dev->size / (128 * 32 * 512);
1093                 if(copy_to_user((char *) arg, (char *) &ubd_id, 
1094                                  sizeof(ubd_id)))
1095                         return(-EFAULT);
1096                 return(0);
1097                 
1098         case CDROMVOLREAD:
1099                 if(copy_from_user(&volume, (char *) arg, sizeof(volume)))
1100                         return(-EFAULT);
1101                 volume.channel0 = 255;
1102                 volume.channel1 = 255;
1103                 volume.channel2 = 255;
1104                 volume.channel3 = 255;
1105                 if(copy_to_user((char *) arg, &volume, sizeof(volume)))
1106                         return(-EFAULT);
1107                 return(0);
1108         }
1109         return(-EINVAL);
1110 }
1111
1112 static int ubd_check_remapped(int fd, unsigned long address, int is_write,
1113                               __u64 offset)
1114 {
1115         __u64 bitmap_offset;
1116         unsigned long new_bitmap[2];
1117         int i, err, n;
1118
1119         /* If it's not a write access, we can't do anything about it */
1120         if(!is_write)
1121                 return(0);
1122
1123         /* We have a write */
1124         for(i = 0; i < sizeof(ubd_dev) / sizeof(ubd_dev[0]); i++){
1125                 struct ubd *dev = &ubd_dev[i];
1126
1127                 if((dev->fd != fd) && (dev->cow.fd != fd))
1128                         continue;
1129
1130                 /* It's a write to a ubd device */
1131
1132                 if(!dev->openflags.w){
1133                         /* It's a write access on a read-only device - probably
1134                          * shouldn't happen.  If the kernel is trying to change
1135                          * something with no intention of writing it back out,
1136                          * then this message will clue us in that this needs
1137                          * fixing
1138                          */
1139                         printk("Write access to mapped page from readonly ubd "
1140                                "device %d\n", i);
1141                         return(0);
1142                 }
1143
1144                 /* It's a write to a writeable ubd device - it must be COWed
1145                  * because, otherwise, the page would have been mapped in
1146                  * writeable
1147                  */
1148
1149                 if(!dev->cow.file)
1150                         panic("Write fault on writeable non-COW ubd device %d",
1151                               i);
1152
1153                 /* It should also be an access to the backing file since the
1154                  * COW pages should be mapped in read-write
1155                  */
1156
1157                 if(fd == dev->fd)
1158                         panic("Write fault on a backing page of ubd "
1159                               "device %d\n", i);
1160
1161                 /* So, we do the write, copying the backing data to the COW
1162                  * file...
1163                  */
1164
1165                 err = os_seek_file(dev->fd, offset + dev->cow.data_offset);
1166                 if(err < 0)
1167                         panic("Couldn't seek to %lld in COW file of ubd "
1168                               "device %d, err = %d",
1169                               offset + dev->cow.data_offset, i, -err);
1170
1171                 n = os_write_file(dev->fd, (void *) address, PAGE_SIZE);
1172                 if(n != PAGE_SIZE)
1173                         panic("Couldn't copy data to COW file of ubd "
1174                               "device %d, err = %d", i, -n);
1175
1176                 /* ... updating the COW bitmap... */
1177
1178                 cowify_bitmap(offset, PAGE_SIZE, NULL, &bitmap_offset,
1179                               dev->cow.bitmap, dev->cow.bitmap_offset,
1180                               new_bitmap, dev->cow.bitmap_len);
1181
1182                 err = os_seek_file(dev->fd, bitmap_offset);
1183                 if(err < 0)
1184                         panic("Couldn't seek to %lld in COW file of ubd "
1185                               "device %d, err = %d", bitmap_offset, i, -err);
1186
1187                 n = os_write_file(dev->fd, new_bitmap, sizeof(new_bitmap));
1188                 if(n != sizeof(new_bitmap))
1189                         panic("Couldn't update bitmap  of ubd device %d, "
1190                               "err = %d", i, -n);
1191
1192                 /* Maybe we can map the COW page in, and maybe we can't.  If
1193                  * it is a pre-V3 COW file, we can't, since the alignment will
1194                  * be wrong.  If it is a V3 or later COW file which has been
1195                  * moved to a system with a larger page size, then maybe we
1196                  * can't, depending on the exact location of the page.
1197                  */
1198
1199                 offset += dev->cow.data_offset;
1200
1201                 /* Remove the remapping, putting the original anonymous page
1202                  * back.  If the COW file can be mapped in, that is done.
1203                  * Otherwise, the COW page is read in.
1204                  */
1205
1206                 if(!physmem_remove_mapping((void *) address))
1207                         panic("Address 0x%lx not remapped by ubd device %d",
1208                               address, i);
1209                 if((offset % UBD_MMAP_BLOCK_SIZE) == 0)
1210                         physmem_subst_mapping((void *) address, dev->fd,
1211                                               offset, 1);
1212                 else {
1213                         err = os_seek_file(dev->fd, offset);
1214                         if(err < 0)
1215                                 panic("Couldn't seek to %lld in COW file of "
1216                                       "ubd device %d, err = %d", offset, i,
1217                                       -err);
1218
1219                         n = os_read_file(dev->fd, (void *) address, PAGE_SIZE);
1220                         if(n != PAGE_SIZE)
1221                                 panic("Failed to read page from offset %llx of "
1222                                       "COW file of ubd device %d, err = %d",
1223                                       offset, i, -n);
1224                 }
1225
1226                 return(1);
1227         }
1228
1229         /* It's not a write on a ubd device */
1230         return(0);
1231 }
1232
1233 static struct remapper ubd_remapper = {
1234         .list   = LIST_HEAD_INIT(ubd_remapper.list),
1235         .proc   = ubd_check_remapped,
1236 };
1237
1238 static int ubd_remapper_setup(void)
1239 {
1240         if(ubd_do_mmap)
1241                 register_remapper(&ubd_remapper);
1242
1243         return(0);
1244 }
1245
1246 __initcall(ubd_remapper_setup);
1247
1248 /*
1249  * Overrides for Emacs so that we follow Linus's tabbing style.
1250  * Emacs will notice this stuff at the end of the file and automatically
1251  * adjust the settings for this buffer only.  This must remain at the end
1252  * of the file.
1253  * ---------------------------------------------------------------------------
1254  * Local variables:
1255  * c-file-style: "linux"
1256  * End:
1257  */