/*
       *  linux/drivers/block/floppy.c
       *
       *  Copyright (C) 1991, 1992  Linus Torvalds
       *  Copyright (C) 1993, 1994  Alain Knaff
       *  Copyright (C) 1998 Alan Cox
       */
      /*
       * 02.12.91 - Changed to static variables to indicate need for reset
       * and recalibrate. This makes some things easier (output_byte reset
       * checking etc), and means less interrupt jumping in case of errors,
       * so the code is hopefully easier to understand.
       */
      
      /*
       * This file is certainly a mess. I've tried my best to get it working,
       * but I don't like programming floppies, and I have only one anyway.
       * Urgel. I should check for more errors, and do more graceful error
       * recovery. Seems there are problems with several drives. I've tried to
       * correct them. No promises.
       */
      
      /*
       * As with hd.c, all routines within this file can (and will) be called
       * by interrupts, so extreme caution is needed. A hardware interrupt
       * handler may not sleep, or a kernel panic will happen. Thus I cannot
       * call "floppy-on" directly, but have to set a special timer interrupt
       * etc.
       */
      
      /*
       * 28.02.92 - made track-buffering routines, based on the routines written
       * by entropy@wintermute.wpi.edu (Lawrence Foard). Linus.
       */
      
      /*
       * Automatic floppy-detection and formatting written by Werner Almesberger
       * (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with
       * the floppy-change signal detection.
       */
      
      /*
       * 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed
       * FDC data overrun bug, added some preliminary stuff for vertical
       * recording support.
       *
       * 1992/9/17: Added DMA allocation & DMA functions. -- hhb.
       *
       * TODO: Errors are still not counted properly.
       */
      
      /* 1992/9/20
       * Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl)
       * modeled after the freeware MS-DOS program fdformat/88 V1.8 by
       * Christoph H. Hochst\"atter.
       * I have fixed the shift values to the ones I always use. Maybe a new
       * ioctl() should be created to be able to modify them.
       * There is a bug in the driver that makes it impossible to format a
       * floppy as the first thing after bootup.
       */
      
      /*
       * 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and
       * this helped the floppy driver as well. Much cleaner, and still seems to
       * work.
       */
      
      /* 1994/6/24 --bbroad-- added the floppy table entries and made
       * minor modifications to allow 2.88 floppies to be run.
       */
      
      /* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more
       * disk types.
       */
      
      /*
       * 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger
       * format bug fixes, but unfortunately some new bugs too...
       */
      
      /* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write
       * errors to allow safe writing by specialized programs.
       */
      
      /* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5" disks
       * by defining bit 1 of the "stretch" parameter to mean put sectors on the
       * opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's
       * drives are "upside-down").
       */
      
      /*
       * 1995/8/26 -- Andreas Busse -- added Mips support.
       */
      
      /*
       * 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent
       * features to asm/floppy.h.
       */
      
      /*
       * 1998/05/07 -- Russell King -- More portability cleanups; moved definition of
       * interrupt and dma channel to asm/floppy.h. Cleaned up some formatting &
       * use of '0' for NULL.
       */
       
      /*
       * 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation
       * failures.
       */
      
      /*
       * 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives.
       */
      
      /*
       * 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24
       * days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were
       * being used to store jiffies, which are unsigned longs).
       */
      
      /*
       * 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br>
       * - get rid of check_region
       * - s/suser/capable/
       */
      
      #define FLOPPY_SANITY_CHECK
      #undef  FLOPPY_SILENT_DCL_CLEAR
      
      #define REALLY_SLOW_IO
      
      #define DEBUGT 2
      #define DCL_DEBUG /* debug disk change line */
      
      /* do print messages for unexpected interrupts */
      static int print_unex=1;
      #include <linux/module.h>
      #include <linux/sched.h>
      #include <linux/fs.h>
      #include <linux/kernel.h>
      #include <linux/timer.h>
      #include <linux/tqueue.h>
      #define FDPATCHES
      #include <linux/fdreg.h>
      
      /*
       * 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support
       */
      
      
      #include <linux/fd.h>
      #include <linux/hdreg.h>
      
      #include <linux/errno.h>
      #include <linux/malloc.h>
      #include <linux/mm.h>
      #include <linux/string.h>
      #include <linux/fcntl.h>
      #include <linux/delay.h>
      #include <linux/mc146818rtc.h> /* CMOS defines */
      #include <linux/ioport.h>
      #include <linux/interrupt.h>
      #include <linux/init.h>
      #include <linux/devfs_fs_kernel.h>
      
      /*
       * PS/2 floppies have much slower step rates than regular floppies.
       * It's been recommended that take about 1/4 of the default speed
       * in some more extreme cases.
       */
      static int slow_floppy;
      
      #include <asm/dma.h>
      #include <asm/irq.h>
      #include <asm/system.h>
      #include <asm/io.h>
      #include <asm/uaccess.h>
      
      static int FLOPPY_IRQ=6;
      static int FLOPPY_DMA=2;
      static int can_use_virtual_dma=2;
      /* =======
       * can use virtual DMA:
       * 0 = use of virtual DMA disallowed by config
       * 1 = use of virtual DMA prescribed by config
       * 2 = no virtual DMA preference configured.  By default try hard DMA,
       * but fall back on virtual DMA when not enough memory available
       */
      
      static int use_virtual_dma;
      /* =======
       * use virtual DMA
       * 0 using hard DMA
       * 1 using virtual DMA
       * This variable is set to virtual when a DMA mem problem arises, and
       * reset back in floppy_grab_irq_and_dma.
       * It is not safe to reset it in other circumstances, because the floppy
       * driver may have several buffers in use at once, and we do currently not
       * record each buffers capabilities
       */
      
      static unsigned short virtual_dma_port=0x3f0;
      void floppy_interrupt(int irq, void *dev_id, struct pt_regs * regs);
      static int set_dor(int fdc, char mask, char data);
      static void register_devfs_entries (int drive) __init;
      static devfs_handle_t devfs_handle;
      
      #define K_64	0x10000		/* 64KB */
      
      /* the following is the mask of allowed drives. By default units 2 and
       * 3 of both floppy controllers are disabled, because switching on the
       * motor of these drives causes system hangs on some PCI computers. drive
       * 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if
       * a drive is allowed.
       *
       * NOTE: This must come before we include the arch floppy header because
       *       some ports reference this variable from there. -DaveM
       */
      
      static int allowed_drive_mask = 0x33;
      
      #include <asm/floppy.h>
      
      static int irqdma_allocated;
      
      #define MAJOR_NR FLOPPY_MAJOR
      
      #include <linux/blk.h>
      #include <linux/blkpg.h>
      #include <linux/cdrom.h> /* for the compatibility eject ioctl */
      
      #ifndef fd_get_dma_residue
      #define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA)
      #endif
      
      /* Dma Memory related stuff */
      
      #ifndef fd_dma_mem_free
      #define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size))
      #endif
      
      #ifndef fd_dma_mem_alloc
      #define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL,get_order(size))
      #endif
      
 246  static inline void fallback_on_nodma_alloc(char **addr, size_t l)
      {
      #ifdef FLOPPY_CAN_FALLBACK_ON_NODMA
 249  	if (*addr)
 250  		return; /* we have the memory */
 251  	if (can_use_virtual_dma != 2)
 252  		return; /* no fallback allowed */
      	printk("DMA memory shortage. Temporarily falling back on virtual DMA\n");
      	*addr = (char *) nodma_mem_alloc(l);
      #else
      	return;
      #endif
      }
      
      /* End dma memory related stuff */
      
      static unsigned long fake_change;
      static int initialising=1;
      
 265  static inline int TYPE(kdev_t x) {
 266  	return  (MINOR(x)>>2) & 0x1f;
      }
 268  static inline int DRIVE(kdev_t x) {
 269  	return (MINOR(x)&0x03) | ((MINOR(x)&0x80) >> 5);
      }
      #define ITYPE(x) (((x)>>2) & 0x1f)
      #define TOMINOR(x) ((x & 3) | ((x & 4) << 5))
      #define UNIT(x) ((x) & 0x03)		/* drive on fdc */
      #define FDC(x) (((x) & 0x04) >> 2)  /* fdc of drive */
      #define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2))
      				/* reverse mapping from unit and fdc to drive */
      #define DP (&drive_params[current_drive])
      #define DRS (&drive_state[current_drive])
      #define DRWE (&write_errors[current_drive])
      #define FDCS (&fdc_state[fdc])
      #define CLEARF(x) (clear_bit(x##_BIT, &DRS->flags))
      #define SETF(x) (set_bit(x##_BIT, &DRS->flags))
      #define TESTF(x) (test_bit(x##_BIT, &DRS->flags))
      
      #define UDP (&drive_params[drive])
      #define UDRS (&drive_state[drive])
      #define UDRWE (&write_errors[drive])
      #define UFDCS (&fdc_state[FDC(drive)])
      #define UCLEARF(x) (clear_bit(x##_BIT, &UDRS->flags))
      #define USETF(x) (set_bit(x##_BIT, &UDRS->flags))
      #define UTESTF(x) (test_bit(x##_BIT, &UDRS->flags))
      
      #define DPRINT(format, args...) printk(DEVICE_NAME "%d: " format, current_drive , ## args)
      
      #define PH_HEAD(floppy,head) (((((floppy)->stretch & 2) >>1) ^ head) << 2)
      #define STRETCH(floppy) ((floppy)->stretch & FD_STRETCH)
      
      #define CLEARSTRUCT(x) memset((x), 0, sizeof(*(x)))
      
      /* read/write */
      #define COMMAND raw_cmd->cmd[0]
      #define DR_SELECT raw_cmd->cmd[1]
      #define TRACK raw_cmd->cmd[2]
      #define HEAD raw_cmd->cmd[3]
      #define SECTOR raw_cmd->cmd[4]
      #define SIZECODE raw_cmd->cmd[5]
      #define SECT_PER_TRACK raw_cmd->cmd[6]
      #define GAP raw_cmd->cmd[7]
      #define SIZECODE2 raw_cmd->cmd[8]
      #define NR_RW 9
      
      /* format */
      #define F_SIZECODE raw_cmd->cmd[2]
      #define F_SECT_PER_TRACK raw_cmd->cmd[3]
      #define F_GAP raw_cmd->cmd[4]
      #define F_FILL raw_cmd->cmd[5]
      #define NR_F 6
      
      /*
       * Maximum disk size (in kilobytes). This default is used whenever the
       * current disk size is unknown.
       * [Now it is rather a minimum]
       */
      #define MAX_DISK_SIZE 4 /* 3984*/
      
      
      /*
       * globals used by 'result()'
       */
      #define MAX_REPLIES 16
      static unsigned char reply_buffer[MAX_REPLIES];
      static int inr; /* size of reply buffer, when called from interrupt */
      #define ST0 (reply_buffer[0])
      #define ST1 (reply_buffer[1])
      #define ST2 (reply_buffer[2])
      #define ST3 (reply_buffer[0]) /* result of GETSTATUS */
      #define R_TRACK (reply_buffer[3])
      #define R_HEAD (reply_buffer[4])
      #define R_SECTOR (reply_buffer[5])
      #define R_SIZECODE (reply_buffer[6])
      
      #define SEL_DLY (2*HZ/100)
      
      /*
       * this struct defines the different floppy drive types.
       */
      static struct {
      	struct floppy_drive_params params;
      	const char *name; /* name printed while booting */
      } default_drive_params[]= {
      /* NOTE: the time values in jiffies should be in msec!
       CMOS drive type
        |     Maximum data rate supported by drive type
        |     |   Head load time, msec
        |     |   |   Head unload time, msec (not used)
        |     |   |   |     Step rate interval, usec
        |     |   |   |     |       Time needed for spinup time (jiffies)
        |     |   |   |     |       |      Timeout for spinning down (jiffies)
        |     |   |   |     |       |      |   Spindown offset (where disk stops)
        |     |   |   |     |       |      |   |     Select delay
        |     |   |   |     |       |      |   |     |     RPS
        |     |   |   |     |       |      |   |     |     |    Max number of tracks
        |     |   |   |     |       |      |   |     |     |    |     Interrupt timeout
        |     |   |   |     |       |      |   |     |     |    |     |   Max nonintlv. sectors
        |     |   |   |     |       |      |   |     |     |    |     |   | -Max Errors- flags */
      {{0,  500, 16, 16, 8000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  80, 3*HZ, 20, {3,1,2,0,2}, 0,
            0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, "unknown" },
      
      {{1,  300, 16, 16, 8000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  40, 3*HZ, 17, {3,1,2,0,2}, 0,
            0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, "360K PC" }, /*5 1/4 360 KB PC*/
      
      {{2,  500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6,  83, 3*HZ, 17, {3,1,2,0,2}, 0,
            0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, "1.2M" }, /*5 1/4 HD AT*/
      
      {{3,  250, 16, 16, 3000,    1*HZ, 3*HZ,  0, SEL_DLY, 5,  83, 3*HZ, 20, {3,1,2,0,2}, 0,
            0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, "720k" }, /*3 1/2 DD*/
      
      {{4,  500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 20, {3,1,2,0,2}, 0,
            0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, "1.44M" }, /*3 1/2 HD*/
      
      {{5, 1000, 15,  8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 40, {3,1,2,0,2}, 0,
            0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M AMI BIOS" }, /*3 1/2 ED*/
      
      {{6, 1000, 15,  8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5,  83, 3*HZ, 40, {3,1,2,0,2}, 0,
            0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M" } /*3 1/2 ED*/
      /*    |  --autodetected formats---    |      |      |
       *    read_track                      |      |    Name printed when booting
       *				      |     Native format
       *	            Frequency of disk change checks */
      };
      
      static struct floppy_drive_params drive_params[N_DRIVE];
      static struct floppy_drive_struct drive_state[N_DRIVE];
      static struct floppy_write_errors write_errors[N_DRIVE];
      static struct floppy_raw_cmd *raw_cmd, default_raw_cmd;
      
      /*
       * This struct defines the different floppy types.
       *
       * Bit 0 of 'stretch' tells if the tracks need to be doubled for some
       * types (e.g. 360kB diskette in 1.2MB drive, etc.).  Bit 1 of 'stretch'
       * tells if the disk is in Commodore 1581 format, which means side 0 sectors
       * are located on side 1 of the disk but with a side 0 ID, and vice-versa.
       * This is the same as the Sharp MZ-80 5.25" CP/M disk format, except that the
       * 1581's logical side 0 is on physical side 1, whereas the Sharp's logical
       * side 0 is on physical side 0 (but with the misnamed sector IDs).
       * 'stretch' should probably be renamed to something more general, like
       * 'options'.  Other parameters should be self-explanatory (see also
       * setfdprm(8)).
       */
      /*
      	    Size
      	     |  Sectors per track
      	     |  | Head
      	     |  | |  Tracks
      	     |  | |  | Stretch
      	     |  | |  | |  Gap 1 size
      	     |  | |  | |    |  Data rate, | 0x40 for perp
      	     |  | |  | |    |    |  Spec1 (stepping rate, head unload
      	     |  | |  | |    |    |    |    /fmt gap (gap2) */
      static struct floppy_struct floppy_type[32] = {
      	{    0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL    },	/*  0 no testing    */
      	{  720, 9,2,40,0,0x2A,0x02,0xDF,0x50,"d360"  }, /*  1 360KB PC      */
      	{ 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,"h1200" },	/*  2 1.2MB AT      */
      	{  720, 9,1,80,0,0x2A,0x02,0xDF,0x50,"D360"  },	/*  3 360KB SS 3.5" */
      	{ 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,"D720"  },	/*  4 720KB 3.5"    */
      	{  720, 9,2,40,1,0x23,0x01,0xDF,0x50,"h360"  },	/*  5 360KB AT      */
      	{ 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,"h720"  },	/*  6 720KB AT      */
      	{ 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,"H1440" },	/*  7 1.44MB 3.5"   */
      	{ 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,"E2880" },	/*  8 2.88MB 3.5"   */
      	{ 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,"E3120" },	/*  9 3.12MB 3.5"   */
      
      	{ 2880,18,2,80,0,0x25,0x00,0xDF,0x02,"h1440" }, /* 10 1.44MB 5.25"  */
      	{ 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,"H1680" }, /* 11 1.68MB 3.5"   */
      	{  820,10,2,41,1,0x25,0x01,0xDF,0x2E,"h410"  },	/* 12 410KB 5.25"   */
      	{ 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,"H820"  },	/* 13 820KB 3.5"    */
      	{ 2952,18,2,82,0,0x25,0x00,0xDF,0x02,"h1476" },	/* 14 1.48MB 5.25"  */
      	{ 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,"H1722" },	/* 15 1.72MB 3.5"   */
      	{  840,10,2,42,1,0x25,0x01,0xDF,0x2E,"h420"  },	/* 16 420KB 5.25"   */
      	{ 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,"H830"  },	/* 17 830KB 3.5"    */
      	{ 2988,18,2,83,0,0x25,0x00,0xDF,0x02,"h1494" },	/* 18 1.49MB 5.25"  */
      	{ 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,"H1743" }, /* 19 1.74 MB 3.5"  */
      
      	{ 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,"h880"  }, /* 20 880KB 5.25"   */
      	{ 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,"D1040" }, /* 21 1.04MB 3.5"   */
      	{ 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,"D1120" }, /* 22 1.12MB 3.5"   */
      	{ 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,"h1600" }, /* 23 1.6MB 5.25"   */
      	{ 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,"H1760" }, /* 24 1.76MB 3.5"   */
      	{ 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,"H1920" }, /* 25 1.92MB 3.5"   */
      	{ 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,"E3200" }, /* 26 3.20MB 3.5"   */
      	{ 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,"E3520" }, /* 27 3.52MB 3.5"   */
      	{ 7680,48,2,80,0,0x25,0x63,0xCF,0x00,"E3840" }, /* 28 3.84MB 3.5"   */
      
      	{ 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,"H1840" }, /* 29 1.84MB 3.5"   */
      	{ 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,"D800"  },	/* 30 800KB 3.5"    */
      	{ 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,"H1600" }, /* 31 1.6MB 3.5"    */
      };
      
      #define	NUMBER(x)	(sizeof(x) / sizeof(*(x)))
      #define SECTSIZE (_FD_SECTSIZE(*floppy))
      
      /* Auto-detection: Disk type used until the next media change occurs. */
      static struct floppy_struct *current_type[N_DRIVE];
      
      /*
       * User-provided type information. current_type points to
       * the respective entry of this array.
       */
      static struct floppy_struct user_params[N_DRIVE];
      
      static int floppy_sizes[256];
      static int floppy_blocksizes[256];
      
      /*
       * The driver is trying to determine the correct media format
       * while probing is set. rw_interrupt() clears it after a
       * successful access.
       */
      static int probing;
      
      /* Synchronization of FDC access. */
      #define FD_COMMAND_NONE -1
      #define FD_COMMAND_ERROR 2
      #define FD_COMMAND_OKAY 3
      
      static volatile int command_status = FD_COMMAND_NONE;
      static unsigned long fdc_busy;
      static DECLARE_WAIT_QUEUE_HEAD(fdc_wait);
      static DECLARE_WAIT_QUEUE_HEAD(command_done);
      
      #define NO_SIGNAL (!interruptible || !signal_pending(current))
      #define CALL(x) if ((x) == -EINTR) return -EINTR
      #define ECALL(x) if ((ret = (x))) return ret;
      #define _WAIT(x,i) CALL(ret=wait_til_done((x),i))
      #define WAIT(x) _WAIT((x),interruptible)
      #define IWAIT(x) _WAIT((x),1)
      
      /* Errors during formatting are counted here. */
      static int format_errors;
      
      /* Format request descriptor. */
      static struct format_descr format_req;
      
      /*
       * Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps
       * Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc),
       * H is head unload time (1=16ms, 2=32ms, etc)
       */
      
      /*
       * Track buffer
       * Because these are written to by the DMA controller, they must
       * not contain a 64k byte boundary crossing, or data will be
       * corrupted/lost.
       */
      static char *floppy_track_buffer;
      static int max_buffer_sectors;
      
      static int *errors;
      typedef void (*done_f)(int);
      static struct cont_t {
      	void (*interrupt)(void); /* this is called after the interrupt of the
      				  * main command */
      	void (*redo)(void); /* this is called to retry the operation */
      	void (*error)(void); /* this is called to tally an error */
      	done_f done; /* this is called to say if the operation has 
      		      * succeeded/failed */
      } *cont;
      
      static void floppy_ready(void);
      static void floppy_start(void);
      static void process_fd_request(void);
      static void recalibrate_floppy(void);
      static void floppy_shutdown(void);
      
      static int floppy_grab_irq_and_dma(void);
      static void floppy_release_irq_and_dma(void);
      
      /*
       * The "reset" variable should be tested whenever an interrupt is scheduled,
       * after the commands have been sent. This is to ensure that the driver doesn't
       * get wedged when the interrupt doesn't come because of a failed command.
       * reset doesn't need to be tested before sending commands, because
       * output_byte is automatically disabled when reset is set.
       */
      #define CHECK_RESET { if (FDCS->reset){ reset_fdc(); return; } }
      static void reset_fdc(void);
      
      /*
       * These are global variables, as that's the easiest way to give
       * information to interrupts. They are the data used for the current
       * request.
       */
      #define NO_TRACK -1
      #define NEED_1_RECAL -2
      #define NEED_2_RECAL -3
      
      static int usage_count;
      
      /* buffer related variables */
      static int buffer_track = -1;
      static int buffer_drive = -1;
      static int buffer_min = -1;
      static int buffer_max = -1;
      
      /* fdc related variables, should end up in a struct */
      static struct floppy_fdc_state fdc_state[N_FDC];
      static int fdc; /* current fdc */
      
      static struct floppy_struct *_floppy = floppy_type;
      static unsigned char current_drive;
      static long current_count_sectors;
      static unsigned char sector_t; /* sector in track */
      static unsigned char in_sector_offset;	/* offset within physical sector,
      					 * expressed in units of 512 bytes */
      
      #ifndef fd_eject
      #define fd_eject(x) -EINVAL
      #endif
      
      #ifdef DEBUGT
      static long unsigned debugtimer;
      #endif
      
      /*
       * Debugging
       * =========
       */
 589  static inline void set_debugt(void)
      {
      #ifdef DEBUGT
      	debugtimer = jiffies;
      #endif
      }
      
 596  static inline void debugt(const char *message)
      {
      #ifdef DEBUGT
 599  	if (DP->flags & DEBUGT)
      		printk("%s dtime=%lu\n", message, jiffies-debugtimer);
      #endif
      }
      
      typedef void (*timeout_fn)(unsigned long);
      static struct timer_list fd_timeout ={ function: (timeout_fn) floppy_shutdown };
      
      static const char *timeout_message;
      
      #ifdef FLOPPY_SANITY_CHECK
 610  static void is_alive(const char *message)
      {
      	/* this routine checks whether the floppy driver is "alive" */
 613  	if (fdc_busy && command_status < 2 && !timer_pending(&fd_timeout)){
      		DPRINT("timeout handler died: %s\n",message);
      	}
      }
      #endif
      
      #ifdef FLOPPY_SANITY_CHECK
      
      #define OLOGSIZE 20
      
      static void (*lasthandler)(void);
      static unsigned long interruptjiffies;
      static unsigned long resultjiffies;
      static int resultsize;
      static unsigned long lastredo;
      
      static struct output_log {
      	unsigned char data;
      	unsigned char status;
      	unsigned long jiffies;
      } output_log[OLOGSIZE];
      
      static int output_log_pos;
      #endif
      
      #define CURRENTD -1
      #define MAXTIMEOUT -2
      
 641  static void reschedule_timeout(int drive, const char *message, int marg)
      {
 643  	if (drive == CURRENTD)
      		drive = current_drive;
      	del_timer(&fd_timeout);
 646  	if (drive < 0 || drive > N_DRIVE) {
      		fd_timeout.expires = jiffies + 20UL*HZ;
      		drive=0;
 649  	} else
      		fd_timeout.expires = jiffies + UDP->timeout;
      	add_timer(&fd_timeout);
 652  	if (UDP->flags & FD_DEBUG){
      		DPRINT("reschedule timeout ");
      		printk(message, marg);
      		printk("\n");
      	}
      	timeout_message = message;
      }
      
 660  static int maximum(int a, int b)
      {
 662  	if (a > b)
 663  		return a;
 664  	else
 665  		return b;
      }
      #define INFBOUND(a,b) (a)=maximum((a),(b));
      
 669  static int minimum(int a, int b)
      {
 671  	if (a < b)
 672  		return a;
 673  	else
 674  		return b;
      }
      #define SUPBOUND(a,b) (a)=minimum((a),(b));
      
      
      /*
       * Bottom half floppy driver.
       * ==========================
       *
       * This part of the file contains the code talking directly to the hardware,
       * and also the main service loop (seek-configure-spinup-command)
       */
      
      /*
       * disk change.
       * This routine is responsible for maintaining the FD_DISK_CHANGE flag,
       * and the last_checked date.
       *
       * last_checked is the date of the last check which showed 'no disk change'
       * FD_DISK_CHANGE is set under two conditions:
       * 1. The floppy has been changed after some i/o to that floppy already
       *    took place.
       * 2. No floppy disk is in the drive. This is done in order to ensure that
       *    requests are quickly flushed in case there is no disk in the drive. It
       *    follows that FD_DISK_CHANGE can only be cleared if there is a disk in
       *    the drive.
       *
       * For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet.
       * For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on
       *  each seek. If a disk is present, the disk change line should also be
       *  cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk
       *  change line is set, this means either that no disk is in the drive, or
       *  that it has been removed since the last seek.
       *
       * This means that we really have a third possibility too:
       *  The floppy has been changed after the last seek.
       */
      
 712  static int disk_change(int drive)
      {
      	int fdc=FDC(drive);
      #ifdef FLOPPY_SANITY_CHECK
 716  	if (jiffies - UDRS->select_date < UDP->select_delay)
      		DPRINT("WARNING disk change called early\n");
      	if (!(FDCS->dor & (0x10 << UNIT(drive))) ||
      	    (FDCS->dor & 3) != UNIT(drive) ||
 720  	    fdc != FDC(drive)){
      		DPRINT("probing disk change on unselected drive\n");
      		DPRINT("drive=%d fdc=%d dor=%x\n",drive, FDC(drive),
      			(unsigned int)FDCS->dor);
      	}
      #endif
      
      #ifdef DCL_DEBUG
 728  	if (UDP->flags & FD_DEBUG){
      		DPRINT("checking disk change line for drive %d\n",drive);
      		DPRINT("jiffies=%lu\n", jiffies);
      		DPRINT("disk change line=%x\n",fd_inb(FD_DIR)&0x80);
      		DPRINT("flags=%lx\n",UDRS->flags);
      	}
      #endif
 735  	if (UDP->flags & FD_BROKEN_DCL)
 736  		return UTESTF(FD_DISK_CHANGED);
 737  	if ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80){
      		USETF(FD_VERIFY); /* verify write protection */
 739  		if (UDRS->maxblock){
      			/* mark it changed */
      			USETF(FD_DISK_CHANGED);
      		}
      
      		/* invalidate its geometry */
 745  		if (UDRS->keep_data >= 0) {
      			if ((UDP->flags & FTD_MSG) &&
 747  			    current_type[drive] != NULL)
      				DPRINT("Disk type is undefined after "
      				       "disk change\n");
      			current_type[drive] = NULL;
      			floppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE;
      		}
      
      		/*USETF(FD_DISK_NEWCHANGE);*/
 755  		return 1;
 756  	} else {
      		UDRS->last_checked=jiffies;
      		UCLEARF(FD_DISK_NEWCHANGE);
      	}
 760  	return 0;
      }
      
 763  static inline int is_selected(int dor, int unit)
      {
 765  	return ((dor  & (0x10 << unit)) && (dor &3) == unit);
      }
      
 768  static int set_dor(int fdc, char mask, char data)
      {
      	register unsigned char drive, unit, newdor,olddor;
      
 772  	if (FDCS->address == -1)
 773  		return -1;
      
      	olddor = FDCS->dor;
      	newdor =  (olddor & mask) | data;
 777  	if (newdor != olddor){
      		unit = olddor & 0x3;
 779  		if (is_selected(olddor, unit) && !is_selected(newdor,unit)){
      			drive = REVDRIVE(fdc,unit);
      #ifdef DCL_DEBUG
 782  			if (UDP->flags & FD_DEBUG){
      				DPRINT("calling disk change from set_dor\n");
      			}
      #endif
      			disk_change(drive);
      		}
      		FDCS->dor = newdor;
      		fd_outb(newdor, FD_DOR);
      
      		unit = newdor & 0x3;
 792  		if (!is_selected(olddor, unit) && is_selected(newdor,unit)){
      			drive = REVDRIVE(fdc,unit);
      			UDRS->select_date = jiffies;
      		}
      	}
      	/*
      	 *	We should propogate failures to grab the resources back
      	 *	nicely from here. Actually we ought to rewrite the fd
      	 *	driver some day too.
      	 */
 802  	if (newdor & FLOPPY_MOTOR_MASK)
      		floppy_grab_irq_and_dma();
 804  	if (olddor & FLOPPY_MOTOR_MASK)
      		floppy_release_irq_and_dma();
 806  	return olddor;
      }
      
 809  static void twaddle(void)
      {
 811  	if (DP->select_delay)
 812  		return;
      	fd_outb(FDCS->dor & ~(0x10<<UNIT(current_drive)), FD_DOR);
      	fd_outb(FDCS->dor, FD_DOR);
      	DRS->select_date = jiffies;
      }
      
      /* reset all driver information about the current fdc. This is needed after
       * a reset, and after a raw command. */
 820  static void reset_fdc_info(int mode)
      {
      	int drive;
      
      	FDCS->spec1 = FDCS->spec2 = -1;
      	FDCS->need_configure = 1;
      	FDCS->perp_mode = 1;
      	FDCS->rawcmd = 0;
 828  	for (drive = 0; drive < N_DRIVE; drive++)
      		if (FDC(drive) == fdc &&
 830  		    (mode || UDRS->track != NEED_1_RECAL))
      			UDRS->track = NEED_2_RECAL;
      }
      
      /* selects the fdc and drive, and enables the fdc's input/dma. */
 835  static void set_fdc(int drive)
      {
 837  	if (drive >= 0 && drive < N_DRIVE){
      		fdc = FDC(drive);
      		current_drive = drive;
      	}
 841  	if (fdc != 1 && fdc != 0) {
      		printk("bad fdc value\n");
 843  		return;
      	}
      	set_dor(fdc,~0,8);
      #if N_FDC > 1
      	set_dor(1-fdc, ~8, 0);
      #endif
 849  	if (FDCS->rawcmd == 2)
      		reset_fdc_info(1);
 851  	if (fd_inb(FD_STATUS) != STATUS_READY)
      		FDCS->reset = 1;
      }
      
      /* locks the driver */
 856  static int _lock_fdc(int drive, int interruptible, int line)
      {
 858  	if (!usage_count){
      		printk(KERN_ERR "Trying to lock fdc while usage count=0 at line %d\n", line);
 860  		return -1;
      	}
 862  	if(floppy_grab_irq_and_dma()==-1)
 863  		return -EBUSY;
      
 865  	if (test_and_set_bit(0, &fdc_busy)) {
      		DECLARE_WAITQUEUE(wait, current);
      		add_wait_queue(&fdc_wait, &wait);
      
 869  		for (;;) {
 870  			set_current_state(TASK_INTERRUPTIBLE);
      
 872  			if (!test_and_set_bit(0, &fdc_busy))
 873  				break;
      
      			schedule();
      
 877  			if (!NO_SIGNAL) {
      				remove_wait_queue(&fdc_wait, &wait);
 879  				return -EINTR;
      			}
      		}
      
 883  		set_current_state(TASK_RUNNING);
      		remove_wait_queue(&fdc_wait, &wait);
      	}
      	command_status = FD_COMMAND_NONE;
      
      	reschedule_timeout(drive, "lock fdc", 0);
      	set_fdc(drive);
 890  	return 0;
      }
      
      #define lock_fdc(drive,interruptible) _lock_fdc(drive,interruptible, __LINE__)
      
      #define LOCK_FDC(drive,interruptible) \
      if (lock_fdc(drive,interruptible)) return -EINTR;
      
      
      /* unlocks the driver */
 900  static inline void unlock_fdc(void)
      {
      	raw_cmd = 0;
 903  	if (!fdc_busy)
      		DPRINT("FDC access conflict!\n");
      
 906  	if (DEVICE_INTR)
      		DPRINT("device interrupt still active at FDC release: %p!\n",
      			DEVICE_INTR);
      	command_status = FD_COMMAND_NONE;
      	del_timer(&fd_timeout);
      	cont = NULL;
      	clear_bit(0, &fdc_busy);
      	floppy_release_irq_and_dma();
      	wake_up(&fdc_wait);
      }
      
      /* switches the motor off after a given timeout */
 918  static void motor_off_callback(unsigned long nr)
      {
      	unsigned char mask = ~(0x10 << UNIT(nr));
      
      	set_dor(FDC(nr), mask, 0);
      }
      
      static struct timer_list motor_off_timer[N_DRIVE] = {
      	{ data: 0, function: motor_off_callback },
      	{ data: 1, function: motor_off_callback },
      	{ data: 2, function: motor_off_callback },
      	{ data: 3, function: motor_off_callback },
      	{ data: 4, function: motor_off_callback },
      	{ data: 5, function: motor_off_callback },
      	{ data: 6, function: motor_off_callback },
      	{ data: 7, function: motor_off_callback }
      };
      
      /* schedules motor off */
 937  static void floppy_off(unsigned int drive)
      {
      	unsigned long volatile delta;
      	register int fdc=FDC(drive);
      
 942  	if (!(FDCS->dor & (0x10 << UNIT(drive))))
 943  		return;
      
      	del_timer(motor_off_timer+drive);
      
      	/* make spindle stop in a position which minimizes spinup time
      	 * next time */
 949  	if (UDP->rps){
      		delta = jiffies - UDRS->first_read_date + HZ -
      			UDP->spindown_offset;
      		delta = ((delta * UDP->rps) % HZ) / UDP->rps;
      		motor_off_timer[drive].expires = jiffies + UDP->spindown - delta;
      	}
      	add_timer(motor_off_timer+drive);
      }
      
      /*
       * cycle through all N_DRIVE floppy drives, for disk change testing.
       * stopping at current drive. This is done before any long operation, to
       * be sure to have up to date disk change information.
       */
 963  static void scandrives(void)
      {
      	int i, drive, saved_drive;
      
 967  	if (DP->select_delay)
 968  		return;
      
      	saved_drive = current_drive;
 971  	for (i=0; i < N_DRIVE; i++){
      		drive = (saved_drive + i + 1) % N_DRIVE;
 973  		if (UDRS->fd_ref == 0 || UDP->select_delay != 0)
 974  			continue; /* skip closed drives */
      		set_fdc(drive);
      		if (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) &
 977  		      (0x10 << UNIT(drive))))
      			/* switch the motor off again, if it was off to
      			 * begin with */
      			set_dor(fdc, ~(0x10 << UNIT(drive)), 0);
      	}
      	set_fdc(saved_drive);
      }
      
 985  static void empty(void)
      {
      }
      
      static struct tq_struct floppy_tq;
      
 991  static void schedule_bh( void (*handler)(void*) )
      {
      	floppy_tq.routine = (void *)(void *) handler;
      	queue_task(&floppy_tq, &tq_immediate);
      	mark_bh(IMMEDIATE_BH);
      }
      
      static struct timer_list fd_timer;
      
1000  static void cancel_activity(void)
      {
      	CLEAR_INTR;
      	floppy_tq.routine = (void *)(void *) empty;
      	del_timer(&fd_timer);
      }
      
      /* this function makes sure that the disk stays in the drive during the
       * transfer */
1009  static void fd_watchdog(void)
      {
      #ifdef DCL_DEBUG
1012  	if (DP->flags & FD_DEBUG){
      		DPRINT("calling disk change from watchdog\n");
      	}
      #endif
      
1017  	if (disk_change(current_drive)){
      		DPRINT("disk removed during i/o\n");
      		cancel_activity();
      		cont->done(0);
      		reset_fdc();
1022  	} else {
      		del_timer(&fd_timer);
      		fd_timer.function = (timeout_fn) fd_watchdog;
      		fd_timer.expires = jiffies + HZ / 10;
      		add_timer(&fd_timer);
      	}
      }
      
1030  static void main_command_interrupt(void)
      {
      	del_timer(&fd_timer);
      	cont->interrupt();
      }
      
      /* waits for a delay (spinup or select) to pass */
1037  static int wait_for_completion(unsigned long delay, timeout_fn function)
      {
1039  	if (FDCS->reset){
      		reset_fdc(); /* do the reset during sleep to win time
      			      * if we don't need to sleep, it's a good
      			      * occasion anyways */
1043  		return 1;
      	}
      
1046  	if ((signed) (jiffies - delay) < 0){
      		del_timer(&fd_timer);
      		fd_timer.function = function;
      		fd_timer.expires = delay;
      		add_timer(&fd_timer);
1051  		return 1;
      	}
1053  	return 0;
      }
      
      static spinlock_t floppy_hlt_lock = SPIN_LOCK_UNLOCKED;
      static int hlt_disabled;
1058  static void floppy_disable_hlt(void)
      {
      	unsigned long flags;
      
1062  	spin_lock_irqsave(&floppy_hlt_lock, flags);
1063  	if (!hlt_disabled) {
      		hlt_disabled=1;
      #ifdef HAVE_DISABLE_HLT
      		disable_hlt();
      #endif
      	}
1069  	spin_unlock_irqrestore(&floppy_hlt_lock, flags);
      }
      
1072  static void floppy_enable_hlt(void)
      {
      	unsigned long flags;
      
1076  	spin_lock_irqsave(&floppy_hlt_lock, flags);
1077  	if (hlt_disabled){
      		hlt_disabled=0;
      #ifdef HAVE_DISABLE_HLT
      		enable_hlt();
      #endif
      	}
1083  	spin_unlock_irqrestore(&floppy_hlt_lock, flags);
      }
      
      
1087  static void setup_DMA(void)
      {
      	unsigned long f;
      
      #ifdef FLOPPY_SANITY_CHECK
1092  	if (raw_cmd->length == 0){
      		int i;
      
      		printk("zero dma transfer size:");
1096  		for (i=0; i < raw_cmd->cmd_count; i++)
      			printk("%x,", raw_cmd->cmd[i]);
      		printk("\n");
      		cont->done(0);
      		FDCS->reset = 1;
1101  		return;
      	}
1103  	if (((unsigned long) raw_cmd->kernel_data) % 512){
      		printk("non aligned address: %p\n", raw_cmd->kernel_data);
      		cont->done(0);
      		FDCS->reset=1;
1107  		return;
      	}
      #endif
      	f=claim_dma_lock();
      	fd_disable_dma();
      #ifdef fd_dma_setup
      	if (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length, 
      			(raw_cmd->flags & FD_RAW_READ)?
      			DMA_MODE_READ : DMA_MODE_WRITE,
1116  			FDCS->address) < 0) {
      		release_dma_lock(f);
      		cont->done(0);
      		FDCS->reset=1;
1120  		return;
      	}
      	release_dma_lock(f);
      #else	
      	fd_clear_dma_ff();
      	fd_cacheflush(raw_cmd->kernel_data, raw_cmd->length);
      	fd_set_dma_mode((raw_cmd->flags & FD_RAW_READ)?
      			DMA_MODE_READ : DMA_MODE_WRITE);
      	fd_set_dma_addr(raw_cmd->kernel_data);
      	fd_set_dma_count(raw_cmd->length);
      	virtual_dma_port = FDCS->address;
      	fd_enable_dma();
      	release_dma_lock(f);
      #endif
      	floppy_disable_hlt();
      }
      
      static void show_floppy(void);
      
      /* waits until the fdc becomes ready */
1140  static int wait_til_ready(void)
      {
      	int counter, status;
1143  	if (FDCS->reset)
1144  		return -1;
1145  	for (counter = 0; counter < 10000; counter++) {
      		status = fd_inb(FD_STATUS);		
1147  		if (status & STATUS_READY)
1148  			return status;
      	}
1150  	if (!initialising) {
      		DPRINT("Getstatus times out (%x) on fdc %d\n",
      			status, fdc);
      		show_floppy();
      	}
      	FDCS->reset = 1;
1156  	return -1;
      }
      
      /* sends a command byte to the fdc */
1160  static int output_byte(char byte)
      {
      	int status;
      
1164  	if ((status = wait_til_ready()) < 0)
1165  		return -1;
1166  	if ((status & (STATUS_READY|STATUS_DIR|STATUS_DMA)) == STATUS_READY){
      		fd_outb(byte,FD_DATA);
      #ifdef FLOPPY_SANITY_CHECK
      		output_log[output_log_pos].data = byte;
      		output_log[output_log_pos].status = status;
      		output_log[output_log_pos].jiffies = jiffies;
      		output_log_pos = (output_log_pos + 1) % OLOGSIZE;
      #endif
1174  		return 0;
      	}
      	FDCS->reset = 1;
1177  	if (!initialising) {
      		DPRINT("Unable to send byte %x to FDC. Fdc=%x Status=%x\n",
      		       byte, fdc, status);
      		show_floppy();
      	}
1182  	return -1;
      }
      #define LAST_OUT(x) if (output_byte(x)<0){ reset_fdc();return;}
      
      /* gets the response from the fdc */
1187  static int result(void)
      {
      	int i, status=0;
      
1191  	for(i=0; i < MAX_REPLIES; i++) {
1192  		if ((status = wait_til_ready()) < 0)
1193  			break;
      		status &= STATUS_DIR|STATUS_READY|STATUS_BUSY|STATUS_DMA;
1195  		if ((status & ~STATUS_BUSY) == STATUS_READY){
      #ifdef FLOPPY_SANITY_CHECK
      			resultjiffies = jiffies;
      			resultsize = i;
      #endif
1200  			return i;
      		}
1202  		if (status == (STATUS_DIR|STATUS_READY|STATUS_BUSY))
      			reply_buffer[i] = fd_inb(FD_DATA);
1204  		else
1205  			break;
      	}
1207  	if (!initialising) {
      		DPRINT("get result error. Fdc=%d Last status=%x Read bytes=%d\n",
      		       fdc, status, i);
      		show_floppy();
      	}
      	FDCS->reset = 1;
1213  	return -1;
      }
      
      #define MORE_OUTPUT -2
      /* does the fdc need more output? */
1218  static int need_more_output(void)
      {
      	int status;
1221  	if ((status = wait_til_ready()) < 0)
1222  		return -1;
1223  	if ((status & (STATUS_READY|STATUS_DIR|STATUS_DMA)) == STATUS_READY)
1224  		return MORE_OUTPUT;
1225  	return result();
      }
      
      /* Set perpendicular mode as required, based on data rate, if supported.
       * 82077 Now tested. 1Mbps data rate only possible with 82077-1.
       */
1231  static inline void perpendicular_mode(void)
      {
      	unsigned char perp_mode;
      
1235  	if (raw_cmd->rate & 0x40){
1236  		switch(raw_cmd->rate & 3){
1237  			case 0:
      				perp_mode=2;
1239  				break;
1240  			case 3:
      				perp_mode=3;
1242  				break;
1243  			default:
      				DPRINT("Invalid data rate for perpendicular mode!\n");
      				cont->done(0);
      				FDCS->reset = 1; /* convenient way to return to
      						  * redo without to much hassle (deep
      						  * stack et al. */
1249  				return;
      		}
1251  	} else
      		perp_mode = 0;
      
1254  	if (FDCS->perp_mode == perp_mode)
1255  		return;
1256  	if (FDCS->version >= FDC_82077_ORIG) {
      		output_byte(FD_PERPENDICULAR);
      		output_byte(perp_mode);
      		FDCS->perp_mode = perp_mode;
1260  	} else if (perp_mode) {
      		DPRINT("perpendicular mode not supported by this FDC.\n");
      	}
      } /* perpendicular_mode */
      
      static int fifo_depth = 0xa;
      static int no_fifo;
      
1268  static int fdc_configure(void)
      {
      	/* Turn on FIFO */
      	output_byte(FD_CONFIGURE);
1272  	if (need_more_output() != MORE_OUTPUT)
1273  		return 0;
      	output_byte(0);
      	output_byte(0x10 | (no_fifo & 0x20) | (fifo_depth & 0xf));
      	output_byte(0);	/* pre-compensation from track 
      			   0 upwards */
1278  	return 1;
      }	
      
      #define NOMINAL_DTR 500
      
      /* Issue a "SPECIFY" command to set the step rate time, head unload time,
       * head load time, and DMA disable flag to values needed by floppy.
       *
       * The value "dtr" is the data transfer rate in Kbps.  It is needed
       * to account for the data rate-based scaling done by the 82072 and 82077
       * FDC types.  This parameter is ignored for other types of FDCs (i.e.
       * 8272a).
       *
       * Note that changing the data transfer rate has a (probably deleterious)
       * effect on the parameters subject to scaling for 82072/82077 FDCs, so
       * fdc_specify is called again after each data transfer rate
       * change.
       *
       * srt: 1000 to 16000 in microseconds
       * hut: 16 to 240 milliseconds
       * hlt: 2 to 254 milliseconds
       *
       * These values are rounded up to the next highest available delay time.
       */
1302  static void fdc_specify(void)
      {
      	unsigned char spec1, spec2;
      	unsigned long srt, hlt, hut;
      	unsigned long dtr = NOMINAL_DTR;
      	unsigned long scale_dtr = NOMINAL_DTR;
      	int hlt_max_code = 0x7f;
      	int hut_max_code = 0xf;
      
1311  	if (FDCS->need_configure && FDCS->version >= FDC_82072A) {
      		fdc_configure();
      		FDCS->need_configure = 0;
      		/*DPRINT("FIFO enabled\n");*/
      	}
      
1317  	switch (raw_cmd->rate & 0x03) {
1318  		case 3:
      			dtr = 1000;
1320  			break;
1321  		case 1:
      			dtr = 300;
1323  			if (FDCS->version >= FDC_82078) {
      				/* chose the default rate table, not the one
      				 * where 1 = 2 Mbps */
      				output_byte(FD_DRIVESPEC);
1327  				if (need_more_output() == MORE_OUTPUT) {
      					output_byte(UNIT(current_drive));
      					output_byte(0xc0);
      				}
      			}
1332  			break;
1333  		case 2:
      			dtr = 250;
1335  			break;
      	}
      
1338  	if (FDCS->version >= FDC_82072) {
      		scale_dtr = dtr;
      		hlt_max_code = 0x00; /* 0==256msec*dtr0/dtr (not linear!) */
      		hut_max_code = 0x0; /* 0==256msec*dtr0/dtr (not linear!) */
      	}
      
      	/* Convert step rate from microseconds to milliseconds and 4 bits */
      	srt = 16 - (DP->srt*scale_dtr/1000 + NOMINAL_DTR - 1)/NOMINAL_DTR;
1346  	if( slow_floppy ) {
      		srt = srt / 4;
      	}
      	SUPBOUND(srt, 0xf);
      	INFBOUND(srt, 0);
      
      	hlt = (DP->hlt*scale_dtr/2 + NOMINAL_DTR - 1)/NOMINAL_DTR;
1353  	if (hlt < 0x01)
      		hlt = 0x01;
1355  	else if (hlt > 0x7f)
      		hlt = hlt_max_code;
      
      	hut = (DP->hut*scale_dtr/16 + NOMINAL_DTR - 1)/NOMINAL_DTR;
1359  	if (hut < 0x1)
      		hut = 0x1;
1361  	else if (hut > 0xf)
      		hut = hut_max_code;
      
      	spec1 = (srt << 4) | hut;
      	spec2 = (hlt << 1) | (use_virtual_dma & 1);
      
      	/* If these parameters did not change, just return with success */
1368  	if (FDCS->spec1 != spec1 || FDCS->spec2 != spec2) {
      		/* Go ahead and set spec1 and spec2 */
      		output_byte(FD_SPECIFY);
      		output_byte(FDCS->spec1 = spec1);
      		output_byte(FDCS->spec2 = spec2);
      	}
      } /* fdc_specify */
      
      /* Set the FDC's data transfer rate on behalf of the specified drive.
       * NOTE: with 82072/82077 FDCs, changing the data rate requires a reissue
       * of the specify command (i.e. using the fdc_specify function).
       */
1380  static int fdc_dtr(void)
      {
      	/* If data rate not already set to desired value, set it. */
1383  	if ((raw_cmd->rate & 3) == FDCS->dtr)
1384  		return 0;
      
      	/* Set dtr */
      	fd_outb(raw_cmd->rate & 3, FD_DCR);
      
      	/* TODO: some FDC/drive combinations (C&T 82C711 with TEAC 1.2MB)
      	 * need a stabilization period of several milliseconds to be
      	 * enforced after data rate changes before R/W operations.
      	 * Pause 5 msec to avoid trouble. (Needs to be 2 jiffies)
      	 */
      	FDCS->dtr = raw_cmd->rate & 3;
      	return(wait_for_completion(jiffies+2UL*HZ/100,
1396  				   (timeout_fn) floppy_ready));
      } /* fdc_dtr */
      
1399  static void tell_sector(void)
      {
      	printk(": track %d, head %d, sector %d, size %d",
      	       R_TRACK, R_HEAD, R_SECTOR, R_SIZECODE);
      } /* tell_sector */
      
      
      /*
       * OK, this error interpreting routine is called after a
       * DMA read/write has succeeded
       * or failed, so we check the results, and copy any buffers.
       * hhb: Added better error reporting.
       * ak: Made this into a separate routine.
       */
1413  static int interpret_errors(void)
      {
      	char bad;
      
1417  	if (inr!=7) {
      		DPRINT("-- FDC reply error");
      		FDCS->reset = 1;
1420  		return 1;
      	}
      
      	/* check IC to find cause of interrupt */
1424  	switch (ST0 & ST0_INTR) {
1425  		case 0x40:	/* error occurred during command execution */
1426  			if (ST1 & ST1_EOC)
1427  				return 0; /* occurs with pseudo-DMA */
      			bad = 1;
1429  			if (ST1 & ST1_WP) {
      				DPRINT("Drive is write protected\n");
      				CLEARF(FD_DISK_WRITABLE);
      				cont->done(0);
      				bad = 2;
1434  			} else if (ST1 & ST1_ND) {
      				SETF(FD_NEED_TWADDLE);
1436  			} else if (ST1 & ST1_OR) {
1437  				if (DP->flags & FTD_MSG)
      					DPRINT("Over/Underrun - retrying\n");
      				bad = 0;
1440  			}else if (*errors >= DP->max_errors.reporting){
      				DPRINT("");
1442  				if (ST0 & ST0_ECE) {
      					printk("Recalibrate failed!");
1444  				} else if (ST2 & ST2_CRC) {
      					printk("data CRC error");
      					tell_sector();
1447  				} else if (ST1 & ST1_CRC) {
      					printk("CRC error");
      					tell_sector();
1450  				} else if ((ST1 & (ST1_MAM|ST1_ND)) || (ST2 & ST2_MAM)) {
1451  					if (!probing) {
      						printk("sector not found");
      						tell_sector();
1454  					} else
      						printk("probe failed...");
1456  				} else if (ST2 & ST2_WC) {	/* seek error */
      					printk("wrong cylinder");
1458  				} else if (ST2 & ST2_BC) {	/* cylinder marked as bad */
      					printk("bad cylinder");
1460  				} else {
      					printk("unknown error. ST[0..2] are: 0x%x 0x%x 0x%x", ST0, ST1, ST2);
      					tell_sector();
      				}
      				printk("\n");
      
      			}
1467  			if (ST2 & ST2_WC || ST2 & ST2_BC)
      				/* wrong cylinder => recal */
      				DRS->track = NEED_2_RECAL;
1470  			return bad;
1471  		case 0x80: /* invalid command given */
      			DPRINT("Invalid FDC command given!\n");
      			cont->done(0);
1474  			return 2;
1475  		case 0xc0:
      			DPRINT("Abnormal termination caused by polling\n");
      			cont->error();
1478  			return 2;
1479  		default: /* (0) Normal command termination */
1480  			return 0;
      	}
      }
      
      /*
       * This routine is called when everything should be correctly set up
       * for the transfer (i.e. floppy motor is on, the correct floppy is
       * selected, and the head is sitting on the right track).
       */
1489  static void setup_rw_floppy(void)
      {
      	int i,r, flags,dflags;
      	unsigned long ready_date;
      	timeout_fn function;
      
      	flags = raw_cmd->flags;
1496  	if (flags & (FD_RAW_READ | FD_RAW_WRITE))
      		flags |= FD_RAW_INTR;
      
1499  	if ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)){
      		ready_date = DRS->spinup_date + DP->spinup;
      		/* If spinup will take a long time, rerun scandrives
      		 * again just before spinup completion. Beware that
      		 * after scandrives, we must again wait for selection.
      		 */
1505  		if ((signed) (ready_date - jiffies) > DP->select_delay){
      			ready_date -= DP->select_delay;
      			function = (timeout_fn) floppy_start;
1508  		} else
      			function = (timeout_fn) setup_rw_floppy;
      
      		/* wait until the floppy is spinning fast enough */
1512  		if (wait_for_completion(ready_date,function))
1513  			return;
      	}
      	dflags = DRS->flags;
      
1517  	if ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE))
      		setup_DMA();
      
1520  	if (flags & FD_RAW_INTR)
      		SET_INTR(main_command_interrupt);
      
      	r=0;
1524  	for (i=0; i< raw_cmd->cmd_count; i++)
      		r|=output_byte(raw_cmd->cmd[i]);
      
      #ifdef DEBUGT
      	debugt("rw_command: ");
      #endif
1530  	if (r){
      		cont->error();
      		reset_fdc();
1533  		return;
      	}
      
1536  	if (!(flags & FD_RAW_INTR)){
      		inr = result();
      		cont->interrupt();
1539  	} else if (flags & FD_RAW_NEED_DISK)
      		fd_watchdog();
      }
      
      static int blind_seek;
      
      /*
       * This is the routine called after every seek (or recalibrate) interrupt
       * from the floppy controller.
       */
1549  static void seek_interrupt(void)
      {
      #ifdef DEBUGT
      	debugt("seek interrupt:");
      #endif
1554  	if (inr != 2 || (ST0 & 0xF8) != 0x20) {
      		DPRINT("seek failed\n");
      		DRS->track = NEED_2_RECAL;
      		cont->error();
      		cont->redo();
1559  		return;
      	}
1561  	if (DRS->track >= 0 && DRS->track != ST1 && !blind_seek){
      #ifdef DCL_DEBUG
1563  		if (DP->flags & FD_DEBUG){
      			DPRINT("clearing NEWCHANGE flag because of effective seek\n");
      			DPRINT("jiffies=%lu\n", jiffies);
      		}
      #endif
      		CLEARF(FD_DISK_NEWCHANGE); /* effective seek */
      		DRS->select_date = jiffies;
      	}
      	DRS->track = ST1;
      	floppy_ready();
      }
      
1575  static void check_wp(void)
      {
1577  	if (TESTF(FD_VERIFY)) {
      		/* check write protection */
      		output_byte(FD_GETSTATUS);
      		output_byte(UNIT(current_drive));
1581  		if (result() != 1){
      			FDCS->reset = 1;
1583  			return;
      		}
      		CLEARF(FD_VERIFY);
      		CLEARF(FD_NEED_TWADDLE);
      #ifdef DCL_DEBUG
1588  		if (DP->flags & FD_DEBUG){
      			DPRINT("checking whether disk is write protected\n");
      			DPRINT("wp=%x\n",ST3 & 0x40);
      		}
      #endif
1593  		if (!(ST3  & 0x40))
      			SETF(FD_DISK_WRITABLE);
1595  		else
      			CLEARF(FD_DISK_WRITABLE);
      	}
      }
      
1600  static void seek_floppy(void)
      {
      	int track;
      
      	blind_seek=0;
      
      #ifdef DCL_DEBUG
1607  	if (DP->flags & FD_DEBUG){
      		DPRINT("calling disk change from seek\n");
      	}
      #endif
      
      	if (!TESTF(FD_DISK_NEWCHANGE) &&
      	    disk_change(current_drive) &&
1614  	    (raw_cmd->flags & FD_RAW_NEED_DISK)){
      		/* the media changed flag should be cleared after the seek.
      		 * If it isn't, this means that there is really no disk in
      		 * the drive.
      		 */
      		SETF(FD_DISK_CHANGED);
      		cont->done(0);
      		cont->redo();
1622  		return;
      	}
1624  	if (DRS->track <= NEED_1_RECAL){
      		recalibrate_floppy();
1626  		return;
      	} else if (TESTF(FD_DISK_NEWCHANGE) &&
      		   (raw_cmd->flags & FD_RAW_NEED_DISK) &&
1629  		   (DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) {
      		/* we seek to clear the media-changed condition. Does anybody
      		 * know a more elegant way, which works on all drives? */
1632  		if (raw_cmd->track)
      			track = raw_cmd->track - 1;
1634  		else {
1635  			if (DP->flags & FD_SILENT_DCL_CLEAR){
      				set_dor(fdc, ~(0x10 << UNIT(current_drive)), 0);
      				blind_seek = 1;
      				raw_cmd->flags |= FD_RAW_NEED_SEEK;
      			}
      			track = 1;
      		}
1642  	} else {
      		check_wp();
      		if (raw_cmd->track != DRS->track &&
1645  		    (raw_cmd->flags & FD_RAW_NEED_SEEK))
      			track = raw_cmd->track;
1647  		else {
      			setup_rw_floppy();
1649  			return;
      		}
      	}
      
      	SET_INTR(seek_interrupt);
      	output_byte(FD_SEEK);
      	output_byte(UNIT(current_drive));
1656  	LAST_OUT(track);
      #ifdef DEBUGT
      	debugt("seek command:");
      #endif
      }
      
1662  static void recal_interrupt(void)
      {
      #ifdef DEBUGT
      	debugt("recal interrupt:");
      #endif
1667  	if (inr !=2)
      		FDCS->reset = 1;
1669  	else if (ST0 & ST0_ECE) {
1670  	       	switch(DRS->track){
1671  			case NEED_1_RECAL:
      #ifdef DEBUGT
      				debugt("recal interrupt need 1 recal:");
      #endif
      				/* after a second recalibrate, we still haven't
      				 * reached track 0. Probably no drive. Raise an
      				 * error, as failing immediately might upset
      				 * computers possessed by the Devil :-) */
      				cont->error();
      				cont->redo();
1681  				return;
1682  			case NEED_2_RECAL:
      #ifdef DEBUGT
      				debugt("recal interrupt need 2 recal:");
      #endif
      				/* If we already did a recalibrate,
      				 * and we are not at track 0, this
      				 * means we have moved. (The only way
      				 * not to move at recalibration is to
      				 * be already at track 0.) Clear the
      				 * new change flag */
      #ifdef DCL_DEBUG
1693  				if (DP->flags & FD_DEBUG){
      					DPRINT("clearing NEWCHANGE flag because of second recalibrate\n");
      				}
      #endif
      
      				CLEARF(FD_DISK_NEWCHANGE);
      				DRS->select_date = jiffies;
      				/* fall through */
1701  			default:
      #ifdef DEBUGT
      				debugt("recal interrupt default:");
      #endif
      				/* Recalibrate moves the head by at
      				 * most 80 steps. If after one
      				 * recalibrate we don't have reached
      				 * track 0, this might mean that we
      				 * started beyond track 80.  Try
      				 * again.  */
      				DRS->track = NEED_1_RECAL;
1712  				break;
      		}
1714  	} else
      		DRS->track = ST1;
      	floppy_ready();
      }
      
1719  static void print_result(char *message, int inr)
      {
      	int i;
      
      	DPRINT("%s ", message);
1724  	if (inr >= 0)
1725  		for (i=0; i<inr; i++)
      			printk("repl[%d]=%x ", i, reply_buffer[i]);
      	printk("\n");
      }
      
      /* interrupt handler. Note that this can be called externally on the Sparc */
1731  void floppy_interrupt(int irq, void *dev_id, struct pt_regs * regs)
      {
      	void (*handler)(void) = DEVICE_INTR;
      	int do_print;
      	unsigned long f;
      
      	lasthandler = handler;
      	interruptjiffies = jiffies;
      
      	f=claim_dma_lock();
      	fd_disable_dma();
      	release_dma_lock(f);
      	
      	floppy_enable_hlt();
      	CLEAR_INTR;
1746  	if (fdc >= N_FDC || FDCS->address == -1){
      		/* we don't even know which FDC is the culprit */
      		printk("DOR0=%x\n", fdc_state[0].dor);
      		printk("floppy interrupt on bizarre fdc %d\n",fdc);
      		printk("handler=%p\n", handler);
      		is_alive("bizarre fdc");
1752  		return;
      	}
      
      	FDCS->reset = 0;
      	/* We have to clear the reset flag here, because apparently on boxes
      	 * with level triggered interrupts (PS/2, Sparc, ...), it is needed to
      	 * emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the
      	 * emission of the SENSEI's.
      	 * It is OK to emit floppy commands because we are in an interrupt
      	 * handler here, and thus we have to fear no interference of other
      	 * activity.
      	 */
      
      	do_print = !handler && print_unex && !initialising;
      
      	inr = result();
1768  	if (do_print)
      		print_result("unexpected interrupt", inr);
1770  	if (inr == 0){
      		int max_sensei = 4;
1772  		do {
      			output_byte(FD_SENSEI);
      			inr = result();
1775  			if (do_print)
      				print_result("sensei", inr);
      			max_sensei--;
1778  		} while ((ST0 & 0x83) != UNIT(current_drive) && inr == 2 && max_sensei);
      	}
1780  	if (handler) {
      		schedule_bh( (void *)(void *) handler);
1782  	} else
      		FDCS->reset = 1;
      	is_alive("normal interrupt end");
      }
      
1787  static void recalibrate_floppy(void)
      {
      #ifdef DEBUGT
      	debugt("recalibrate floppy:");
      #endif
      	SET_INTR(recal_interrupt);
      	output_byte(FD_RECALIBRATE);
1794  	LAST_OUT(UNIT(current_drive));
      }
      
      /*
       * Must do 4 FD_SENSEIs after reset because of ``drive polling''.
       */
1800  static void reset_interrupt(void)
      {
      #ifdef DEBUGT
      	debugt("reset interrupt:");
      #endif
      	result();		/* get the status ready for set_fdc */
1806  	if (FDCS->reset) {
      		printk("reset set in interrupt, calling %p\n", cont->error);
      		cont->error(); /* a reset just after a reset. BAD! */
      	}
      	cont->redo();
      }
      
      /*
       * reset is done by pulling bit 2 of DOR low for a while (old FDCs),
       * or by setting the self clearing bit 7 of STATUS (newer FDCs)
       */
1817  static void reset_fdc(void)
      {
      	unsigned long flags;
      	
      	SET_INTR(reset_interrupt);
      	FDCS->reset = 0;
      	reset_fdc_info(0);
      
      	/* Pseudo-DMA may intercept 'reset finished' interrupt.  */
      	/* Irrelevant for systems with true DMA (i386).          */
      	
      	flags=claim_dma_lock();
      	fd_disable_dma();
      	release_dma_lock(flags);
      
1832  	if (FDCS->version >= FDC_82072A)
      		fd_outb(0x80 | (FDCS->dtr &3), FD_STATUS);
1834  	else {
      		fd_outb(FDCS->dor & ~0x04, FD_DOR);
      		udelay(FD_RESET_DELAY);
      		fd_outb(FDCS->dor, FD_DOR);
      	}
      }
      
1841  static void show_floppy(void)
      {
      	int i;
      
      	printk("\n");
      	printk("floppy driver state\n");
      	printk("-------------------\n");
      	printk("now=%lu last interrupt=%lu diff=%lu last called handler=%p\n",
      	       jiffies, interruptjiffies, jiffies-interruptjiffies, lasthandler);
      
      
      #ifdef FLOPPY_SANITY_CHECK
      	printk("timeout_message=%s\n", timeout_message);
      	printk("last output bytes:\n");
1855  	for (i=0; i < OLOGSIZE; i++)
      		printk("%2x %2x %lu\n",
      		       output_log[(i+output_log_pos) % OLOGSIZE].data,
      		       output_log[(i+output_log_pos) % OLOGSIZE].status,
      		       output_log[(i+output_log_pos) % OLOGSIZE].jiffies);
      	printk("last result at %lu\n", resultjiffies);
      	printk("last redo_fd_request at %lu\n", lastredo);
1862  	for (i=0; i<resultsize; i++){
      		printk("%2x ", reply_buffer[i]);
      	}
      	printk("\n");
      #endif
      
      	printk("status=%x\n", fd_inb(FD_STATUS));
      	printk("fdc_busy=%lu\n", fdc_busy);
1870  	if (DEVICE_INTR)
      		printk("DEVICE_INTR=%p\n", DEVICE_INTR);
1872  	if (floppy_tq.sync)
      		printk("floppy_tq.routine=%p\n", floppy_tq.routine);
1874  	if (timer_pending(&fd_timer))
      		printk("fd_timer.function=%p\n", fd_timer.function);
1876  	if (timer_pending(&fd_timeout)){
      		printk("timer_function=%p\n",fd_timeout.function);
      		printk("expires=%lu\n",fd_timeout.expires-jiffies);
      		printk("now=%lu\n",jiffies);
      	}
      	printk("cont=%p\n", cont);
      	printk("CURRENT=%p\n", CURRENT);
      	printk("command_status=%d\n", command_status);
      	printk("\n");
      }
      
1887  static void floppy_shutdown(void)
      {
      	unsigned long flags;
      	
1891  	if (!initialising)
      		show_floppy();
      	cancel_activity();
      
      	floppy_enable_hlt();
      	
      	flags=claim_dma_lock();
      	fd_disable_dma();
      	release_dma_lock(flags);
      	
      	/* avoid dma going to a random drive after shutdown */
      
1903  	if (!initialising)
      		DPRINT("floppy timeout called\n");
      	FDCS->reset = 1;
1906  	if (cont){
      		cont->done(0);
      		cont->redo(); /* this will recall reset when needed */
1909  	} else {
      		printk("no cont in shutdown!\n");
      		process_fd_request();
      	}
      	is_alive("floppy shutdown");
      }
      /*typedef void (*timeout_fn)(unsigned long);*/
      
      /* start motor, check media-changed condition and write protection */
1918  static int start_motor(void (*function)(void) )
      {
      	int mask, data;
      
      	mask = 0xfc;
      	data = UNIT(current_drive);
1924  	if (!(raw_cmd->flags & FD_RAW_NO_MOTOR)){
1925  		if (!(FDCS->dor & (0x10 << UNIT(current_drive)))){
      			set_debugt();
      			/* no read since this drive is running */
      			DRS->first_read_date = 0;
      			/* note motor start time if motor is not yet running */
      			DRS->spinup_date = jiffies;
      			data |= (0x10 << UNIT(current_drive));
      		}
      	} else
1934  		if (FDCS->dor & (0x10 << UNIT(current_drive)))
      			mask &= ~(0x10 << UNIT(current_drive));
      
      	/* starts motor and selects floppy */
      	del_timer(motor_off_timer + current_drive);
      	set_dor(fdc, mask, data);
      
      	/* wait_for_completion also schedules reset if needed. */
      	return(wait_for_completion(DRS->select_date+DP->select_delay,
1943  				   (timeout_fn) function));
      }
      
1946  static void floppy_ready(void)
      {
1948  	CHECK_RESET;
1949  	if (start_motor(floppy_ready)) return;
1950  	if (fdc_dtr()) return;
      
      #ifdef DCL_DEBUG
1953  	if (DP->flags & FD_DEBUG){
      		DPRINT("calling disk change from floppy_ready\n");
      	}
      #endif
      	if (!(raw_cmd->flags & FD_RAW_NO_MOTOR) &&
      	   disk_change(current_drive) &&
1959  	   !DP->select_delay)
      		twaddle(); /* this clears the dcl on certain drive/controller
      			    * combinations */
      
      #ifdef fd_chose_dma_mode
      	if ((raw_cmd->flags & FD_RAW_READ) || 
1965  	    (raw_cmd->flags & FD_RAW_WRITE))
      	{
      		unsigned long flags = claim_dma_lock();
      		fd_chose_dma_mode(raw_cmd->kernel_data,
      				  raw_cmd->length);
      		release_dma_lock(flags);
      	}
      #endif
      
1974  	if (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)){
      		perpendicular_mode();
      		fdc_specify(); /* must be done here because of hut, hlt ... */
      		seek_floppy();
1978  	} else {
      		if ((raw_cmd->flags & FD_RAW_READ) || 
1980  		    (raw_cmd->flags & FD_RAW_WRITE))
      			fdc_specify();
      		setup_rw_floppy();
      	}
      }
      
1986  static void floppy_start(void)
      {
      	reschedule_timeout(CURRENTD, "floppy start", 0);
      
      	scandrives();
      #ifdef DCL_DEBUG
1992  	if (DP->flags & FD_DEBUG){
      		DPRINT("setting NEWCHANGE in floppy_start\n");
      	}
      #endif
      	SETF(FD_DISK_NEWCHANGE);
      	floppy_ready();
      }
      
      /*
       * ========================================================================
       * here ends the bottom half. Exported routines are:
       * floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc,
       * start_motor, reset_fdc, reset_fdc_info, interpret_errors.
       * Initialization also uses output_byte, result, set_dor, floppy_interrupt
       * and set_dor.
       * ========================================================================
       */
      /*
       * General purpose continuations.
       * ==============================
       */
      
2014  static void do_wakeup(void)
      {
      	reschedule_timeout(MAXTIMEOUT, "do wakeup", 0);
      	cont = 0;
      	command_status += 2;
      	wake_up(&command_done);
      }
      
      static struct cont_t wakeup_cont={
      	empty,
      	do_wakeup,
      	empty,
      	(done_f)empty
      };
      
      
      static struct cont_t intr_cont={
      	empty,
      	process_fd_request,
      	empty,
      	(done_f) empty
      };
      
2037  static int wait_til_done(void (*handler)(void), int interruptible)
      {
      	int ret;
      
      	schedule_bh((void *)(void *)handler);
      
2043  	if (command_status < 2 && NO_SIGNAL) {
      		DECLARE_WAITQUEUE(wait, current);
      
      		add_wait_queue(&command_done, &wait);
2047  		for (;;) {
2048  			set_current_state(interruptible?
      					  TASK_INTERRUPTIBLE:
2050  					  TASK_UNINTERRUPTIBLE);
      
2052  			if (command_status >= 2 || !NO_SIGNAL)
2053  				break;
      
      			is_alive("wait_til_done");
      
      			schedule();
      		}
      
2060  		set_current_state(TASK_RUNNING);
      		remove_wait_queue(&command_done, &wait);
      	}
      
2064  	if (command_status < 2){
      		cancel_activity();
      		cont = &intr_cont;
      		reset_fdc();
2068  		return -EINTR;
      	}
      
2071  	if (FDCS->reset)
      		command_status = FD_COMMAND_ERROR;
2073  	if (command_status == FD_COMMAND_OKAY)
      		ret=0;
2075  	else
      		ret=-EIO;
      	command_status = FD_COMMAND_NONE;
2078  	return ret;
      }
      
2081  static void generic_done(int result)
      {
      	command_status = result;
      	cont = &wakeup_cont;
      }
      
2087  static void generic_success(void)
      {
      	cont->done(1);
      }
      
2092  static void generic_failure(void)
      {
      	cont->done(0);
      }
      
2097  static void success_and_wakeup(void)
      {
      	generic_success();
      	cont->redo();
      }
      
      
      /*
       * formatting and rw support.
       * ==========================
       */
      
2109  static int next_valid_format(void)
      {
      	int probed_format;
      
      	probed_format = DRS->probed_format;
2114  	while(1){
      		if (probed_format >= 8 ||
2116  		     !DP->autodetect[probed_format]){
      			DRS->probed_format = 0;
2118  			return 1;
      		}
2120  		if (floppy_type[DP->autodetect[probed_format]].sect){
      			DRS->probed_format = probed_format;
2122  			return 0;
      		}
      		probed_format++;
      	}
      }
      
2128  static void bad_flp_intr(void)
      {
2130  	if (probing){
      		DRS->probed_format++;
2132  		if (!next_valid_format())
2133  			return;
      	}
      	(*errors)++;
      	INFBOUND(DRWE->badness, *errors);
2137  	if (*errors > DP->max_errors.abort)
      		cont->done(0);
2139  	if (*errors > DP->max_errors.reset)
      		FDCS->reset = 1;
2141  	else if (*errors > DP->max_errors.recal)
      		DRS->track = NEED_2_RECAL;
      }
      
2145  static void set_floppy(kdev_t device)
      {
2147  	if (TYPE(device))
      		_floppy = TYPE(device) + floppy_type;
2149  	else
      		_floppy = current_type[ DRIVE(device) ];
      }
      
      /*
       * formatting support.
       * ===================
       */
2157  static void format_interrupt(void)
      {
2159  	switch (interpret_errors()){
2160  		case 1:
      			cont->error();
2162  		case 2:
2163  			break;
2164  		case 0:
      			cont->done(1);
      	}
      	cont->redo();
      }
      
      #define CODE2SIZE (ssize = ((1 << SIZECODE) + 3) >> 2)
      #define FM_MODE(x,y) ((y) & ~(((x)->rate & 0x80) >>1))
      #define CT(x) ((x) | 0xc0)
2173  static void setup_format_params(int track)
      {
      	struct fparm {
      		unsigned char track,head,sect,size;
      	} *here = (struct fparm *)floppy_track_buffer;
      	int il,n;
      	int count,head_shift,track_shift;
      
      	raw_cmd = &default_raw_cmd;
      	raw_cmd->track = track;
      
      	raw_cmd->flags = FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN |
      		FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK;
      	raw_cmd->rate = _floppy->rate & 0x43;
      	raw_cmd->cmd_count = NR_F;
      	COMMAND = FM_MODE(_floppy,FD_FORMAT);
      	DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy,format_req.head);
      	F_SIZECODE = FD_SIZECODE(_floppy);
      	F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE;
      	F_GAP = _floppy->fmt_gap;
      	F_FILL = FD_FILL_BYTE;
      
      	raw_cmd->kernel_data = floppy_track_buffer;
      	raw_cmd->length = 4 * F_SECT_PER_TRACK;
      
      	/* allow for about 30ms for data transport per track */
      	head_shift  = (F_SECT_PER_TRACK + 5) / 6;
      
      	/* a ``cylinder'' is two tracks plus a little stepping time */
      	track_shift = 2 * head_shift + 3;
      
      	/* position of logical sector 1 on this track */
      	n = (track_shift * format_req.track + head_shift * format_req.head)
      		% F_SECT_PER_TRACK;
      
      	/* determine interleave */
      	il = 1;
2210  	if (_floppy->fmt_gap < 0x22)
      		il++;
      
      	/* initialize field */
2214  	for (count = 0; count < F_SECT_PER_TRACK; ++count) {
      		here[count].track = format_req.track;
      		here[count].head = format_req.head;
      		here[count].sect = 0;
      		here[count].size = F_SIZECODE;
      	}
      	/* place logical sectors */
2221  	for (count = 1; count <= F_SECT_PER_TRACK; ++count) {
      		here[n].sect = count;
      		n = (n+il) % F_SECT_PER_TRACK;
2224  		if (here[n].sect) { /* sector busy, find next free sector */
      			++n;
2226  			if (n>= F_SECT_PER_TRACK) {
      				n-=F_SECT_PER_TRACK;
2228  				while (here[n].sect) ++n;
      			}
      		}
      	}
      }
      
2234  static void redo_format(void)
      {
      	buffer_track = -1;
      	setup_format_params(format_req.track << STRETCH(_floppy));
      	floppy_start();
      #ifdef DEBUGT
      	debugt("queue format request");
      #endif
      }
      
      static struct cont_t format_cont={
      	format_interrupt,
      	redo_format,
      	bad_flp_intr,
      	generic_done };
      
2250  static int do_format(kdev_t device, struct format_descr *tmp_format_req)
      {
      	int ret;
      	int drive=DRIVE(device);
      
2255  	LOCK_FDC(drive,1);
      	set_floppy(device);
      	if (!_floppy ||
      	    _floppy->track > DP->tracks ||
      	    tmp_format_req->track >= _floppy->track ||
      	    tmp_format_req->head >= _floppy->head ||
      	    (_floppy->sect << 2) % (1 <<  FD_SIZECODE(_floppy)) ||
2262  	    !_floppy->fmt_gap) {
      		process_fd_request();
2264  		return -EINVAL;
      	}
      	format_req = *tmp_format_req;
      	format_errors = 0;
      	cont = &format_cont;
      	errors = &format_errors;
2270  	IWAIT(redo_format);
      	process_fd_request();
2272  	return ret;
      }
      
      /*
       * Buffer read/write and support
       * =============================
       */
      
      /* new request_done. Can handle physical sectors which are smaller than a
       * logical buffer */
2282  static void request_done(int uptodate)
      {
      	int block;
      	unsigned long flags;
      
      	probing = 0;
      	reschedule_timeout(MAXTIMEOUT, "request done %d", uptodate);
      
2290  	if (QUEUE_EMPTY){
      		DPRINT("request list destroyed in floppy request done\n");
2292  		return;
      	}
      
2295  	if (uptodate){
      		/* maintain values for invalidation on geometry
      		 * change */
      		block = current_count_sectors + CURRENT->sector;
      		INFBOUND(DRS->maxblock, block);
2300  		if (block > _floppy->sect)
      			DRS->maxtrack = 1;
      
      		/* unlock chained buffers */
2304  		spin_lock_irqsave(&io_request_lock, flags);
      		while (current_count_sectors && !QUEUE_EMPTY &&
2306  		       current_count_sectors >= CURRENT->current_nr_sectors){
      			current_count_sectors -= CURRENT->current_nr_sectors;
      			CURRENT->nr_sectors -= CURRENT->current_nr_sectors;
      			CURRENT->sector += CURRENT->current_nr_sectors;
      			end_request(1);
      		}
2312  		spin_unlock_irqrestore(&io_request_lock, flags);
      
2314  		if (current_count_sectors && !QUEUE_EMPTY){
      			/* "unlock" last subsector */
      			CURRENT->buffer += current_count_sectors <<9;
      			CURRENT->current_nr_sectors -= current_count_sectors;
      			CURRENT->nr_sectors -= current_count_sectors;
      			CURRENT->sector += current_count_sectors;
2320  			return;
      		}
      
2323  		if (current_count_sectors && QUEUE_EMPTY)
      			DPRINT("request list destroyed in floppy request done\n");
      
2326  	} else {
2327  		if (CURRENT->cmd == WRITE) {
      			/* record write error information */
      			DRWE->write_errors++;
2330  			if (DRWE->write_errors == 1) {
      				DRWE->first_error_sector = CURRENT->sector;
      				DRWE->first_error_generation = DRS->generation;
      			}
      			DRWE->last_error_sector = CURRENT->sector;
      			DRWE->last_error_generation = DRS->generation;
      		}
2337  		spin_lock_irqsave(&io_request_lock, flags);
      		end_request(0);
2339  		spin_unlock_irqrestore(&io_request_lock, flags);
      	}
      }
      
      /* Interrupt handler evaluating the result of the r/w operation */
2344  static void rw_interrupt(void)
      {
      	int nr_sectors, ssize, eoc, heads;
      
2348  	if (R_HEAD >= 2) {
      	    /* some Toshiba floppy controllers occasionnally seem to
      	     * return bogus interrupts after read/write operations, which
      	     * can be recognized by a bad head number (>= 2) */
2352  	     return;
      	}  
      
2355  	if (!DRS->first_read_date)
      		DRS->first_read_date = jiffies;
      
      	nr_sectors = 0;
      	CODE2SIZE;
      
2361  	if (ST1 & ST1_EOC)
      		eoc = 1;
2363  	else
      		eoc = 0;
      
2366  	if (COMMAND & 0x80)
      		heads = 2;
2368  	else
      		heads = 1;
      
      	nr_sectors = (((R_TRACK-TRACK) * heads +
      				   R_HEAD-HEAD) * SECT_PER_TRACK +
      				   R_SECTOR-SECTOR + eoc) << SIZECODE >> 2;
      
      #ifdef FLOPPY_SANITY_CHECK
      	if (nr_sectors / ssize > 
2377  		(in_sector_offset + current_count_sectors + ssize - 1) / ssize) {
      		DPRINT("long rw: %x instead of %lx\n",
      			nr_sectors, current_count_sectors);
      		printk("rs=%d s=%d\n", R_SECTOR, SECTOR);
      		printk("rh=%d h=%d\n", R_HEAD, HEAD);
      		printk("rt=%d t=%d\n", R_TRACK, TRACK);
      		printk("heads=%d eoc=%d\n", heads, eoc);
      		printk("spt=%d st=%d ss=%d\n", SECT_PER_TRACK,
      		       sector_t, ssize);
      		printk("in_sector_offset=%d\n", in_sector_offset);
      	}
      #endif
      
      	nr_sectors -= in_sector_offset;
      	INFBOUND(nr_sectors,0);
      	SUPBOUND(current_count_sectors, nr_sectors);
      
2394  	switch (interpret_errors()){
2395  		case 2:
      			cont->redo();
2397  			return;
2398  		case 1:
2399  			if (!current_count_sectors){
      				cont->error();
      				cont->redo();
2402  				return;
      			}
2404  			break;
2405  		case 0:
2406  			if (!current_count_sectors){
      				cont->redo();
2408  				return;
      			}
      			current_type[current_drive] = _floppy;
      			floppy_sizes[TOMINOR(current_drive) ]= 
      				(_floppy->size+1)>>1;
2413  			break;
      	}
      
2416  	if (probing) {
2417  		if (DP->flags & FTD_MSG)
      			DPRINT("Auto-detected floppy type %s in fd%d\n",
      				_floppy->name,current_drive);
      		current_type[current_drive] = _floppy;
      		floppy_sizes[TOMINOR(current_drive)] = (_floppy->size+1) >> 1;
      		probing = 0;
      	}
      
      	if (CT(COMMAND) != FD_READ || 
2426  	     raw_cmd->kernel_data == CURRENT->buffer){
      		/* transfer directly from buffer */
      		cont->done(1);
2429  	} else if (CT(COMMAND) == FD_READ){
      		buffer_track = raw_cmd->track;
      		buffer_drive = current_drive;
      		INFBOUND(buffer_max, nr_sectors + sector_t);
      	}
      	cont->redo();
      }
      
      /* Compute maximal contiguous buffer size. */
2438  static int buffer_chain_size(void)
      {
      	struct buffer_head *bh;
      	int size;
      	char *base;
      
      	base = CURRENT->buffer;
      	size = CURRENT->current_nr_sectors << 9;
      	bh = CURRENT->bh;
      
2448  	if (bh){
      		bh = bh->b_reqnext;
2450  		while (bh && bh->b_data == base + size){
      			size += bh->b_size;
      			bh = bh->b_reqnext;
      		}
      	}
2455  	return size >> 9;
      }
      
      /* Compute the maximal transfer size */
2459  static int transfer_size(int ssize, int max_sector, int max_size)
      {
      	SUPBOUND(max_sector, sector_t + max_size);
      
      	/* alignment */
      	max_sector -= (max_sector % _floppy->sect) % ssize;
      
      	/* transfer size, beginning not aligned */
      	current_count_sectors = max_sector - sector_t ;
      
2469  	return max_sector;
      }
      
      /*
       * Move data from/to the track buffer to/from the buffer cache.
       */
2475  static void copy_buffer(int ssize, int max_sector, int max_sector_2)
      {
      	int remaining; /* number of transferred 512-byte sectors */
      	struct buffer_head *bh;
      	char *buffer, *dma_buffer;
      	int size;
      
      	max_sector = transfer_size(ssize,
      				   minimum(max_sector, max_sector_2),
      				   CURRENT->nr_sectors);
      
      	if (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE &&
2487  	    buffer_max > sector_t + CURRENT->nr_sectors)
      		current_count_sectors = minimum(buffer_max - sector_t,
      						CURRENT->nr_sectors);
      
      	remaining = current_count_sectors << 9;
      #ifdef FLOPPY_SANITY_CHECK
      	if ((remaining >> 9) > CURRENT->nr_sectors  &&
2494  	    CT(COMMAND) == FD_WRITE){
      		DPRINT("in copy buffer\n");
      		printk("current_count_sectors=%ld\n", current_count_sectors);
      		printk("remaining=%d\n", remaining >> 9);
      		printk("CURRENT->nr_sectors=%ld\n",CURRENT->nr_sectors);
      		printk("CURRENT->current_nr_sectors=%ld\n",
      		       CURRENT->current_nr_sectors);
      		printk("max_sector=%d\n", max_sector);
      		printk("ssize=%d\n", ssize);
      	}
      #endif
      
      	buffer_max = maximum(max_sector, buffer_max);
      
      	dma_buffer = floppy_track_buffer + ((sector_t - buffer_min) << 9);
      
      	bh = CURRENT->bh;
      	size = CURRENT->current_nr_sectors << 9;
      	buffer = CURRENT->buffer;
      
2514  	while (remaining > 0){
      		SUPBOUND(size, remaining);
      #ifdef FLOPPY_SANITY_CHECK
      		if (dma_buffer + size >
      		    floppy_track_buffer + (max_buffer_sectors << 10) ||
2519  		    dma_buffer < floppy_track_buffer){
      			DPRINT("buffer overrun in copy buffer %d\n",
      				(int) ((floppy_track_buffer - dma_buffer) >>9));
      			printk("sector_t=%d buffer_min=%d\n",
      			       sector_t, buffer_min);
      			printk("current_count_sectors=%ld\n",
      			       current_count_sectors);
2526  			if (CT(COMMAND) == FD_READ)
      				printk("read\n");
2528  			if (CT(COMMAND) == FD_READ)
      				printk("write\n");
2530  			break;
      		}
2532  		if (((unsigned long)buffer) % 512)
      			DPRINT("%p buffer not aligned\n", buffer);
      #endif
2535  		if (CT(COMMAND) == FD_READ)
      			memcpy(buffer, dma_buffer, size);
2537  		else
      			memcpy(dma_buffer, buffer, size);
      		remaining -= size;
2540  		if (!remaining)
2541  			break;
      
      		dma_buffer += size;
      		bh = bh->b_reqnext;
      #ifdef FLOPPY_SANITY_CHECK
2546  		if (!bh){
      			DPRINT("bh=null in copy buffer after copy\n");
2548  			break;
      		}
      #endif
      		size = bh->b_size;
      		buffer = bh->b_data;
      	}
      #ifdef FLOPPY_SANITY_CHECK
2555  	if (remaining){
2556  		if (remaining > 0)
      			max_sector -= remaining >> 9;
      		DPRINT("weirdness: remaining %d\n", remaining>>9);
      	}
      #endif
      }
      
      #if 0
      static inline int check_dma_crossing(char *start, 
      				     unsigned long length, char *message)
      {
      	if (CROSS_64KB(start, length)) {
      		printk("DMA xfer crosses 64KB boundary in %s %p-%p\n", 
      		       message, start, start+length);
      		return 1;
      	} else
      		return 0;
      }
      #endif
      
      /* work around a bug in pseudo DMA
       * (on some FDCs) pseudo DMA does not stop when the CPU stops
       * sending data.  Hence we need a different way to signal the
       * transfer length:  We use SECT_PER_TRACK.  Unfortunately, this
       * does not work with MT, hence we can only transfer one head at
       * a time
       */
2583  static void virtualdmabug_workaround(void)
      {
      	int hard_sectors, end_sector;
      
2587  	if(CT(COMMAND) == FD_WRITE) {
      		COMMAND &= ~0x80; /* switch off multiple track mode */
      
      		hard_sectors = raw_cmd->length >> (7 + SIZECODE);
      		end_sector = SECTOR + hard_sectors - 1;
      #ifdef FLOPPY_SANITY_CHECK
2593  		if(end_sector > SECT_PER_TRACK) {
      			printk("too many sectors %d > %d\n",
      			       end_sector, SECT_PER_TRACK);
2596  			return;
      		}
      #endif
      		SECT_PER_TRACK = end_sector; /* make sure SECT_PER_TRACK points
      					      * to end of transfer */
      	}
      }
      
      /*
       * Formulate a read/write request.
       * this routine decides where to load the data (directly to buffer, or to
       * tmp floppy area), how much data to load (the size of the buffer, the whole
       * track, or a single sector)
       * All floppy_track_buffer handling goes in here. If we ever add track buffer
       * allocation on the fly, it should be done here. No other part should need
       * modification.
       */
      
2614  static int make_raw_rw_request(void)
      {
      	int aligned_sector_t;
      	int max_sector, max_size, tracksize, ssize;
      
2619  	if(max_buffer_sectors == 0) {
      		printk("VFS: Block I/O scheduled on unopened device\n");
2621  		return 0;
      	}
      
      	set_fdc(DRIVE(CURRENT->rq_dev));
      
      	raw_cmd = &default_raw_cmd;
      	raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_DISK |
      		FD_RAW_NEED_SEEK;
      	raw_cmd->cmd_count = NR_RW;
2630  	if (CURRENT->cmd == READ){
      		raw_cmd->flags |= FD_RAW_READ;
      		COMMAND = FM_MODE(_floppy,FD_READ);
2633  	} else if (CURRENT->cmd == WRITE){
      		raw_cmd->flags |= FD_RAW_WRITE;
      		COMMAND = FM_MODE(_floppy,FD_WRITE);
2636  	} else {
      		DPRINT("make_raw_rw_request: unknown command\n");
2638  		return 0;
      	}
      
      	max_sector = _floppy->sect * _floppy->head;
      
      	TRACK = CURRENT->sector / max_sector;
      	sector_t = CURRENT->sector % max_sector;
2645  	if (_floppy->track && TRACK >= _floppy->track) {
2646  		if (CURRENT->current_nr_sectors & 1) {
      			current_count_sectors = 1;
2648  			return 1;
2649  		} else
2650  			return 0;
      	}
      	HEAD = sector_t / _floppy->sect;
      
      	if (((_floppy->stretch & FD_SWAPSIDES) || TESTF(FD_NEED_TWADDLE)) &&
2655  	    sector_t < _floppy->sect)
      		max_sector = _floppy->sect;
      
      	/* 2M disks have phantom sectors on the first track */
2659  	if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)){
      		max_sector = 2 * _floppy->sect / 3;
2661  		if (sector_t >= max_sector){
      			current_count_sectors = minimum(_floppy->sect - sector_t,
      							CURRENT->nr_sectors);
2664  			return 1;
      		}
      		SIZECODE = 2;
2667  	} else
      		SIZECODE = FD_SIZECODE(_floppy);
      	raw_cmd->rate = _floppy->rate & 0x43;
      	if ((_floppy->rate & FD_2M) &&
      	    (TRACK || HEAD) &&
2672  	    raw_cmd->rate == 2)
      		raw_cmd->rate = 1;
      
2675  	if (SIZECODE)
      		SIZECODE2 = 0xff;
2677  	else
      		SIZECODE2 = 0x80;
      	raw_cmd->track = TRACK << STRETCH(_floppy);
      	DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy,HEAD);
      	GAP = _floppy->gap;
      	CODE2SIZE;
      	SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE;
      	SECTOR = ((sector_t % _floppy->sect) << 2 >> SIZECODE) + 1;
      
      	/* tracksize describes the size which can be filled up with sectors
      	 * of size ssize.
      	 */
      	tracksize = _floppy->sect - _floppy->sect % ssize;
2690  	if (tracksize < _floppy->sect){
      		SECT_PER_TRACK ++;
2692  		if (tracksize <= sector_t % _floppy->sect)
      			SECTOR--;
      
      		/* if we are beyond tracksize, fill up using smaller sectors */
2696  		while (tracksize <= sector_t % _floppy->sect){
2697  			while(tracksize + ssize > _floppy->sect){
      				SIZECODE--;
      				ssize >>= 1;
      			}
      			SECTOR++; SECT_PER_TRACK ++;
      			tracksize += ssize;
      		}
      		max_sector = HEAD * _floppy->sect + tracksize;
2705  	} else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) {
      		max_sector = _floppy->sect;
2707  	} else if (!HEAD && CT(COMMAND) == FD_WRITE) {
      		/* for virtual DMA bug workaround */
      		max_sector = _floppy->sect;
      	}
      
      	in_sector_offset = (sector_t % _floppy->sect) % ssize;
      	aligned_sector_t = sector_t - in_sector_offset;
      	max_size = CURRENT->nr_sectors;
      	if ((raw_cmd->track == buffer_track) && 
      	    (current_drive == buffer_drive) &&
2717  	    (sector_t >= buffer_min) && (sector_t < buffer_max)) {
      		/* data already in track buffer */
2719  		if (CT(COMMAND) == FD_READ) {
      			copy_buffer(1, max_sector, buffer_max);
2721  			return 1;
      		}
2723  	} else if (in_sector_offset || CURRENT->nr_sectors < ssize){
2724  		if (CT(COMMAND) == FD_WRITE){
      			if (sector_t + CURRENT->nr_sectors > ssize &&
2726  			    sector_t + CURRENT->nr_sectors < ssize + ssize)
      				max_size = ssize + ssize;
2728  			else
      				max_size = ssize;
      		}
      		raw_cmd->flags &= ~FD_RAW_WRITE;
      		raw_cmd->flags |= FD_RAW_READ;
      		COMMAND = FM_MODE(_floppy,FD_READ);
2734  	} else if ((unsigned long)CURRENT->buffer < MAX_DMA_ADDRESS) {
      		unsigned long dma_limit;
      		int direct, indirect;
      
      		indirect= transfer_size(ssize,max_sector,max_buffer_sectors*2) -
      			sector_t;
      
      		/*
      		 * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide
      		 * on a 64 bit machine!
      		 */
      		max_size = buffer_chain_size();
      		dma_limit = (MAX_DMA_ADDRESS - ((unsigned long) CURRENT->buffer)) >> 9;
2747  		if ((unsigned long) max_size > dma_limit) {
      			max_size = dma_limit;
      		}
      		/* 64 kb boundaries */
2751  		if (CROSS_64KB(CURRENT->buffer, max_size << 9))
      			max_size = (K_64 - 
      				    ((unsigned long)CURRENT->buffer) % K_64)>>9;
      		direct = transfer_size(ssize,max_sector,max_size) - sector_t;
      		/*
      		 * We try to read tracks, but if we get too many errors, we
      		 * go back to reading just one sector at a time.
      		 *
      		 * This means we should be able to read a sector even if there
      		 * are other bad sectors on this track.
      		 */
      		if (!direct ||
      		    (indirect * 2 > direct * 3 &&
      		     *errors < DP->max_errors.read_track &&
      		     /*!TESTF(FD_NEED_TWADDLE) &&*/
2766  		     ((!probing || (DP->read_track&(1<<DRS->probed_format)))))){
      			max_size = CURRENT->nr_sectors;
2768  		} else {
      			raw_cmd->kernel_data = CURRENT->buffer;
      			raw_cmd->length = current_count_sectors << 9;
2771  			if (raw_cmd->length == 0){
      				DPRINT("zero dma transfer attempted from make_raw_request\n");
      				DPRINT("indirect=%d direct=%d sector_t=%d",
      					indirect, direct, sector_t);
2775  				return 0;
      			}
      /*			check_dma_crossing(raw_cmd->kernel_data, 
      					   raw_cmd->length, 
      					   "end of make_raw_request [1]");*/
      
      			virtualdmabug_workaround();
2782  			return 2;
      		}
      	}
      
2786  	if (CT(COMMAND) == FD_READ)
      		max_size = max_sector; /* unbounded */
      
      	/* claim buffer track if needed */
      	if (buffer_track != raw_cmd->track ||  /* bad track */
      	    buffer_drive !=current_drive || /* bad drive */
      	    sector_t > buffer_max ||
      	    sector_t < buffer_min ||
      	    ((CT(COMMAND) == FD_READ ||
      	      (!in_sector_offset && CURRENT->nr_sectors >= ssize))&&
      	     max_sector > 2 * max_buffer_sectors + buffer_min &&
2797  	     max_size + sector_t > 2 * max_buffer_sectors + buffer_min)
2798  	    /* not enough space */){
      		buffer_track = -1;
      		buffer_drive = current_drive;
      		buffer_max = buffer_min = aligned_sector_t;
      	}
      	raw_cmd->kernel_data = floppy_track_buffer + 
      		((aligned_sector_t-buffer_min)<<9);
      
2806  	if (CT(COMMAND) == FD_WRITE){
      		/* copy write buffer to track buffer.
      		 * if we get here, we know that the write
      		 * is either aligned or the data already in the buffer
      		 * (buffer will be overwritten) */
      #ifdef FLOPPY_SANITY_CHECK
2812  		if (in_sector_offset && buffer_track == -1)
      			DPRINT("internal error offset !=0 on write\n");
      #endif
      		buffer_track = raw_cmd->track;
      		buffer_drive = current_drive;
      		copy_buffer(ssize, max_sector, 2*max_buffer_sectors+buffer_min);
2818  	} else
      		transfer_size(ssize, max_sector,
      			      2*max_buffer_sectors+buffer_min-aligned_sector_t);
      
      	/* round up current_count_sectors to get dma xfer size */
      	raw_cmd->length = in_sector_offset+current_count_sectors;
      	raw_cmd->length = ((raw_cmd->length -1)|(ssize-1))+1;
      	raw_cmd->length <<= 9;
      #ifdef FLOPPY_SANITY_CHECK
      	/*check_dma_crossing(raw_cmd->kernel_data, raw_cmd->length, 
      	  "end of make_raw_request");*/
      	if ((raw_cmd->length < current_count_sectors << 9) ||
      	    (raw_cmd->kernel_data != CURRENT->buffer &&
      	     CT(COMMAND) == FD_WRITE &&
      	     (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max ||
      	      aligned_sector_t < buffer_min)) ||
      	    raw_cmd->length % (128 << SIZECODE) ||
2835  	    raw_cmd->length <= 0 || current_count_sectors <= 0){
      		DPRINT("fractionary current count b=%lx s=%lx\n",
      			raw_cmd->length, current_count_sectors);
2838  		if (raw_cmd->kernel_data != CURRENT->buffer)
      			printk("addr=%d, length=%ld\n",
      			       (int) ((raw_cmd->kernel_data - 
      				       floppy_track_buffer) >> 9),
      			       current_count_sectors);
      		printk("st=%d ast=%d mse=%d msi=%d\n",
      		       sector_t, aligned_sector_t, max_sector, max_size);
      		printk("ssize=%x SIZECODE=%d\n", ssize, SIZECODE);
      		printk("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n",
      		       COMMAND, SECTOR, HEAD, TRACK);
      		printk("buffer drive=%d\n", buffer_drive);
      		printk("buffer track=%d\n", buffer_track);
      		printk("buffer_min=%d\n", buffer_min);
      		printk("buffer_max=%d\n", buffer_max);
2852  		return 0;
      	}
      
2855  	if (raw_cmd->kernel_data != CURRENT->buffer){
      		if (raw_cmd->kernel_data < floppy_track_buffer ||
      		    current_count_sectors < 0 ||
      		    raw_cmd->length < 0 ||
      		    raw_cmd->kernel_data + raw_cmd->length >
2860  		    floppy_track_buffer + (max_buffer_sectors  << 10)){
      			DPRINT("buffer overrun in schedule dma\n");
      			printk("sector_t=%d buffer_min=%d current_count=%ld\n",
      			       sector_t, buffer_min,
      			       raw_cmd->length >> 9);
      			printk("current_count_sectors=%ld\n",
      			       current_count_sectors);
2867  			if (CT(COMMAND) == FD_READ)
      				printk("read\n");
2869  			if (CT(COMMAND) == FD_READ)
      				printk("write\n");
2871  			return 0;
      		}
      	} else if (raw_cmd->length > CURRENT->nr_sectors << 9 ||
2874  		   current_count_sectors > CURRENT->nr_sectors){
      		DPRINT("buffer overrun in direct transfer\n");
2876  		return 0;
2877  	} else if (raw_cmd->length < current_count_sectors << 9){
      		DPRINT("more sectors than bytes\n");
      		printk("bytes=%ld\n", raw_cmd->length >> 9);
      		printk("sectors=%ld\n", current_count_sectors);
      	}
2882  	if (raw_cmd->length == 0){
      		DPRINT("zero dma transfer attempted from make_raw_request\n");
2884  		return 0;
      	}
      #endif
      
      	virtualdmabug_workaround();
2889  	return 2;
      }
      
2892  static void redo_fd_request(void)
      {
      #define REPEAT {request_done(0); continue; }
      	kdev_t device;
      	int tmp;
      
      	lastredo = jiffies;
2899  	if (current_drive < N_DRIVE)
      		floppy_off(current_drive);
      
2902  	if (!QUEUE_EMPTY && CURRENT->rq_status == RQ_INACTIVE){
      		CLEAR_INTR;
      		unlock_fdc();
2905  		return;
      	}
      
2908  	while(1){
2909  		if (QUEUE_EMPTY) {
      			CLEAR_INTR;
      			unlock_fdc();
2912  			return;
      		}
2914  		if (MAJOR(CURRENT->rq_dev) != MAJOR_NR)
      			panic(DEVICE_NAME ": request list destroyed");
2916  		if (CURRENT->bh && !buffer_locked(CURRENT->bh))
      			panic(DEVICE_NAME ": block not locked");
      
      		device = CURRENT->rq_dev;
      		set_fdc(DRIVE(device));
      		reschedule_timeout(CURRENTD, "redo fd request", 0);
      
      		set_floppy(device);
      		raw_cmd = & default_raw_cmd;
      		raw_cmd->flags = 0;
2926  		if (start_motor(redo_fd_request)) return;
      		disk_change(current_drive);
      		if (test_bit(current_drive, &fake_change) ||
2929  		   TESTF(FD_DISK_CHANGED)){
      			DPRINT("disk absent or changed during operation\n");
2931  			REPEAT;
      		}
2933  		if (!_floppy) { /* Autodetection */
2934  			if (!probing){
      				DRS->probed_format = 0;
2936  				if (next_valid_format()){
      					DPRINT("no autodetectable formats\n");
      					_floppy = NULL;
2939  					REPEAT;
      				}
      			}
      			probing = 1;
      			_floppy = floppy_type+DP->autodetect[DRS->probed_format];
2944  		} else
      			probing = 0;
      		errors = & (CURRENT->errors);
      		tmp = make_raw_rw_request();
2948  		if (tmp < 2){
      			request_done(tmp);
2950  			continue;
      		}
      
2953  		if (TESTF(FD_NEED_TWADDLE))
      			twaddle();
      		schedule_bh( (void *)(void *) floppy_start);
      #ifdef DEBUGT
      		debugt("queue fd request");
      #endif
2959  		return;
      	}
      #undef REPEAT
      }
      
      static struct cont_t rw_cont={
      	rw_interrupt,
      	redo_fd_request,
      	bad_flp_intr,
      	request_done };
      
2970  static void process_fd_request(void)
      {
      	cont = &rw_cont;
      	schedule_bh( (void *)(void *) redo_fd_request);
      }
      
2976  static void do_fd_request(request_queue_t * q)
      {
2978  	if(max_buffer_sectors == 0) {
      		printk("VFS: do_fd_request called on non-open device\n");
2980  		return;
      	}
      
2983  	if (usage_count == 0) {
      		printk("warning: usage count=0, CURRENT=%p exiting\n", CURRENT);
      		printk("sect=%ld cmd=%d\n", CURRENT->sector, CURRENT->cmd);
2986  		return;
      	}
2988  	if (fdc_busy){
      		/* fdc busy, this new request will be treated when the
      		   current one is done */
      		is_alive("do fd request, old request running");
2992  		return;
      	}
      	lock_fdc(MAXTIMEOUT,0);
      	process_fd_request();
      	is_alive("do fd request");
      }
      
      static struct cont_t poll_cont={
      	success_and_wakeup,
      	floppy_ready,
      	generic_failure,
      	generic_done };
      
3005  static int poll_drive(int interruptible, int flag)
      {
      	int ret;
      	/* no auto-sense, just clear dcl */
      	raw_cmd = &default_raw_cmd;
      	raw_cmd->flags= flag;
      	raw_cmd->track=0;
      	raw_cmd->cmd_count=0;
      	cont = &poll_cont;
      #ifdef DCL_DEBUG
3015  	if (DP->flags & FD_DEBUG){
      		DPRINT("setting NEWCHANGE in poll_drive\n");
      	}
      #endif
      	SETF(FD_DISK_NEWCHANGE);
3020  	WAIT(floppy_ready);
3021  	return ret;
      }
      
      /*
       * User triggered reset
       * ====================
       */
      
3029  static void reset_intr(void)
      {
      	printk("weird, reset interrupt called\n");
      }
      
      static struct cont_t reset_cont={
      	reset_intr,
      	success_and_wakeup,
      	generic_failure,
      	generic_done };
      
3040  static int user_reset_fdc(int drive, int arg, int interruptible)
      {
      	int ret;
      
      	ret=0;
3045  	LOCK_FDC(drive,interruptible);
3046  	if (arg == FD_RESET_ALWAYS)
      		FDCS->reset=1;
3048  	if (FDCS->reset){
      		cont = &reset_cont;
3050  		WAIT(reset_fdc);
      	}
      	process_fd_request();
3053  	return ret;
      }
      
      /*
       * Misc Ioctl's and support
       * ========================
       */
3060  static inline int fd_copyout(void *param, const void *address, unsigned long size)
      {
3062  	return copy_to_user(param,address, size) ? -EFAULT : 0;
      }
      
3065  static inline int fd_copyin(void *param, void *address, unsigned long size)
      {
3067  	return copy_from_user(address, param, size) ? -EFAULT : 0;
      }
      
      #define _COPYOUT(x) (copy_to_user((void *)param, &(x), sizeof(x)) ? -EFAULT : 0)
      #define _COPYIN(x) (copy_from_user(&(x), (void *)param, sizeof(x)) ? -EFAULT : 0)
      
      #define COPYOUT(x) ECALL(_COPYOUT(x))
      #define COPYIN(x) ECALL(_COPYIN(x))
      
3076  static inline const char *drive_name(int type, int drive)
      {
      	struct floppy_struct *floppy;
      
3080  	if (type)
      		floppy = floppy_type + type;
3082  	else {
3083  		if (UDP->native_format)
      			floppy = floppy_type + UDP->native_format;
3085  		else
3086  			return "(null)";
      	}
3088  	if (floppy->name)
3089  		return floppy->name;
3090  	else
3091  		return "(null)";
      }
      
      
      /* raw commands */
3096  static void raw_cmd_done(int flag)
      {
      	int i;
      
3100  	if (!flag) {
      		raw_cmd->flags |= FD_RAW_FAILURE;
      		raw_cmd->flags |= FD_RAW_HARDFAILURE;
3103  	} else {
      		raw_cmd->reply_count = inr;
3105  		if (raw_cmd->reply_count > MAX_REPLIES)
      			raw_cmd->reply_count=0;
3107  		for (i=0; i< raw_cmd->reply_count; i++)
      			raw_cmd->reply[i] = reply_buffer[i];
      
3110  		if (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE))
      		{
      			unsigned long flags;
      			flags=claim_dma_lock();
      			raw_cmd->length = fd_get_dma_residue();
      			release_dma_lock(flags);
      		}
      		
      		if ((raw_cmd->flags & FD_RAW_SOFTFAILURE) &&
3119  		    (!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0)))
      			raw_cmd->flags |= FD_RAW_FAILURE;
      
3122  		if (disk_change(current_drive))
      			raw_cmd->flags |= FD_RAW_DISK_CHANGE;
3124  		else
      			raw_cmd->flags &= ~FD_RAW_DISK_CHANGE;
3126  		if (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER)
      			motor_off_callback(current_drive);
      
      		if (raw_cmd->next &&
      		   (!(raw_cmd->flags & FD_RAW_FAILURE) ||
      		    !(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) &&
      		   ((raw_cmd->flags & FD_RAW_FAILURE) ||
3133  		    !(raw_cmd->flags &FD_RAW_STOP_IF_SUCCESS))) {
      			raw_cmd = raw_cmd->next;
3135  			return;
      		}
      	}
      	generic_done(flag);
      }
      
      
      static struct cont_t raw_cmd_cont={
      	success_and_wakeup,
      	floppy_start,
      	generic_failure,
      	raw_cmd_done
      };
      
3149  static inline int raw_cmd_copyout(int cmd, char *param,
      				  struct floppy_raw_cmd *ptr)
      {
      	int ret;
      
3154  	while(ptr) {
3155  		COPYOUT(*ptr);
      		param += sizeof(struct floppy_raw_cmd);
3157  		if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length){
3158  			if (ptr->length>=0 && ptr->length<=ptr->buffer_length)
      				ECALL(fd_copyout(ptr->data, 
      						 ptr->kernel_data, 
      						 ptr->buffer_length - 
3162  						 ptr->length));
      		}
      		ptr = ptr->next;
      	}
3166  	return 0;
      }
      
      
3170  static void raw_cmd_free(struct floppy_raw_cmd **ptr)
      {
      	struct floppy_raw_cmd *next,*this;
      
      	this = *ptr;
      	*ptr = 0;
3176  	while(this) {
3177  		if (this->buffer_length) {
      			fd_dma_mem_free((unsigned long)this->kernel_data,
      					this->buffer_length);
      			this->buffer_length = 0;
      		}
      		next = this->next;
      		kfree(this);
      		this = next;
      	}
      }
      
      
3189  static inline int raw_cmd_copyin(int cmd, char *param,
      				 struct floppy_raw_cmd **rcmd)
      {
      	struct floppy_raw_cmd *ptr;
      	int ret;
      	int i;
      	
      	*rcmd = 0;
3197  	while(1) {
      		ptr = (struct floppy_raw_cmd *) 
      			kmalloc(sizeof(struct floppy_raw_cmd), GFP_USER);
3200  		if (!ptr)
3201  			return -ENOMEM;
      		*rcmd = ptr;
3203  		COPYIN(*ptr);
      		ptr->next = 0;
      		ptr->buffer_length = 0;
      		param += sizeof(struct floppy_raw_cmd);
3207  		if (ptr->cmd_count > 33)
      			/* the command may now also take up the space
      			 * initially intended for the reply & the
      			 * reply count. Needed for long 82078 commands
      			 * such as RESTORE, which takes ... 17 command
      			 * bytes. Murphy's law #137: When you reserve
      			 * 16 bytes for a structure, you'll one day
      			 * discover that you really need 17...
      			 */
3216  			return -EINVAL;
      
3218  		for (i=0; i< 16; i++)
      			ptr->reply[i] = 0;
      		ptr->resultcode = 0;
      		ptr->kernel_data = 0;
      
3223  		if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) {
3224  			if (ptr->length <= 0)
3225  				return -EINVAL;
      			ptr->kernel_data =(char*)fd_dma_mem_alloc(ptr->length);
      			fallback_on_nodma_alloc(&ptr->kernel_data,
      						ptr->length);
3229  			if (!ptr->kernel_data)
3230  				return -ENOMEM;
      			ptr->buffer_length = ptr->length;
      		}
3233  		if (ptr->flags & FD_RAW_WRITE)
      			ECALL(fd_copyin(ptr->data, ptr->kernel_data, 
3235  					ptr->length));
      		rcmd = & (ptr->next);
3237  		if (!(ptr->flags & FD_RAW_MORE))
3238  			return 0;
      		ptr->rate &= 0x43;
      	}
      }
      
      
3244  static int raw_cmd_ioctl(int cmd, void *param)
      {
      	int drive, ret, ret2;
      	struct floppy_raw_cmd *my_raw_cmd;
      
3249  	if (FDCS->rawcmd <= 1)
      		FDCS->rawcmd = 1;
3251  	for (drive= 0; drive < N_DRIVE; drive++){
3252  		if (FDC(drive) != fdc)
3253  			continue;
3254  		if (drive == current_drive){
3255  			if (UDRS->fd_ref > 1){
      				FDCS->rawcmd = 2;
3257  				break;
      			}
3259  		} else if (UDRS->fd_ref){
      			FDCS->rawcmd = 2;
3261  			break;
      		}
      	}
      
3265  	if (FDCS->reset)
3266  		return -EIO;
      
      	ret = raw_cmd_copyin(cmd, param, &my_raw_cmd);
3269  	if (ret) {
      		raw_cmd_free(&my_raw_cmd);
3271  		return ret;
      	}
      
      	raw_cmd = my_raw_cmd;
      	cont = &raw_cmd_cont;
      	ret=wait_til_done(floppy_start,1);
      #ifdef DCL_DEBUG
3278  	if (DP->flags & FD_DEBUG){
      		DPRINT("calling disk change from raw_cmd ioctl\n");
      	}
      #endif
      
3283  	if (ret != -EINTR && FDCS->reset)
      		ret = -EIO;
      
      	DRS->track = NO_TRACK;
      
      	ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd);
3289  	if (!ret)
      		ret = ret2;
      	raw_cmd_free(&my_raw_cmd);
3292  	return ret;
      }
      
3295  static int invalidate_drive(kdev_t rdev)
      {
      	/* invalidate the buffer track to force a reread */
      	set_bit(DRIVE(rdev), &fake_change);
      	process_fd_request();
      	check_disk_change(rdev);
3301  	return 0;
      }
      
      
3305  static inline void clear_write_error(int drive)
      {
      	CLEARSTRUCT(UDRWE);
      }
      
3310  static inline int set_geometry(unsigned int cmd, struct floppy_struct *g,
      			       int drive, int type, kdev_t device)
      {
      	int cnt;
      
      	/* sanity checking for parameters.*/
      	if (g->sect <= 0 ||
      	    g->head <= 0 ||
      	    g->track <= 0 ||
      	    g->track > UDP->tracks>>STRETCH(g) ||
      	    /* check if reserved bits are set */
3321  	    (g->stretch&~(FD_STRETCH|FD_SWAPSIDES)) != 0)
3322  		return -EINVAL;
3323  	if (type){
3324  		if (!capable(CAP_SYS_ADMIN))
3325  			return -EPERM;
3326  		LOCK_FDC(drive,1);
3327  		for (cnt = 0; cnt < N_DRIVE; cnt++){
      			if (ITYPE(drive_state[cnt].fd_device) == type &&
3329  			    drive_state[cnt].fd_ref)
      				set_bit(drive, &fake_change);
      		}
      		floppy_type[type] = *g;
      		floppy_type[type].name="user format";
3334  		for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
      			floppy_sizes[cnt]= floppy_sizes[cnt+0x80]=
      				(floppy_type[type].size+1)>>1;
      		process_fd_request();
3338  		for (cnt = 0; cnt < N_DRIVE; cnt++){
      			if (ITYPE(drive_state[cnt].fd_device) == type &&
3340  			    drive_state[cnt].fd_ref)
      				check_disk_change(
      					MKDEV(FLOPPY_MAJOR,
      					      drive_state[cnt].fd_device));
      		}
3345  	} else {
3346  		LOCK_FDC(drive,1);
3347  		if (cmd != FDDEFPRM)
      			/* notice a disk change immediately, else
      			 * we lose our settings immediately*/
3350  			CALL(poll_drive(1, FD_RAW_NEED_DISK));
      		user_params[drive] = *g;
3352  		if (buffer_drive == drive)
      			SUPBOUND(buffer_max, user_params[drive].sect);
      		current_type[drive] = &user_params[drive];
      		floppy_sizes[drive] = (user_params[drive].size+1) >> 1;
3356  		if (cmd == FDDEFPRM)
      			DRS->keep_data = -1;
3358  		else
      			DRS->keep_data = 1;
      		/* invalidation. Invalidate only when needed, i.e.
      		 * when there are already sectors in the buffer cache
      		 * whose number will change. This is useful, because
      		 * mtools often changes the geometry of the disk after
      		 * looking at the boot block */
3365  		if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack)
      			invalidate_drive(device);
3367  		else
      			process_fd_request();
      	}
3370  	return 0;
      }
      
      /* handle obsolete ioctl's */
      static int ioctl_table[]= {
      	FDCLRPRM,
      	FDSETPRM,
      	FDDEFPRM,
      	FDGETPRM,
      	FDMSGON,
      	FDMSGOFF,
      	FDFMTBEG,
      	FDFMTTRK,
      	FDFMTEND,
      	FDSETEMSGTRESH,
      	FDFLUSH,
      	FDSETMAXERRS,
      	FDGETMAXERRS,
      	FDGETDRVTYP,
      	FDSETDRVPRM,
      	FDGETDRVPRM,
      	FDGETDRVSTAT,
      	FDPOLLDRVSTAT,
      	FDRESET,
      	FDGETFDCSTAT,
      	FDWERRORCLR,
      	FDWERRORGET,
      	FDRAWCMD,
      	FDEJECT,
      	FDTWADDLE
      };
      
3402  static inline int normalize_ioctl(int *cmd, int *size)
      {
      	int i;
      
3406  	for (i=0; i < ARRAY_SIZE(ioctl_table); i++) {
3407  		if ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)){
      			*size = _IOC_SIZE(*cmd);
      			*cmd = ioctl_table[i];
3410  			if (*size > _IOC_SIZE(*cmd)) {
      				printk("ioctl not yet supported\n");
3412  				return -EFAULT;
      			}
3414  			return 0;
      		}
      	}
3417  	return -EINVAL;
      }
      
3420  static int get_floppy_geometry(int drive, int type, struct floppy_struct **g)
      {
3422  	if (type)
      		*g = &floppy_type[type];
3424  	else {
3425  		LOCK_FDC(drive,0);
3426  		CALL(poll_drive(0,0));
      		process_fd_request();		
      		*g = current_type[drive];
      	}
3430  	if (!*g)
3431  		return -ENODEV;
3432  	return 0;
      }
      
3435  static int fd_ioctl(struct inode *inode, struct file *filp, unsigned int cmd,
      		    unsigned long param)
      {
      #define FD_IOCTL_ALLOWED ((filp) && (filp)->private_data)
      #define OUT(c,x) case c: outparam = (const char *) (x); break
      #define IN(c,x,tag) case c: *(x) = inparam. tag ; return 0
      
      	int i,drive,type;
      	kdev_t device;
      	int ret;
      	int size;
      	union inparam {
      		struct floppy_struct g; /* geometry */
      		struct format_descr f;
      		struct floppy_max_errors max_errors;
      		struct floppy_drive_params dp;
      	} inparam; /* parameters coming from user space */
      	const char *outparam; /* parameters passed back to user space */
      
      	device = inode->i_rdev;
3455  	switch (cmd) {
3456  		case BLKROSET:
3457  		case BLKROGET:
3458  		case BLKRASET:
3459  		case BLKRAGET:
3460  		case BLKFLSBUF:
3461  			return blk_ioctl(device, cmd, param);
      	}
      	type = TYPE(device);
      	drive = DRIVE(device);
      
      	/* convert compatibility eject ioctls into floppy eject ioctl.
      	 * We do this in order to provide a means to eject floppy disks before
      	 * installing the new fdutils package */
      	if (cmd == CDROMEJECT || /* CD-ROM eject */
3470  	    cmd == 0x6470 /* SunOS floppy eject */) {
      		DPRINT("obsolete eject ioctl\n");
      		DPRINT("please use floppycontrol --eject\n");
      		cmd = FDEJECT;
      	}
      
      	/* generic block device ioctls */
3477  	switch(cmd) {
      		/* the following have been inspired by the corresponding
      		 * code for other block devices. */
      		struct floppy_struct *g;
3481  		case HDIO_GETGEO:
      		{
      			struct hd_geometry loc;
3484  			ECALL(get_floppy_geometry(drive, type, &g));
      			loc.heads = g->head;
      			loc.sectors = g->sect;
      			loc.cylinders = g->track;
      			loc.start = 0;
3489  			return _COPYOUT(loc);
      		}
      
3492  		case BLKGETSIZE:
3493  			ECALL(get_floppy_geometry(drive, type, &g));
3494  			return put_user(g->size, (long *) param);
      		/* BLKRRPART is not defined as floppies don't have
      		 * partition tables */
      	}
      
      	/* convert the old style command into a new style command */
3500  	if ((cmd & 0xff00) == 0x0200) {
3501  		ECALL(normalize_ioctl(&cmd, &size));
3502  	} else
3503  		return -EINVAL;
      
      	/* permission checks */
      	if (((cmd & 0x40) && !FD_IOCTL_ALLOWED) ||
3507  	    ((cmd & 0x80) && !capable(CAP_SYS_ADMIN)))
3508  		return -EPERM;
      
      	/* copyin */
      	CLEARSTRUCT(&inparam);
3512  	if (_IOC_DIR(cmd) & _IOC_WRITE)
3513  		ECALL(fd_copyin((void *)param, &inparam, size))
      
3515  	switch (cmd) {
3516  		case FDEJECT:
3517  			if (UDRS->fd_ref != 1)
      				/* somebody else has this drive open */
3519  				return -EBUSY;
3520  			LOCK_FDC(drive,1);
      
      			/* do the actual eject. Fails on
      			 * non-Sparc architectures */
      			ret=fd_eject(UNIT(drive));
      
      			USETF(FD_DISK_CHANGED);
      			USETF(FD_VERIFY);
      			process_fd_request();
3529  			return ret;			
3530  		case FDCLRPRM:
3531  			LOCK_FDC(drive,1);
      			current_type[drive] = NULL;
      			floppy_sizes[drive] = MAX_DISK_SIZE;
      			UDRS->keep_data = 0;
3535  			return invalidate_drive(device);
3536  		case FDSETPRM:
3537  		case FDDEFPRM:
      			return set_geometry(cmd, & inparam.g,
3539  					    drive, type, device);
3540  		case FDGETPRM:
      			ECALL(get_floppy_geometry(drive, type, 
      						  (struct floppy_struct**)
3543  						  &outparam));
3544  			break;
      
3546  		case FDMSGON:
      			UDP->flags |= FTD_MSG;
3548  			return 0;
3549  		case FDMSGOFF:
      			UDP->flags &= ~FTD_MSG;
3551  			return 0;
      
3553  		case FDFMTBEG:
3554  			LOCK_FDC(drive,1);
3555  			CALL(poll_drive(1, FD_RAW_NEED_DISK));
      			ret = UDRS->flags;
      			process_fd_request();
3558  			if (ret & FD_VERIFY)
3559  				return -ENODEV;
3560  			if (!(ret & FD_DISK_WRITABLE))
3561  				return -EROFS;
3562  			return 0;
3563  		case FDFMTTRK:
3564  			if (UDRS->fd_ref != 1)
3565  				return -EBUSY;
3566  			return do_format(device, &inparam.f);
3567  		case FDFMTEND:
3568  		case FDFLUSH:
3569  			LOCK_FDC(drive,1);
3570  			return invalidate_drive(device);
      
3572  		case FDSETEMSGTRESH:
      			UDP->max_errors.reporting =
      				(unsigned short) (param & 0x0f);
3575  			return 0;
3576  		OUT(FDGETMAXERRS, &UDP->max_errors);
3577  		IN(FDSETMAXERRS, &UDP->max_errors, max_errors);
      
3579  		case FDGETDRVTYP:
      			outparam = drive_name(type,drive);
      			SUPBOUND(size,strlen(outparam)+1);
3582  			break;
      
3584  		IN(FDSETDRVPRM, UDP, dp);
3585  		OUT(FDGETDRVPRM, UDP);
      
3587  		case FDPOLLDRVSTAT:
3588  			LOCK_FDC(drive,1);
3589  			CALL(poll_drive(1, FD_RAW_NEED_DISK));
      			process_fd_request();
      			/* fall through */
3592  	       	OUT(FDGETDRVSTAT, UDRS);
      
3594  		case FDRESET:
3595  			return user_reset_fdc(drive, (int)param, 1);
      
3597  		OUT(FDGETFDCSTAT,UFDCS);
      
3599  		case FDWERRORCLR:
      			CLEARSTRUCT(UDRWE);
3601  			return 0;
3602  		OUT(FDWERRORGET,UDRWE);
      
3604  		case FDRAWCMD:
3605  			if (type)
3606  				return -EINVAL;
3607  			LOCK_FDC(drive,1);
      			set_floppy(device);
3609  			CALL(i = raw_cmd_ioctl(cmd,(void *) param));
      			process_fd_request();
3611  			return i;
      
3613  		case FDTWADDLE:
3614  			LOCK_FDC(drive,1);
      			twaddle();
      			process_fd_request();
3617  			return 0;
      
3619  		default:
3620  			return -EINVAL;
      	}
      
3623  	if (_IOC_DIR(cmd) & _IOC_READ)
3624  		return fd_copyout((void *)param, outparam, size);
3625  	else
3626  		return 0;
      #undef OUT
      #undef IN
      }
      
3631  static void __init config_types(void)
      {
      	int first=1;
      	int drive;
      
      	/* read drive info out of physical CMOS */
      	drive=0;
3638  	if (!UDP->cmos)
      		UDP->cmos = FLOPPY0_TYPE;
      	drive=1;
3641  	if (!UDP->cmos && FLOPPY1_TYPE)
      		UDP->cmos = FLOPPY1_TYPE;
      
      	/* XXX */
      	/* additional physical CMOS drive detection should go here */
      
3647  	for (drive=0; drive < N_DRIVE; drive++){
      		unsigned int type = UDP->cmos;
      		struct floppy_drive_params *params;
      		const char *name = NULL;
      		static char temparea[32];
      
3653  		if (type < NUMBER(default_drive_params)) {
      			params = &default_drive_params[type].params;
3655  			if (type) {
      				name = default_drive_params[type].name;
      				allowed_drive_mask |= 1 << drive;
      			}
3659  		} else {
      			params = &default_drive_params[0].params;
      			sprintf(temparea, "unknown type %d (usb?)", type);
      			name = temparea;
      		}
3664  		if (name) {
      			const char * prepend = ",";
3666  			if (first) {
      				prepend = KERN_INFO "Floppy drive(s):";
      				first = 0;
      			}
      			printk("%s fd%d is %s", prepend, drive, name);
      			register_devfs_entries (drive);
      		}
      		*UDP = *params;
      	}
3675  	if (!first)
      		printk("\n");
      }
      
3679  static int floppy_release(struct inode * inode, struct file * filp)
      {
      	int drive = DRIVE(inode->i_rdev);
      
3683  	if (UDRS->fd_ref < 0)
      		UDRS->fd_ref=0;
3685  	else if (!UDRS->fd_ref--) {
      		DPRINT("floppy_release with fd_ref == 0");
      		UDRS->fd_ref = 0;
      	}
      	floppy_release_irq_and_dma();
3690  	return 0;
      }
      
      /*
       * floppy_open check for aliasing (/dev/fd0 can be the same as
       * /dev/PS0 etc), and disallows simultaneous access to the same
       * drive with different device numbers.
       */
      #define RETERR(x) do{floppy_release(inode,filp); return -(x);}while(0)
      
3700  static int floppy_open(struct inode * inode, struct file * filp)
      {
      	int drive;
      	int old_dev;
      	int try;
      	char *tmp;
      
3707  	if (!filp) {
      		DPRINT("Weird, open called with filp=0\n");
3709  		return -EIO;
      	}
      
      	filp->private_data = (void*) 0;
      
      	drive = DRIVE(inode->i_rdev);
      	if (drive >= N_DRIVE ||
      	    !(allowed_drive_mask & (1 << drive)) ||
3717  	    fdc_state[FDC(drive)].version == FDC_NONE)
3718  		return -ENXIO;
      
3720  	if (TYPE(inode->i_rdev) >= NUMBER(floppy_type))
3721  		return -ENXIO;
      	old_dev = UDRS->fd_device;
3723  	if (UDRS->fd_ref && old_dev != MINOR(inode->i_rdev))
3724  		return -EBUSY;
      
3726  	if (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)){
      		USETF(FD_DISK_CHANGED);
      		USETF(FD_VERIFY);
      	}
      
      	if (UDRS->fd_ref == -1 ||
3732  	   (UDRS->fd_ref && (filp->f_flags & O_EXCL)))
3733  		return -EBUSY;
      
3735  	if (floppy_grab_irq_and_dma())
3736  		return -EBUSY;
      
3738  	if (filp->f_flags & O_EXCL)
      		UDRS->fd_ref = -1;
3740  	else
      		UDRS->fd_ref++;
      
3743  	if (!floppy_track_buffer){
      		/* if opening an ED drive, reserve a big buffer,
      		 * else reserve a small one */
3746  		if ((UDP->cmos == 6) || (UDP->cmos == 5))
      			try = 64; /* Only 48 actually useful */
3748  		else
      			try = 32; /* Only 24 actually useful */
      
      		tmp=(char *)fd_dma_mem_alloc(1024 * try);
3752  		if (!tmp && !floppy_track_buffer) {
      			try >>= 1; /* buffer only one side */
      			INFBOUND(try, 16);
      			tmp= (char *)fd_dma_mem_alloc(1024*try);
      		}
3757  		if (!tmp && !floppy_track_buffer) {
      			fallback_on_nodma_alloc(&tmp, 2048 * try);
      		}
3760  		if (!tmp && !floppy_track_buffer) {
      			DPRINT("Unable to allocate DMA memory\n");
3762  			RETERR(ENXIO);
      		}
3764  		if (floppy_track_buffer) {
3765  			if (tmp)
      				fd_dma_mem_free((unsigned long)tmp,try*1024);
3767  		} else {
      			buffer_min = buffer_max = -1;
      			floppy_track_buffer = tmp;
      			max_buffer_sectors = try;
      		}
      	}
      
      	UDRS->fd_device = MINOR(inode->i_rdev);
3775  	if (old_dev != -1 && old_dev != MINOR(inode->i_rdev)) {
3776  		if (buffer_drive == drive)
      			buffer_track = -1;
      		invalidate_buffers(MKDEV(FLOPPY_MAJOR,old_dev));
      	}
      
      	/* Allow ioctls if we have write-permissions even if read-only open.
      	 * Needed so that programs such as fdrawcmd still can work on write
      	 * protected disks */
      	if ((filp->f_mode & 2) || 
3785  	    (inode->i_sb && (permission(inode,2) == 0)))
      	    filp->private_data = (void*) 8;
      
3788  	if (UFDCS->rawcmd == 1)
      		UFDCS->rawcmd = 2;
      
3791  	if (filp->f_flags & O_NDELAY)
3792  		return 0;
3793  	if (filp->f_mode & 3) {
      		UDRS->last_checked = 0;
      		check_disk_change(inode->i_rdev);
3796  		if (UTESTF(FD_DISK_CHANGED))
3797  			RETERR(ENXIO);
      	}
3799  	if ((filp->f_mode & 2) && !(UTESTF(FD_DISK_WRITABLE)))
3800  		RETERR(EROFS);
3801  	return 0;
      #undef RETERR
      }
      
      /*
       * Check if the disk has been changed or if a change has been faked.
       */
3808  static int check_floppy_change(kdev_t dev)
      {
      	int drive = DRIVE(dev);
      
3812  	if (MAJOR(dev) != MAJOR_NR) {
      		DPRINT("check_floppy_change: not a floppy\n");
3814  		return 0;
      	}
      
3817  	if (UTESTF(FD_DISK_CHANGED) || UTESTF(FD_VERIFY))
3818  		return 1;
      
3820  	if (UDP->checkfreq < (int)(jiffies - UDRS->last_checked)) {
3821  		if(floppy_grab_irq_and_dma()) {
3822  			return 1;
      		}
      
      		lock_fdc(drive,0);
      		poll_drive(0,0);
      		process_fd_request();
      		floppy_release_irq_and_dma();
      	}
      
      	if (UTESTF(FD_DISK_CHANGED) ||
      	   UTESTF(FD_VERIFY) ||
      	   test_bit(drive, &fake_change) ||
3834  	   (!TYPE(dev) && !current_type[drive]))
3835  		return 1;
3836  	return 0;
      }
      
      /* revalidate the floppy disk, i.e. trigger format autodetection by reading
       * the bootblock (block 0). "Autodetection" is also needed to check whether
       * there is a disk in the drive at all... Thus we also do it for fixed
       * geometry formats */
3843  static int floppy_revalidate(kdev_t dev)
      {
      #define NO_GEOM (!current_type[drive] && !TYPE(dev))
      	struct buffer_head * bh;
      	int drive=DRIVE(dev);
      	int cf;
      
      	if (UTESTF(FD_DISK_CHANGED) ||
      	    UTESTF(FD_VERIFY) ||
      	    test_bit(drive, &fake_change) ||
3853  	    NO_GEOM){
3854  		if(usage_count == 0) {
      			printk("VFS: revalidate called on non-open device.\n");
3856  			return -EFAULT;
      		}
      		lock_fdc(drive,0);
      		cf = UTESTF(FD_DISK_CHANGED) || UTESTF(FD_VERIFY);
3860  		if (!(cf || test_bit(drive, &fake_change) || NO_GEOM)){
      			process_fd_request(); /*already done by another thread*/
3862  			return 0;
      		}
      		UDRS->maxblock = 0;
      		UDRS->maxtrack = 0;
3866  		if (buffer_drive == drive)
      			buffer_track = -1;
      		clear_bit(drive, &fake_change);
      		UCLEARF(FD_DISK_CHANGED);
3870  		if (cf)
      			UDRS->generation++;
3872  		if (NO_GEOM){
      			/* auto-sensing */
      			int size = floppy_blocksizes[MINOR(dev)];
3875  			if (!size)
      				size = 1024;
3877  			if (!(bh = getblk(dev,0,size))){
      				process_fd_request();
3879  				return -ENXIO;
      			}
3881  			if (bh && !buffer_uptodate(bh))
      				ll_rw_block(READ, 1, &bh);
      			process_fd_request();
      			wait_on_buffer(bh);
      			brelse(bh);
3886  			return 0;
      		}
3888  		if (cf)
      			poll_drive(0, FD_RAW_NEED_DISK);
      		process_fd_request();
      	}
3892  	return 0;
      }
      
      static struct block_device_operations floppy_fops = {
      	open:			floppy_open,
      	release:		floppy_release,
      	ioctl:			fd_ioctl,
      	check_media_change:	check_floppy_change,
      	revalidate:		floppy_revalidate,
      };
      
3903  static void __init register_devfs_entries (int drive)
      {
          int base_minor, i;
          static char *table[] =
          {"", "d360", "h1200", "u360", "u720", "h360", "h720",
           "u1440", "u2880", "CompaQ", "h1440", "u1680", "h410",
           "u820", "h1476", "u1722", "h420", "u830", "h1494", "u1743",
           "h880", "u1040", "u1120", "h1600", "u1760", "u1920",
           "u3200", "u3520", "u3840", "u1840", "u800", "u1600",
           NULL
          };
          static int t360[] = {1,0}, t1200[] = {2,5,6,10,12,14,16,18,20,23,0},
            t3in[] = {8,9,26,27,28, 7,11,15,19,24,25,29,31, 3,4,13,17,21,22,30,0};
          static int *table_sup[] = 
          {NULL, t360, t1200, t3in+5+8, t3in+5, t3in, t3in};
      
          base_minor = (drive < 4) ? drive : (124 + drive);
3920      if (UDP->cmos <= NUMBER(default_drive_params)) {
      	i = 0;
3922  	do {
      	    char name[16];
      
      	    sprintf (name, "%d%s", drive, table[table_sup[UDP->cmos][i]]);
      	    devfs_register (devfs_handle, name, DEVFS_FL_DEFAULT, MAJOR_NR,
      			    base_minor + (table_sup[UDP->cmos][i] << 2),
      			    S_IFBLK | S_IRUSR | S_IWUSR | S_IRGRP |S_IWGRP,
      			    &floppy_fops, NULL);
3930  	} while (table_sup[UDP->cmos][i++]);
          }
      }
      
      /*
       * Floppy Driver initialization
       * =============================
       */
      
      /* Determine the floppy disk controller type */
      /* This routine was written by David C. Niemi */
3941  static char __init get_fdc_version(void)
      {
      	int r;
      
      	output_byte(FD_DUMPREGS);	/* 82072 and better know DUMPREGS */
3946  	if (FDCS->reset)
3947  		return FDC_NONE;
3948  	if ((r = result()) <= 0x00)
3949  		return FDC_NONE;	/* No FDC present ??? */
3950  	if ((r==1) && (reply_buffer[0] == 0x80)){
      		printk(KERN_INFO "FDC %d is an 8272A\n",fdc);
3952  		return FDC_8272A;	/* 8272a/765 don't know DUMPREGS */
      	}
3954  	if (r != 10) {
      		printk("FDC %d init: DUMPREGS: unexpected return of %d bytes.\n",
      		       fdc, r);
3957  		return FDC_UNKNOWN;
      	}
      
3960  	if (!fdc_configure()) {
      		printk(KERN_INFO "FDC %d is an 82072\n",fdc);
3962  		return FDC_82072;      	/* 82072 doesn't know CONFIGURE */
      	}
      
      	output_byte(FD_PERPENDICULAR);
3966  	if (need_more_output() == MORE_OUTPUT) {
      		output_byte(0);
3968  	} else {
      		printk(KERN_INFO "FDC %d is an 82072A\n", fdc);
3970  		return FDC_82072A;	/* 82072A as found on Sparcs. */
      	}
      
      	output_byte(FD_UNLOCK);
      	r = result();
3975  	if ((r == 1) && (reply_buffer[0] == 0x80)){
      		printk(KERN_INFO "FDC %d is a pre-1991 82077\n", fdc);
3977  		return FDC_82077_ORIG;	/* Pre-1991 82077, doesn't know 
      					 * LOCK/UNLOCK */
      	}
3980  	if ((r != 1) || (reply_buffer[0] != 0x00)) {
      		printk("FDC %d init: UNLOCK: unexpected return of %d bytes.\n",
      		       fdc, r);
3983  		return FDC_UNKNOWN;
      	}
      	output_byte(FD_PARTID);
      	r = result();
3987  	if (r != 1) {
      		printk("FDC %d init: PARTID: unexpected return of %d bytes.\n",
      		       fdc, r);
3990  		return FDC_UNKNOWN;
      	}
3992  	if (reply_buffer[0] == 0x80) {
      		printk(KERN_INFO "FDC %d is a post-1991 82077\n",fdc);
3994  		return FDC_82077;	/* Revised 82077AA passes all the tests */
      	}
3996  	switch (reply_buffer[0] >> 5) {
3997  		case 0x0:
      			/* Either a 82078-1 or a 82078SL running at 5Volt */
      			printk(KERN_INFO "FDC %d is an 82078.\n",fdc);
4000  			return FDC_82078;
4001  		case 0x1:
      			printk(KERN_INFO "FDC %d is a 44pin 82078\n",fdc);
4003  			return FDC_82078;
4004  		case 0x2:
      			printk(KERN_INFO "FDC %d is a S82078B\n", fdc);
4006  			return FDC_S82078B;
4007  		case 0x3:
      			printk(KERN_INFO "FDC %d is a National Semiconductor PC87306\n", fdc);
4009  			return FDC_87306;
4010  		default:
      			printk(KERN_INFO "FDC %d init: 82078 variant with unknown PARTID=%d.\n",
      			       fdc, reply_buffer[0] >> 5);
4013  			return FDC_82078_UNKN;
      	}
      } /* get_fdc_version */
      
      /* lilo configuration */
      
4019  static void __init floppy_set_flags(int *ints,int param, int param2)
      {
      	int i;
      
4023  	for (i=0; i < ARRAY_SIZE(default_drive_params); i++){
4024  		if (param)
      			default_drive_params[i].params.flags |= param2;
4026  		else
      			default_drive_params[i].params.flags &= ~param2;
      	}
      	DPRINT("%s flag 0x%x\n", param2 ? "Setting" : "Clearing", param);
      }
      
4032  static void __init daring(int *ints,int param, int param2)
      {
      	int i;
      
4036  	for (i=0; i < ARRAY_SIZE(default_drive_params); i++){
4037  		if (param){
      			default_drive_params[i].params.select_delay = 0;
      			default_drive_params[i].params.flags |= FD_SILENT_DCL_CLEAR;
4040  		} else {
      			default_drive_params[i].params.select_delay = 2*HZ/100;
      			default_drive_params[i].params.flags &= ~FD_SILENT_DCL_CLEAR;
      		}
      	}
      	DPRINT("Assuming %s floppy hardware\n", param ? "standard" : "broken");
      }
      
4048  static void __init set_cmos(int *ints, int dummy, int dummy2)
      {
      	int current_drive=0;
      
4052  	if (ints[0] != 2){
      		DPRINT("wrong number of parameters for CMOS\n");
4054  		return;
      	}
      	current_drive = ints[1];
4057  	if (current_drive < 0 || current_drive >= 8){
      		DPRINT("bad drive for set_cmos\n");
4059  		return;
      	}
4061  	if (current_drive >= 4 && !FDC2)
      		FDC2 = 0x370;
      	DP->cmos = ints[2];
      	DPRINT("setting CMOS code to %d\n", ints[2]);
      }
      
      static struct param_table {
      	const char *name;
      	void (*fn)(int *ints, int param, int param2);
      	int *var;
      	int def_param;
      	int param2;
      } config_params[]={
      	{ "allowed_drive_mask", 0, &allowed_drive_mask, 0xff, 0}, /* obsolete */
      	{ "all_drives", 0, &allowed_drive_mask, 0xff, 0 }, /* obsolete */
      	{ "asus_pci", 0, &allowed_drive_mask, 0x33, 0},
      
      	{ "irq", 0, &FLOPPY_IRQ, 6, 0 },
      	{ "dma", 0, &FLOPPY_DMA, 2, 0 },
      
      	{ "daring", daring, 0, 1, 0},
      
      	{ "two_fdc",  0, &FDC2, 0x370, 0 },
      	{ "one_fdc", 0, &FDC2, 0, 0 },
      
      	{ "thinkpad", floppy_set_flags, 0, 1, FD_INVERTED_DCL },
      	{ "broken_dcl", floppy_set_flags, 0, 1, FD_BROKEN_DCL },
      	{ "messages", floppy_set_flags, 0, 1, FTD_MSG },
      	{ "silent_dcl_clear", floppy_set_flags, 0, 1, FD_SILENT_DCL_CLEAR },
      	{ "debug", floppy_set_flags, 0, 1, FD_DEBUG },
      
      	{ "nodma", 0, &can_use_virtual_dma, 1, 0 },
      	{ "omnibook", 0, &can_use_virtual_dma, 1, 0 },
      	{ "yesdma", 0, &can_use_virtual_dma, 0, 0 },
      
      	{ "fifo_depth", 0, &fifo_depth, 0xa, 0 },
      	{ "nofifo", 0, &no_fifo, 0x20, 0 },
      	{ "usefifo", 0, &no_fifo, 0, 0 },
      
      	{ "cmos", set_cmos, 0, 0, 0 },
      	{ "slow", 0, &slow_floppy, 1, 0 },
      
      	{ "unexpected_interrupts", 0, &print_unex, 1, 0 },
      	{ "no_unexpected_interrupts", 0, &print_unex, 0, 0 },
      	{ "L40SX", 0, &print_unex, 0, 0 }
      };
      
4108  static int __init floppy_setup(char *str)
      {
      	int i;
      	int param;
      	int ints[11];
      
      	str = get_options(str,ARRAY_SIZE(ints),ints);
4115  	if (str) {
4116  		for (i=0; i< ARRAY_SIZE(config_params); i++){
4117  			if (strcmp(str,config_params[i].name) == 0){
4118  				if (ints[0])
      					param = ints[1];
4120  				else
      					param = config_params[i].def_param;
4122  				if (config_params[i].fn)
      					config_params[i].
      						fn(ints,param,
      						   config_params[i].param2);
4126  				if (config_params[i].var) {
      					DPRINT("%s=%d\n", str, param);
      					*config_params[i].var = param;
      				}
4130  				return 1;
      			}
      		}
      	}
4134  	if (str) {
      		DPRINT("unknown floppy option [%s]\n", str);
      		
      		DPRINT("allowed options are:");
4138  		for (i=0; i< ARRAY_SIZE(config_params); i++)
      			printk(" %s",config_params[i].name);
      		printk("\n");
4141  	} else
      		DPRINT("botched floppy option\n");
      	DPRINT("Read linux/Documentation/floppy.txt\n");
4144  	return 0;
      }
      
      static int have_no_fdc= -EIO;
      
      
4150  int __init floppy_init(void)
      {
      	int i,unit,drive;
      
      
      	raw_cmd = NULL;
      
      	devfs_handle = devfs_mk_dir (NULL, "floppy", NULL);
4158  	if (devfs_register_blkdev(MAJOR_NR,"fd",&floppy_fops)) {
      		printk("Unable to get major %d for floppy\n",MAJOR_NR);
4160  		return -EBUSY;
      	}
      
4163  	for (i=0; i<256; i++)
4164  		if (ITYPE(i))
      			floppy_sizes[i] = (floppy_type[ITYPE(i)].size+1) >> 1;
4166  		else
      			floppy_sizes[i] = MAX_DISK_SIZE;
      
      	blk_size[MAJOR_NR] = floppy_sizes;
      	blksize_size[MAJOR_NR] = floppy_blocksizes;
      	blk_init_queue(BLK_DEFAULT_QUEUE(MAJOR_NR), DEVICE_REQUEST);
      	reschedule_timeout(MAXTIMEOUT, "floppy init", MAXTIMEOUT);
      	config_types();
      
4175  	for (i = 0; i < N_FDC; i++) {
      		fdc = i;
      		CLEARSTRUCT(FDCS);
      		FDCS->dtr = -1;
      		FDCS->dor = 0x4;
      #ifdef __sparc__
      		/*sparcs don't have a DOR reset which we can fall back on to*/
      		FDCS->version = FDC_82072A;
      #endif
      	}
      
      	use_virtual_dma = can_use_virtual_dma & 1;
      	fdc_state[0].address = FDC1;
4188  	if (fdc_state[0].address == -1) {
      		devfs_unregister_blkdev(MAJOR_NR,"fd");
      		del_timer(&fd_timeout);
      		blk_cleanup_queue(BLK_DEFAULT_QUEUE(MAJOR_NR));
4192  		return -ENODEV;
      	}
      #if N_FDC > 1
      	fdc_state[1].address = FDC2;
      #endif
      
      	fdc = 0; /* reset fdc in case of unexpected interrupt */
4199  	if (floppy_grab_irq_and_dma()){
      		del_timer(&fd_timeout);
      		blk_cleanup_queue(BLK_DEFAULT_QUEUE(MAJOR_NR));
      		devfs_unregister_blkdev(MAJOR_NR,"fd");
      		del_timer(&fd_timeout);
4204  		return -EBUSY;
      	}
      
      	/* initialise drive state */
4208  	for (drive = 0; drive < N_DRIVE; drive++) {
      		CLEARSTRUCT(UDRS);
      		CLEARSTRUCT(UDRWE);
      		USETF(FD_DISK_NEWCHANGE);
      		USETF(FD_DISK_CHANGED);
      		USETF(FD_VERIFY);
      		UDRS->fd_device = -1;
      		floppy_track_buffer = NULL;
      		max_buffer_sectors = 0;
      	}
      
4219  	for (i = 0; i < N_FDC; i++) {
      		fdc = i;
      		FDCS->driver_version = FD_DRIVER_VERSION;
4222  		for (unit=0; unit<4; unit++)
      			FDCS->track[unit] = 0;
4224  		if (FDCS->address == -1)
4225  			continue;
      		FDCS->rawcmd = 2;
4227  		if (user_reset_fdc(-1,FD_RESET_ALWAYS,0)){
       			/* free ioports reserved by floppy_grab_irq_and_dma() */
       			release_region(FDCS->address, 6);
       			release_region(FDCS->address+7, 1);
      			FDCS->address = -1;
      			FDCS->version = FDC_NONE;
4233  			continue;
      		}
      		/* Try to determine the floppy controller type */
      		FDCS->version = get_fdc_version();
4237  		if (FDCS->version == FDC_NONE){
       			/* free ioports reserved by floppy_grab_irq_and_dma() */
       			release_region(FDCS->address, 6);
       			release_region(FDCS->address+7, 1);
      			FDCS->address = -1;
4242  			continue;
      		}
4244  		if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A)
      			can_use_virtual_dma = 0;
      
      		have_no_fdc = 0;
      		/* Not all FDCs seem to be able to handle the version command
      		 * properly, so force a reset for the standard FDC clones,
      		 * to avoid interrupt garbage.
      		 */
      		user_reset_fdc(-1,FD_RESET_ALWAYS,0);
      	}
      	fdc=0;
      	del_timer(&fd_timeout);
      	current_drive = 0;
      	floppy_release_irq_and_dma();
      	initialising=0;
4259  	if (have_no_fdc) 
      	{
      		DPRINT("no floppy controllers found\n");
      		floppy_tq.routine = (void *)(void *) empty;
      		mark_bh(IMMEDIATE_BH);
      		schedule();
4265  		if (usage_count)
      			floppy_release_irq_and_dma();
      		blk_cleanup_queue(BLK_DEFAULT_QUEUE(MAJOR_NR));
      		devfs_unregister_blkdev(MAJOR_NR,"fd");
      	}
      	
4271  	for (drive = 0; drive < N_DRIVE; drive++) {
4272  		if (!(allowed_drive_mask & (1 << drive)))
4273  			continue;
4274  		if (fdc_state[FDC(drive)].version == FDC_NONE)
4275  			continue;
4276  		for (i = 0; i<NUMBER(floppy_type); i++)
      			register_disk(NULL, MKDEV(MAJOR_NR,TOMINOR(drive)+i*4),
      					1, &floppy_fops, 0);
      	}
4280  	return have_no_fdc;
      }
      
      static spinlock_t floppy_usage_lock = SPIN_LOCK_UNLOCKED;
      
4285  static int floppy_grab_irq_and_dma(void)
      {
      	unsigned long flags;
      
4289  	spin_lock_irqsave(&floppy_usage_lock, flags);
4290  	if (usage_count++){
4291  		spin_unlock_irqrestore(&floppy_usage_lock, flags);
4292  		return 0;
      	}
4294  	spin_unlock_irqrestore(&floppy_usage_lock, flags);
4295  	MOD_INC_USE_COUNT;
4296  	if (fd_request_irq()) {
      		DPRINT("Unable to grab IRQ%d for the floppy driver\n",
      			FLOPPY_IRQ);
4299  		MOD_DEC_USE_COUNT;
4300  		spin_lock_irqsave(&floppy_usage_lock, flags);
      		usage_count--;
4302  		spin_unlock_irqrestore(&floppy_usage_lock, flags);
4303  		return -1;
      	}
4305  	if (fd_request_dma()) {
      		DPRINT("Unable to grab DMA%d for the floppy driver\n",
      			FLOPPY_DMA);
      		fd_free_irq();
4309  		MOD_DEC_USE_COUNT;
4310  		spin_lock_irqsave(&floppy_usage_lock, flags);
      		usage_count--;
4312  		spin_unlock_irqrestore(&floppy_usage_lock, flags);
4313  		return -1;
      	}
      
4316  	for (fdc=0; fdc< N_FDC; fdc++){
4317  		if (FDCS->address != -1){
4318  			if (!request_region(FDCS->address, 6, "floppy")) {
      				DPRINT("Floppy io-port 0x%04lx in use\n", FDCS->address);
4320  				goto cleanup1;
      			}
4322  			if (!request_region(FDCS->address + 7, 1, "floppy DIR")) {
      				DPRINT("Floppy io-port 0x%04lx in use\n", FDCS->address + 7);
4324  				goto cleanup2;
      			}
      			/* address + 6 is reserved, and may be taken by IDE.
      			 * Unfortunately, Adaptec doesn't know this :-(, */
      		}
      	}
4330  	for (fdc=0; fdc< N_FDC; fdc++){
4331  		if (FDCS->address != -1){
      			reset_fdc_info(1);
      			fd_outb(FDCS->dor, FD_DOR);
      		}
      	}
      	fdc = 0;
      	set_dor(0, ~0, 8);  /* avoid immediate interrupt */
      
4339  	for (fdc = 0; fdc < N_FDC; fdc++)
4340  		if (FDCS->address != -1)
      			fd_outb(FDCS->dor, FD_DOR);
      	/*
      	 *	The driver will try and free resources and relies on us
      	 *	to know if they were allocated or not.
      	 */
      	fdc = 0;
      	irqdma_allocated = 1;
4348  	return 0;
      cleanup2:
      	release_region(FDCS->address, 6);
      cleanup1:
      	fd_free_irq();
      	fd_free_dma();
4354  	while(--fdc >= 0) {
      		release_region(FDCS->address, 6);
      		release_region(FDCS->address + 7, 1);
      	}
4358  	MOD_DEC_USE_COUNT;
4359  	spin_lock_irqsave(&floppy_usage_lock, flags);
      	usage_count--;
4361  	spin_unlock_irqrestore(&floppy_usage_lock, flags);
4362  	return -1;
      }
      
4365  static void floppy_release_irq_and_dma(void)
      {
      	int old_fdc;
      #ifdef FLOPPY_SANITY_CHECK
      #ifndef __sparc__
      	int drive;
      #endif
      #endif
      	long tmpsize;
      	unsigned long tmpaddr;
      	unsigned long flags;
      
4377  	spin_lock_irqsave(&floppy_usage_lock, flags);
4378  	if (--usage_count){
4379  		spin_unlock_irqrestore(&floppy_usage_lock, flags);
4380  		return;
      	}
4382  	spin_unlock_irqrestore(&floppy_usage_lock, flags);
4383  	if(irqdma_allocated)
      	{
      		fd_disable_dma();
      		fd_free_dma();
      		fd_free_irq();
      		irqdma_allocated=0;
      	}
      	set_dor(0, ~0, 8);
      #if N_FDC > 1
      	set_dor(1, ~8, 0);
      #endif
      	floppy_enable_hlt();
      
4396  	if (floppy_track_buffer && max_buffer_sectors) {
      		tmpsize = max_buffer_sectors*1024;
      		tmpaddr = (unsigned long)floppy_track_buffer;
      		floppy_track_buffer = NULL;
      		max_buffer_sectors = 0;
      		buffer_min = buffer_max = -1;
      		fd_dma_mem_free(tmpaddr, tmpsize);
      	}
      
      #ifdef FLOPPY_SANITY_CHECK
      #ifndef __sparc__
4407  	for (drive=0; drive < N_FDC * 4; drive++)
4408  		if (timer_pending(motor_off_timer + drive))
      			printk("motor off timer %d still active\n", drive);
      #endif
      
4412  	if (timer_pending(&fd_timeout))
      		printk("floppy timer still active:%s\n", timeout_message);
4414  	if (timer_pending(&fd_timer))
      		printk("auxiliary floppy timer still active\n");
4416  	if (floppy_tq.sync)
      		printk("task queue still active\n");
      #endif
      	old_fdc = fdc;
4420  	for (fdc = 0; fdc < N_FDC; fdc++)
4421  		if (FDCS->address != -1) {
      			release_region(FDCS->address, 6);
      			release_region(FDCS->address+7, 1);
      		}
      	fdc = old_fdc;
4426  	MOD_DEC_USE_COUNT;
      }
      
      
      #ifdef MODULE
      
      char *floppy;
      
      static void __init parse_floppy_cfg_string(char *cfg)
      {
      	char *ptr;
      
      	while(*cfg) {
      		for(ptr = cfg;*cfg && *cfg != ' ' && *cfg != '\t'; cfg++);
      		if (*cfg) {
      			*cfg = '\0';
      			cfg++;
      		}
      		if (*ptr)
      			floppy_setup(ptr);
      	}
      }
      
      int init_module(void)
      {
      	printk(KERN_INFO "inserting floppy driver for " UTS_RELEASE "\n");
      		
      	if (floppy)
      		parse_floppy_cfg_string(floppy);
      	return floppy_init();
      }
      
      void cleanup_module(void)
      {
      	int dummy;
      		
      	devfs_unregister (devfs_handle);
      	devfs_unregister_blkdev(MAJOR_NR, "fd");
      
      	blk_cleanup_queue(BLK_DEFAULT_QUEUE(MAJOR_NR));
      	/* eject disk, if any */
      	dummy = fd_eject(0);
      }
      
      MODULE_PARM(floppy,"s");
      MODULE_PARM(FLOPPY_IRQ,"i");
      MODULE_PARM(FLOPPY_DMA,"i");
      MODULE_AUTHOR("Alain L. Knaff");
      MODULE_SUPPORTED_DEVICE("fd");
      
      #else
      
      __setup ("floppy=", floppy_setup);
      
      /* eject the boot floppy (if we need the drive for a different root floppy) */
      /* This should only be called at boot time when we're sure that there's no
       * resource contention. */
4483  void floppy_eject(void)
      {
      	int dummy;
4486  	if (have_no_fdc)
4487  		return;
4488  	if(floppy_grab_irq_and_dma()==0)
      	{
      		lock_fdc(MAXTIMEOUT,0);
      		dummy=fd_eject(0);
      		process_fd_request();
      		floppy_release_irq_and_dma();
      	}
      }
      #endif