ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / block / amiflop.c
1 /*
2  *  linux/amiga/amiflop.c
3  *
4  *  Copyright (C) 1993  Greg Harp
5  *  Portions of this driver are based on code contributed by Brad Pepers
6  *  
7  *  revised 28.5.95 by Joerg Dorchain
8  *  - now no bugs(?) any more for both HD & DD
9  *  - added support for 40 Track 5.25" drives, 80-track hopefully behaves
10  *    like 3.5" dd (no way to test - are there any 5.25" drives out there
11  *    that work on an A4000?)
12  *  - wrote formatting routine (maybe dirty, but works)
13  *
14  *  june/july 1995 added ms-dos support by Joerg Dorchain
15  *  (portions based on messydos.device and various contributors)
16  *  - currently only 9 and 18 sector disks
17  *
18  *  - fixed a bug with the internal trackbuffer when using multiple 
19  *    disks the same time
20  *  - made formatting a bit safer
21  *  - added command line and machine based default for "silent" df0
22  *
23  *  december 1995 adapted for 1.2.13pl4 by Joerg Dorchain
24  *  - works but I think it's inefficient. (look in redo_fd_request)
25  *    But the changes were very efficient. (only three and a half lines)
26  *
27  *  january 1996 added special ioctl for tracking down read/write problems
28  *  - usage ioctl(d, RAW_TRACK, ptr); the raw track buffer (MFM-encoded data
29  *    is copied to area. (area should be large enough since no checking is
30  *    done - 30K is currently sufficient). return the actual size of the
31  *    trackbuffer
32  *  - replaced udelays() by a timer (CIAA timer B) for the waits 
33  *    needed for the disk mechanic.
34  *
35  *  february 1996 fixed error recovery and multiple disk access
36  *  - both got broken the first time I tampered with the driver :-(
37  *  - still not safe, but better than before
38  *
39  *  revised Marts 3rd, 1996 by Jes Sorensen for use in the 1.3.28 kernel.
40  *  - Minor changes to accept the kdev_t.
41  *  - Replaced some more udelays with ms_delays. Udelay is just a loop,
42  *    and so the delay will be different depending on the given
43  *    processor :-(
44  *  - The driver could use a major cleanup because of the new
45  *    major/minor handling that came with kdev_t. It seems to work for
46  *    the time being, but I can't guarantee that it will stay like
47  *    that when we start using 16 (24?) bit minors.
48  *
49  * restructured jan 1997 by Joerg Dorchain
50  * - Fixed Bug accessing multiple disks
51  * - some code cleanup
52  * - added trackbuffer for each drive to speed things up
53  * - fixed some race conditions (who finds the next may send it to me ;-)
54  */
55
56 #include <linux/module.h>
57
58 #include <linux/fd.h>
59 #include <linux/hdreg.h>
60 #include <linux/delay.h>
61 #include <linux/init.h>
62 #include <linux/amifdreg.h>
63 #include <linux/amifd.h>
64 #include <linux/buffer_head.h>
65 #include <linux/blkdev.h>
66 #include <linux/elevator.h>
67
68 #include <asm/setup.h>
69 #include <asm/uaccess.h>
70 #include <asm/amigahw.h>
71 #include <asm/amigaints.h>
72 #include <asm/irq.h>
73
74 #undef DEBUG /* print _LOTS_ of infos */
75
76 #define RAW_IOCTL
77 #ifdef RAW_IOCTL
78 #define IOCTL_RAW_TRACK 0x5254524B  /* 'RTRK' */
79 #endif
80
81 /*
82  *  Defines
83  */
84
85 /*
86  *  Error codes
87  */
88 #define FD_OK           0       /* operation succeeded */
89 #define FD_ERROR        -1      /* general error (seek, read, write, etc) */
90 #define FD_NOUNIT       1       /* unit does not exist */
91 #define FD_UNITBUSY     2       /* unit already active */
92 #define FD_NOTACTIVE    3       /* unit is not active */
93 #define FD_NOTREADY     4       /* unit is not ready (motor not on/no disk) */
94
95 #define MFM_NOSYNC      1
96 #define MFM_HEADER      2
97 #define MFM_DATA        3
98 #define MFM_TRACK       4
99
100 /*
101  *  Floppy ID values
102  */
103 #define FD_NODRIVE      0x00000000  /* response when no unit is present */
104 #define FD_DD_3         0xffffffff  /* double-density 3.5" (880K) drive */
105 #define FD_HD_3         0x55555555  /* high-density 3.5" (1760K) drive */
106 #define FD_DD_5         0xaaaaaaaa  /* double-density 5.25" (440K) drive */
107
108 static long int fd_def_df0 = FD_DD_3;     /* default for df0 if it doesn't identify */
109
110 MODULE_PARM(fd_def_df0,"l");
111 MODULE_LICENSE("GPL");
112
113 static struct request_queue *floppy_queue;
114 #define QUEUE (floppy_queue)
115 #define CURRENT elv_next_request(floppy_queue)
116
117 /*
118  *  Macros
119  */
120 #define MOTOR_ON        (ciab.prb &= ~DSKMOTOR)
121 #define MOTOR_OFF       (ciab.prb |= DSKMOTOR)
122 #define SELECT(mask)    (ciab.prb &= ~mask)
123 #define DESELECT(mask)  (ciab.prb |= mask)
124 #define SELMASK(drive)  (1 << (3 + (drive & 3)))
125
126 static struct fd_drive_type drive_types[] = {
127 /*  code        name       tr he   rdsz   wrsz sm pc1 pc2 sd  st st*/
128 /*  warning: times are now in milliseconds (ms)                    */
129 { FD_DD_3,      "DD 3.5",  80, 2, 14716, 13630, 1, 80,161, 3, 18, 1},
130 { FD_HD_3,      "HD 3.5",  80, 2, 28344, 27258, 2, 80,161, 3, 18, 1},
131 { FD_DD_5,      "DD 5.25", 40, 2, 14716, 13630, 1, 40, 81, 6, 30, 2},
132 { FD_NODRIVE, "No Drive", 0, 0,     0,     0, 0,  0,  0,  0,  0, 0}
133 };
134 static int num_dr_types = sizeof(drive_types) / sizeof(drive_types[0]);
135
136 static int amiga_read(int), dos_read(int);
137 static void amiga_write(int), dos_write(int);
138 static struct fd_data_type data_types[] = {
139         { "Amiga", 11 , amiga_read, amiga_write},
140         { "MS-Dos", 9, dos_read, dos_write}
141 };
142
143 /* current info on each unit */
144 static struct amiga_floppy_struct unit[FD_MAX_UNITS];
145
146 static struct timer_list flush_track_timer[FD_MAX_UNITS];
147 static struct timer_list post_write_timer;
148 static struct timer_list motor_on_timer;
149 static struct timer_list motor_off_timer[FD_MAX_UNITS];
150 static int on_attempts;
151
152 /* Synchronization of FDC access */
153 /* request loop (trackbuffer) */
154 static volatile int fdc_busy = -1;
155 static volatile int fdc_nested;
156 static DECLARE_WAIT_QUEUE_HEAD(fdc_wait);
157  
158 static DECLARE_WAIT_QUEUE_HEAD(motor_wait);
159
160 static volatile int selected = -1;      /* currently selected drive */
161
162 static int writepending;
163 static int writefromint;
164 static char *raw_buf;
165
166 static spinlock_t amiflop_lock = SPIN_LOCK_UNLOCKED;
167
168 #define RAW_BUF_SIZE 30000  /* size of raw disk data */
169
170 /*
171  * These are global variables, as that's the easiest way to give
172  * information to interrupts. They are the data used for the current
173  * request.
174  */
175 static volatile char block_flag;
176 static DECLARE_WAIT_QUEUE_HEAD(wait_fd_block);
177
178 /* MS-Dos MFM Coding tables (should go quick and easy) */
179 static unsigned char mfmencode[16]={
180         0x2a, 0x29, 0x24, 0x25, 0x12, 0x11, 0x14, 0x15,
181         0x4a, 0x49, 0x44, 0x45, 0x52, 0x51, 0x54, 0x55
182 };
183 static unsigned char mfmdecode[128];
184
185 /* floppy internal millisecond timer stuff */
186 static volatile int ms_busy = -1;
187 static DECLARE_WAIT_QUEUE_HEAD(ms_wait);
188 #define MS_TICKS ((amiga_eclock+50)/1000)
189
190 /*
191  * Note that MAX_ERRORS=X doesn't imply that we retry every bad read
192  * max X times - some types of errors increase the errorcount by 2 or
193  * even 3, so we might actually retry only X/2 times before giving up.
194  */
195 #define MAX_ERRORS 12
196
197 /* Prevent "aliased" accesses. */
198 static int fd_ref[4] = { 0,0,0,0 };
199 static int fd_device[4] = { 0, 0, 0, 0 };
200
201 /*
202  * Here come the actual hardware access and helper functions.
203  * They are not reentrant and single threaded because all drives
204  * share the same hardware and the same trackbuffer.
205  */
206
207 /* Milliseconds timer */
208
209 static irqreturn_t ms_isr(int irq, void *dummy, struct pt_regs *fp)
210 {
211         ms_busy = -1;
212         wake_up(&ms_wait);
213         return IRQ_HANDLED;
214 }
215
216 /* all waits are queued up 
217    A more generic routine would do a schedule a la timer.device */
218 static void ms_delay(int ms)
219 {
220         unsigned long flags;
221         int ticks;
222         if (ms > 0) {
223                 local_irq_save(flags);
224                 while (ms_busy == 0)
225                         sleep_on(&ms_wait);
226                 ms_busy = 0;
227                 local_irq_restore(flags);
228                 ticks = MS_TICKS*ms-1;
229                 ciaa.tblo=ticks%256;
230                 ciaa.tbhi=ticks/256;
231                 ciaa.crb=0x19; /*count eclock, force load, one-shoot, start */
232                 sleep_on(&ms_wait);
233         }
234 }
235
236 /* Hardware semaphore */
237
238 /* returns true when we would get the semaphore */
239 static inline int try_fdc(int drive)
240 {
241         drive &= 3;
242         return ((fdc_busy < 0) || (fdc_busy == drive));
243 }
244
245 static void get_fdc(int drive)
246 {
247         unsigned long flags;
248
249         drive &= 3;
250 #ifdef DEBUG
251         printk("get_fdc: drive %d  fdc_busy %d  fdc_nested %d\n",drive,fdc_busy,fdc_nested);
252 #endif
253         local_irq_save(flags);
254         while (!try_fdc(drive))
255                 sleep_on(&fdc_wait);
256         fdc_busy = drive;
257         fdc_nested++;
258         local_irq_restore(flags);
259 }
260
261 static inline void rel_fdc(void)
262 {
263 #ifdef DEBUG
264         if (fdc_nested == 0)
265                 printk("fd: unmatched rel_fdc\n");
266         printk("rel_fdc: fdc_busy %d fdc_nested %d\n",fdc_busy,fdc_nested);
267 #endif
268         fdc_nested--;
269         if (fdc_nested == 0) {
270                 fdc_busy = -1;
271                 wake_up(&fdc_wait);
272         }
273 }
274
275 static void fd_select (int drive)
276 {
277         unsigned char prb = ~0;
278
279         drive&=3;
280 #ifdef DEBUG
281         printk("selecting %d\n",drive);
282 #endif
283         if (drive == selected)
284                 return;
285         get_fdc(drive);
286         selected = drive;
287
288         if (unit[drive].track % 2 != 0)
289                 prb &= ~DSKSIDE;
290         if (unit[drive].motor == 1)
291                 prb &= ~DSKMOTOR;
292         ciab.prb |= (SELMASK(0)|SELMASK(1)|SELMASK(2)|SELMASK(3));
293         ciab.prb = prb;
294         prb &= ~SELMASK(drive);
295         ciab.prb = prb;
296         rel_fdc();
297 }
298
299 static void fd_deselect (int drive)
300 {
301         unsigned char prb;
302         unsigned long flags;
303
304         drive&=3;
305 #ifdef DEBUG
306         printk("deselecting %d\n",drive);
307 #endif
308         if (drive != selected) {
309                 printk(KERN_WARNING "Deselecting drive %d while %d was selected!\n",drive,selected);
310                 return;
311         }
312
313         get_fdc(drive);
314         local_irq_save(flags);
315
316         selected = -1;
317
318         prb = ciab.prb;
319         prb |= (SELMASK(0)|SELMASK(1)|SELMASK(2)|SELMASK(3));
320         ciab.prb = prb;
321
322         local_irq_restore (flags);
323         rel_fdc();
324
325 }
326
327 static void motor_on_callback(unsigned long nr)
328 {
329         if (!(ciaa.pra & DSKRDY) || --on_attempts == 0) {
330                 wake_up (&motor_wait);
331         } else {
332                 motor_on_timer.expires = jiffies + HZ/10;
333                 add_timer(&motor_on_timer);
334         }
335 }
336
337 static int fd_motor_on(int nr)
338 {
339         nr &= 3;
340
341         del_timer(motor_off_timer + nr);
342
343         if (!unit[nr].motor) {
344                 unit[nr].motor = 1;
345                 fd_select(nr);
346
347                 motor_on_timer.data = nr;
348                 mod_timer(&motor_on_timer, jiffies + HZ/2);
349
350                 on_attempts = 10;
351                 sleep_on (&motor_wait);
352                 fd_deselect(nr);
353         }
354
355         if (on_attempts == 0) {
356                 on_attempts = -1;
357 #if 0
358                 printk (KERN_ERR "motor_on failed, turning motor off\n");
359                 fd_motor_off (nr);
360                 return 0;
361 #else
362                 printk (KERN_WARNING "DSKRDY not set after 1.5 seconds - assuming drive is spinning notwithstanding\n");
363 #endif
364         }
365
366         return 1;
367 }
368
369 static void fd_motor_off(unsigned long drive)
370 {
371         long calledfromint;
372 #ifdef MODULE
373         long decusecount;
374
375         decusecount = drive & 0x40000000;
376 #endif
377         calledfromint = drive & 0x80000000;
378         drive&=3;
379         if (calledfromint && !try_fdc(drive)) {
380                 /* We would be blocked in an interrupt, so try again later */
381                 motor_off_timer[drive].expires = jiffies + 1;
382                 add_timer(motor_off_timer + drive);
383                 return;
384         }
385         unit[drive].motor = 0;
386         fd_select(drive);
387         udelay (1);
388         fd_deselect(drive);
389
390 #ifdef MODULE
391 /*
392   this is the last interrupt for any drive access, happens after
393   release (from floppy_off). So we have to wait until now to decrease
394   the use count.
395 */
396         if (decusecount)
397                 MOD_DEC_USE_COUNT;
398 #endif
399 }
400
401 static void floppy_off (unsigned int nr)
402 {
403         int drive;
404
405         drive = nr & 3;
406         /* called this way it is always from interrupt */
407         motor_off_timer[drive].data = nr | 0x80000000;
408         mod_timer(motor_off_timer + drive, jiffies + 3*HZ);
409 }
410
411 static int fd_calibrate(int drive)
412 {
413         unsigned char prb;
414         int n;
415
416         drive &= 3;
417         get_fdc(drive);
418         if (!fd_motor_on (drive))
419                 return 0;
420         fd_select (drive);
421         prb = ciab.prb;
422         prb |= DSKSIDE;
423         prb &= ~DSKDIREC;
424         ciab.prb = prb;
425         for (n = unit[drive].type->tracks/2; n != 0; --n) {
426                 if (ciaa.pra & DSKTRACK0)
427                         break;
428                 prb &= ~DSKSTEP;
429                 ciab.prb = prb;
430                 prb |= DSKSTEP;
431                 udelay (2);
432                 ciab.prb = prb;
433                 ms_delay(unit[drive].type->step_delay);
434         }
435         ms_delay (unit[drive].type->settle_time);
436         prb |= DSKDIREC;
437         n = unit[drive].type->tracks + 20;
438         for (;;) {
439                 prb &= ~DSKSTEP;
440                 ciab.prb = prb;
441                 prb |= DSKSTEP;
442                 udelay (2);
443                 ciab.prb = prb;
444                 ms_delay(unit[drive].type->step_delay + 1);
445                 if ((ciaa.pra & DSKTRACK0) == 0)
446                         break;
447                 if (--n == 0) {
448                         printk (KERN_ERR "fd%d: calibrate failed, turning motor off\n", drive);
449                         fd_motor_off (drive);
450                         unit[drive].track = -1;
451                         rel_fdc();
452                         return 0;
453                 }
454         }
455         unit[drive].track = 0;
456         ms_delay(unit[drive].type->settle_time);
457
458         rel_fdc();
459         fd_deselect(drive);
460         return 1;
461 }
462
463 static int fd_seek(int drive, int track)
464 {
465         unsigned char prb;
466         int cnt;
467
468 #ifdef DEBUG
469         printk("seeking drive %d to track %d\n",drive,track);
470 #endif
471         drive &= 3;
472         get_fdc(drive);
473         if (unit[drive].track == track) {
474                 rel_fdc();
475                 return 1;
476         }
477         if (!fd_motor_on(drive)) {
478                 rel_fdc();
479                 return 0;
480         }
481         if (unit[drive].track < 0 && !fd_calibrate(drive)) {
482                 rel_fdc();
483                 return 0;
484         }
485
486         fd_select (drive);
487         cnt = unit[drive].track/2 - track/2;
488         prb = ciab.prb;
489         prb |= DSKSIDE | DSKDIREC;
490         if (track % 2 != 0)
491                 prb &= ~DSKSIDE;
492         if (cnt < 0) {
493                 cnt = - cnt;
494                 prb &= ~DSKDIREC;
495         }
496         ciab.prb = prb;
497         if (track % 2 != unit[drive].track % 2)
498                 ms_delay (unit[drive].type->side_time);
499         unit[drive].track = track;
500         if (cnt == 0) {
501                 rel_fdc();
502                 fd_deselect(drive);
503                 return 1;
504         }
505         do {
506                 prb &= ~DSKSTEP;
507                 ciab.prb = prb;
508                 prb |= DSKSTEP;
509                 udelay (1);
510                 ciab.prb = prb;
511                 ms_delay (unit[drive].type->step_delay);
512         } while (--cnt != 0);
513         ms_delay (unit[drive].type->settle_time);
514
515         rel_fdc();
516         fd_deselect(drive);
517         return 1;
518 }
519
520 static unsigned long fd_get_drive_id(int drive)
521 {
522         int i;
523         ulong id = 0;
524
525         drive&=3;
526         get_fdc(drive);
527         /* set up for ID */
528         MOTOR_ON;
529         udelay(2);
530         SELECT(SELMASK(drive));
531         udelay(2);
532         DESELECT(SELMASK(drive));
533         udelay(2);
534         MOTOR_OFF;
535         udelay(2);
536         SELECT(SELMASK(drive));
537         udelay(2);
538         DESELECT(SELMASK(drive));
539         udelay(2);
540
541         /* loop and read disk ID */
542         for (i=0; i<32; i++) {
543                 SELECT(SELMASK(drive));
544                 udelay(2);
545
546                 /* read and store value of DSKRDY */
547                 id <<= 1;
548                 id |= (ciaa.pra & DSKRDY) ? 0 : 1;      /* cia regs are low-active! */
549
550                 DESELECT(SELMASK(drive));
551         }
552
553         rel_fdc();
554
555         /*
556          * RB: At least A500/A2000's df0: don't identify themselves.
557          * As every (real) Amiga has at least a 3.5" DD drive as df0:
558          * we default to that if df0: doesn't identify as a certain
559          * type.
560          */
561         if(drive == 0 && id == FD_NODRIVE)
562         {
563                 id = fd_def_df0;
564                 printk(KERN_NOTICE "fd: drive 0 didn't identify, setting default %08lx\n", (ulong)fd_def_df0);
565         }
566         /* return the ID value */
567         return (id);
568 }
569
570 static irqreturn_t fd_block_done(int irq, void *dummy, struct pt_regs *fp)
571 {
572         if (block_flag)
573                 custom.dsklen = 0x4000;
574
575         if (block_flag == 2) { /* writing */
576                 writepending = 2;
577                 post_write_timer.expires = jiffies + 1; /* at least 2 ms */
578                 post_write_timer.data = selected;
579                 add_timer(&post_write_timer);
580         }
581         else {                /* reading */
582                 block_flag = 0;
583                 wake_up (&wait_fd_block);
584         }
585         return IRQ_HANDLED;
586 }
587
588 static void raw_read(int drive)
589 {
590         drive&=3;
591         get_fdc(drive);
592         while (block_flag)
593                 sleep_on(&wait_fd_block);
594         fd_select(drive);
595         /* setup adkcon bits correctly */
596         custom.adkcon = ADK_MSBSYNC;
597         custom.adkcon = ADK_SETCLR|ADK_WORDSYNC|ADK_FAST;
598
599         custom.dsksync = MFM_SYNC;
600
601         custom.dsklen = 0;
602         custom.dskptr = (u_char *)ZTWO_PADDR((u_char *)raw_buf);
603         custom.dsklen = unit[drive].type->read_size/sizeof(short) | DSKLEN_DMAEN;
604         custom.dsklen = unit[drive].type->read_size/sizeof(short) | DSKLEN_DMAEN;
605
606         block_flag = 1;
607
608         while (block_flag)
609                 sleep_on (&wait_fd_block);
610
611         custom.dsklen = 0;
612         fd_deselect(drive);
613         rel_fdc();
614 }
615
616 static int raw_write(int drive)
617 {
618         ushort adk;
619
620         drive&=3;
621         get_fdc(drive); /* corresponds to rel_fdc() in post_write() */
622         if ((ciaa.pra & DSKPROT) == 0) {
623                 rel_fdc();
624                 return 0;
625         }
626         while (block_flag)
627                 sleep_on(&wait_fd_block);
628         fd_select(drive);
629         /* clear adkcon bits */
630         custom.adkcon = ADK_PRECOMP1|ADK_PRECOMP0|ADK_WORDSYNC|ADK_MSBSYNC;
631         /* set appropriate adkcon bits */
632         adk = ADK_SETCLR|ADK_FAST;
633         if ((ulong)unit[drive].track >= unit[drive].type->precomp2)
634                 adk |= ADK_PRECOMP1;
635         else if ((ulong)unit[drive].track >= unit[drive].type->precomp1)
636                 adk |= ADK_PRECOMP0;
637         custom.adkcon = adk;
638
639         custom.dsklen = DSKLEN_WRITE;
640         custom.dskptr = (u_char *)ZTWO_PADDR((u_char *)raw_buf);
641         custom.dsklen = unit[drive].type->write_size/sizeof(short) | DSKLEN_DMAEN|DSKLEN_WRITE;
642         custom.dsklen = unit[drive].type->write_size/sizeof(short) | DSKLEN_DMAEN|DSKLEN_WRITE;
643
644         block_flag = 2;
645         return 1;
646 }
647
648 /*
649  * to be called at least 2ms after the write has finished but before any
650  * other access to the hardware.
651  */
652 static void post_write (unsigned long drive)
653 {
654 #ifdef DEBUG
655         printk("post_write for drive %ld\n",drive);
656 #endif
657         drive &= 3;
658         custom.dsklen = 0;
659         block_flag = 0;
660         writepending = 0;
661         writefromint = 0;
662         unit[drive].dirty = 0;
663         wake_up(&wait_fd_block);
664         fd_deselect(drive);
665         rel_fdc(); /* corresponds to get_fdc() in raw_write */
666 }
667
668
669 /*
670  * The following functions are to convert the block contents into raw data
671  * written to disk and vice versa.
672  * (Add other formats here ;-))
673  */
674
675 static unsigned long scan_sync(unsigned long raw, unsigned long end)
676 {
677         ushort *ptr = (ushort *)raw, *endp = (ushort *)end;
678
679         while (ptr < endp && *ptr++ != 0x4489)
680                 ;
681         if (ptr < endp) {
682                 while (*ptr == 0x4489 && ptr < endp)
683                         ptr++;
684                 return (ulong)ptr;
685         }
686         return 0;
687 }
688
689 static inline unsigned long checksum(unsigned long *addr, int len)
690 {
691         unsigned long csum = 0;
692
693         len /= sizeof(*addr);
694         while (len-- > 0)
695                 csum ^= *addr++;
696         csum = ((csum>>1) & 0x55555555)  ^  (csum & 0x55555555);
697
698         return csum;
699 }
700
701 static unsigned long decode (unsigned long *data, unsigned long *raw,
702                              int len)
703 {
704         ulong *odd, *even;
705
706         /* convert length from bytes to longwords */
707         len >>= 2;
708         odd = raw;
709         even = odd + len;
710
711         /* prepare return pointer */
712         raw += len * 2;
713
714         do {
715                 *data++ = ((*odd++ & 0x55555555) << 1) | (*even++ & 0x55555555);
716         } while (--len != 0);
717
718         return (ulong)raw;
719 }
720
721 struct header {
722         unsigned char magic;
723         unsigned char track;
724         unsigned char sect;
725         unsigned char ord;
726         unsigned char labels[16];
727         unsigned long hdrchk;
728         unsigned long datachk;
729 };
730
731 static int amiga_read(int drive)
732 {
733         unsigned long raw;
734         unsigned long end;
735         int scnt;
736         unsigned long csum;
737         struct header hdr;
738
739         drive&=3;
740         raw = (long) raw_buf;
741         end = raw + unit[drive].type->read_size;
742
743         for (scnt = 0;scnt < unit[drive].dtype->sects * unit[drive].type->sect_mult; scnt++) {
744                 if (!(raw = scan_sync(raw, end))) {
745                         printk (KERN_INFO "can't find sync for sector %d\n", scnt);
746                         return MFM_NOSYNC;
747                 }
748
749                 raw = decode ((ulong *)&hdr.magic, (ulong *)raw, 4);
750                 raw = decode ((ulong *)&hdr.labels, (ulong *)raw, 16);
751                 raw = decode ((ulong *)&hdr.hdrchk, (ulong *)raw, 4);
752                 raw = decode ((ulong *)&hdr.datachk, (ulong *)raw, 4);
753                 csum = checksum((ulong *)&hdr,
754                                 (char *)&hdr.hdrchk-(char *)&hdr);
755
756 #ifdef DEBUG
757                 printk ("(%x,%d,%d,%d) (%lx,%lx,%lx,%lx) %lx %lx\n",
758                         hdr.magic, hdr.track, hdr.sect, hdr.ord,
759                         *(ulong *)&hdr.labels[0], *(ulong *)&hdr.labels[4],
760                         *(ulong *)&hdr.labels[8], *(ulong *)&hdr.labels[12],
761                         hdr.hdrchk, hdr.datachk);
762 #endif
763
764                 if (hdr.hdrchk != csum) {
765                         printk(KERN_INFO "MFM_HEADER: %08lx,%08lx\n", hdr.hdrchk, csum);
766                         return MFM_HEADER;
767                 }
768
769                 /* verify track */
770                 if (hdr.track != unit[drive].track) {
771                         printk(KERN_INFO "MFM_TRACK: %d, %d\n", hdr.track, unit[drive].track);
772                         return MFM_TRACK;
773                 }
774
775                 raw = decode ((ulong *)(unit[drive].trackbuf + hdr.sect*512),
776                               (ulong *)raw, 512);
777                 csum = checksum((ulong *)(unit[drive].trackbuf + hdr.sect*512), 512);
778
779                 if (hdr.datachk != csum) {
780                         printk(KERN_INFO "MFM_DATA: (%x:%d:%d:%d) sc=%d %lx, %lx\n",
781                                hdr.magic, hdr.track, hdr.sect, hdr.ord, scnt,
782                                hdr.datachk, csum);
783                         printk (KERN_INFO "data=(%lx,%lx,%lx,%lx)\n",
784                                 ((ulong *)(unit[drive].trackbuf+hdr.sect*512))[0],
785                                 ((ulong *)(unit[drive].trackbuf+hdr.sect*512))[1],
786                                 ((ulong *)(unit[drive].trackbuf+hdr.sect*512))[2],
787                                 ((ulong *)(unit[drive].trackbuf+hdr.sect*512))[3]);
788                         return MFM_DATA;
789                 }
790         }
791
792         return 0;
793 }
794
795 static void encode(unsigned long data, unsigned long *dest)
796 {
797         unsigned long data2;
798
799         data &= 0x55555555;
800         data2 = data ^ 0x55555555;
801         data |= ((data2 >> 1) | 0x80000000) & (data2 << 1);
802
803         if (*(dest - 1) & 0x00000001)
804                 data &= 0x7FFFFFFF;
805
806         *dest = data;
807 }
808
809 static void encode_block(unsigned long *dest, unsigned long *src, int len)
810 {
811         int cnt, to_cnt = 0;
812         unsigned long data;
813
814         /* odd bits */
815         for (cnt = 0; cnt < len / 4; cnt++) {
816                 data = src[cnt] >> 1;
817                 encode(data, dest + to_cnt++);
818         }
819
820         /* even bits */
821         for (cnt = 0; cnt < len / 4; cnt++) {
822                 data = src[cnt];
823                 encode(data, dest + to_cnt++);
824         }
825 }
826
827 static unsigned long *putsec(int disk, unsigned long *raw, int cnt)
828 {
829         struct header hdr;
830         int i;
831
832         disk&=3;
833         *raw = (raw[-1]&1) ? 0x2AAAAAAA : 0xAAAAAAAA;
834         raw++;
835         *raw++ = 0x44894489;
836
837         hdr.magic = 0xFF;
838         hdr.track = unit[disk].track;
839         hdr.sect = cnt;
840         hdr.ord = unit[disk].dtype->sects * unit[disk].type->sect_mult - cnt;
841         for (i = 0; i < 16; i++)
842                 hdr.labels[i] = 0;
843         hdr.hdrchk = checksum((ulong *)&hdr,
844                               (char *)&hdr.hdrchk-(char *)&hdr);
845         hdr.datachk = checksum((ulong *)(unit[disk].trackbuf+cnt*512), 512);
846
847         encode_block(raw, (ulong *)&hdr.magic, 4);
848         raw += 2;
849         encode_block(raw, (ulong *)&hdr.labels, 16);
850         raw += 8;
851         encode_block(raw, (ulong *)&hdr.hdrchk, 4);
852         raw += 2;
853         encode_block(raw, (ulong *)&hdr.datachk, 4);
854         raw += 2;
855         encode_block(raw, (ulong *)(unit[disk].trackbuf+cnt*512), 512);
856         raw += 256;
857
858         return raw;
859 }
860
861 static void amiga_write(int disk)
862 {
863         unsigned int cnt;
864         unsigned long *ptr = (unsigned long *)raw_buf;
865
866         disk&=3;
867         /* gap space */
868         for (cnt = 0; cnt < 415 * unit[disk].type->sect_mult; cnt++)
869                 *ptr++ = 0xaaaaaaaa;
870
871         /* sectors */
872         for (cnt = 0; cnt < unit[disk].dtype->sects * unit[disk].type->sect_mult; cnt++)
873                 ptr = putsec (disk, ptr, cnt);
874         *(ushort *)ptr = (ptr[-1]&1) ? 0x2AA8 : 0xAAA8;
875 }
876
877
878 struct dos_header {
879         unsigned char track,   /* 0-80 */
880                 side,    /* 0-1 */
881                 sec,     /* 0-...*/
882                 len_desc;/* 2 */
883         unsigned short crc;     /* on 68000 we got an alignment problem, 
884                                    but this compiler solves it  by adding silently 
885                                    adding a pad byte so data won't fit
886                                    and this took about 3h to discover.... */
887         unsigned char gap1[22];     /* for longword-alignedness (0x4e) */
888 };
889
890 /* crc routines are borrowed from the messydos-handler  */
891
892 /* excerpt from the messydos-device           
893 ; The CRC is computed not only over the actual data, but including
894 ; the SYNC mark (3 * $a1) and the 'ID/DATA - Address Mark' ($fe/$fb).
895 ; As we don't read or encode these fields into our buffers, we have to
896 ; preload the registers containing the CRC with the values they would have
897 ; after stepping over these fields.
898 ;
899 ; How CRCs "really" work:
900 ;
901 ; First, you should regard a bitstring as a series of coefficients of
902 ; polynomials. We calculate with these polynomials in modulo-2
903 ; arithmetic, in which both add and subtract are done the same as
904 ; exclusive-or. Now, we modify our data (a very long polynomial) in
905 ; such a way that it becomes divisible by the CCITT-standard 16-bit
906 ;                16   12   5
907 ; polynomial:   x  + x  + x + 1, represented by $11021. The easiest
908 ; way to do this would be to multiply (using proper arithmetic) our
909 ; datablock with $11021. So we have:
910 ;   data * $11021                =
911 ;   data * ($10000 + $1021)      =
912 ;   data * $10000 + data * $1021
913 ; The left part of this is simple: Just add two 0 bytes. But then
914 ; the right part (data $1021) remains difficult and even could have
915 ; a carry into the left part. The solution is to use a modified
916 ; multiplication, which has a result that is not correct, but with
917 ; a difference of any multiple of $11021. We then only need to keep
918 ; the 16 least significant bits of the result.
919 ;
920 ; The following algorithm does this for us:
921 ;
922 ;   unsigned char *data, c, crclo, crchi;
923 ;   while (not done) {
924 ;       c = *data++ + crchi;
925 ;       crchi = (@ c) >> 8 + crclo;
926 ;       crclo = @ c;
927 ;   }
928 ;
929 ; Remember, + is done with EOR, the @ operator is in two tables (high
930 ; and low byte separately), which is calculated as
931 ;
932 ;      $1021 * (c & $F0)
933 ;  xor $1021 * (c & $0F)
934 ;  xor $1021 * (c >> 4)         (* is regular multiplication)
935 ;
936 ;
937 ; Anyway, the end result is the same as the remainder of the division of
938 ; the data by $11021. I am afraid I need to study theory a bit more...
939
940
941 my only works was to code this from manx to C....
942
943 */
944
945 static ushort dos_crc(void * data_a3, int data_d0, int data_d1, int data_d3)
946 {
947         static unsigned char CRCTable1[] = {
948                 0x00,0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x81,0x91,0xa1,0xb1,0xc1,0xd1,0xe1,0xf1,
949                 0x12,0x02,0x32,0x22,0x52,0x42,0x72,0x62,0x93,0x83,0xb3,0xa3,0xd3,0xc3,0xf3,0xe3,
950                 0x24,0x34,0x04,0x14,0x64,0x74,0x44,0x54,0xa5,0xb5,0x85,0x95,0xe5,0xf5,0xc5,0xd5,
951                 0x36,0x26,0x16,0x06,0x76,0x66,0x56,0x46,0xb7,0xa7,0x97,0x87,0xf7,0xe7,0xd7,0xc7,
952                 0x48,0x58,0x68,0x78,0x08,0x18,0x28,0x38,0xc9,0xd9,0xe9,0xf9,0x89,0x99,0xa9,0xb9,
953                 0x5a,0x4a,0x7a,0x6a,0x1a,0x0a,0x3a,0x2a,0xdb,0xcb,0xfb,0xeb,0x9b,0x8b,0xbb,0xab,
954                 0x6c,0x7c,0x4c,0x5c,0x2c,0x3c,0x0c,0x1c,0xed,0xfd,0xcd,0xdd,0xad,0xbd,0x8d,0x9d,
955                 0x7e,0x6e,0x5e,0x4e,0x3e,0x2e,0x1e,0x0e,0xff,0xef,0xdf,0xcf,0xbf,0xaf,0x9f,0x8f,
956                 0x91,0x81,0xb1,0xa1,0xd1,0xc1,0xf1,0xe1,0x10,0x00,0x30,0x20,0x50,0x40,0x70,0x60,
957                 0x83,0x93,0xa3,0xb3,0xc3,0xd3,0xe3,0xf3,0x02,0x12,0x22,0x32,0x42,0x52,0x62,0x72,
958                 0xb5,0xa5,0x95,0x85,0xf5,0xe5,0xd5,0xc5,0x34,0x24,0x14,0x04,0x74,0x64,0x54,0x44,
959                 0xa7,0xb7,0x87,0x97,0xe7,0xf7,0xc7,0xd7,0x26,0x36,0x06,0x16,0x66,0x76,0x46,0x56,
960                 0xd9,0xc9,0xf9,0xe9,0x99,0x89,0xb9,0xa9,0x58,0x48,0x78,0x68,0x18,0x08,0x38,0x28,
961                 0xcb,0xdb,0xeb,0xfb,0x8b,0x9b,0xab,0xbb,0x4a,0x5a,0x6a,0x7a,0x0a,0x1a,0x2a,0x3a,
962                 0xfd,0xed,0xdd,0xcd,0xbd,0xad,0x9d,0x8d,0x7c,0x6c,0x5c,0x4c,0x3c,0x2c,0x1c,0x0c,
963                 0xef,0xff,0xcf,0xdf,0xaf,0xbf,0x8f,0x9f,0x6e,0x7e,0x4e,0x5e,0x2e,0x3e,0x0e,0x1e
964         };
965
966         static unsigned char CRCTable2[] = {
967                 0x00,0x21,0x42,0x63,0x84,0xa5,0xc6,0xe7,0x08,0x29,0x4a,0x6b,0x8c,0xad,0xce,0xef,
968                 0x31,0x10,0x73,0x52,0xb5,0x94,0xf7,0xd6,0x39,0x18,0x7b,0x5a,0xbd,0x9c,0xff,0xde,
969                 0x62,0x43,0x20,0x01,0xe6,0xc7,0xa4,0x85,0x6a,0x4b,0x28,0x09,0xee,0xcf,0xac,0x8d,
970                 0x53,0x72,0x11,0x30,0xd7,0xf6,0x95,0xb4,0x5b,0x7a,0x19,0x38,0xdf,0xfe,0x9d,0xbc,
971                 0xc4,0xe5,0x86,0xa7,0x40,0x61,0x02,0x23,0xcc,0xed,0x8e,0xaf,0x48,0x69,0x0a,0x2b,
972                 0xf5,0xd4,0xb7,0x96,0x71,0x50,0x33,0x12,0xfd,0xdc,0xbf,0x9e,0x79,0x58,0x3b,0x1a,
973                 0xa6,0x87,0xe4,0xc5,0x22,0x03,0x60,0x41,0xae,0x8f,0xec,0xcd,0x2a,0x0b,0x68,0x49,
974                 0x97,0xb6,0xd5,0xf4,0x13,0x32,0x51,0x70,0x9f,0xbe,0xdd,0xfc,0x1b,0x3a,0x59,0x78,
975                 0x88,0xa9,0xca,0xeb,0x0c,0x2d,0x4e,0x6f,0x80,0xa1,0xc2,0xe3,0x04,0x25,0x46,0x67,
976                 0xb9,0x98,0xfb,0xda,0x3d,0x1c,0x7f,0x5e,0xb1,0x90,0xf3,0xd2,0x35,0x14,0x77,0x56,
977                 0xea,0xcb,0xa8,0x89,0x6e,0x4f,0x2c,0x0d,0xe2,0xc3,0xa0,0x81,0x66,0x47,0x24,0x05,
978                 0xdb,0xfa,0x99,0xb8,0x5f,0x7e,0x1d,0x3c,0xd3,0xf2,0x91,0xb0,0x57,0x76,0x15,0x34,
979                 0x4c,0x6d,0x0e,0x2f,0xc8,0xe9,0x8a,0xab,0x44,0x65,0x06,0x27,0xc0,0xe1,0x82,0xa3,
980                 0x7d,0x5c,0x3f,0x1e,0xf9,0xd8,0xbb,0x9a,0x75,0x54,0x37,0x16,0xf1,0xd0,0xb3,0x92,
981                 0x2e,0x0f,0x6c,0x4d,0xaa,0x8b,0xe8,0xc9,0x26,0x07,0x64,0x45,0xa2,0x83,0xe0,0xc1,
982                 0x1f,0x3e,0x5d,0x7c,0x9b,0xba,0xd9,0xf8,0x17,0x36,0x55,0x74,0x93,0xb2,0xd1,0xf0
983         };
984
985 /* look at the asm-code - what looks in C a bit strange is almost as good as handmade */
986         register int i;
987         register unsigned char *CRCT1, *CRCT2, *data, c, crch, crcl;
988
989         CRCT1=CRCTable1;
990         CRCT2=CRCTable2;
991         data=data_a3;
992         crcl=data_d1;
993         crch=data_d0;
994         for (i=data_d3; i>=0; i--) {
995                 c = (*data++) ^ crch;
996                 crch = CRCT1[c] ^ crcl;
997                 crcl = CRCT2[c];
998         }
999         return (crch<<8)|crcl;
1000 }
1001
1002 static inline ushort dos_hdr_crc (struct dos_header *hdr)
1003 {
1004         return dos_crc(&(hdr->track), 0xb2, 0x30, 3); /* precomputed magic */
1005 }
1006
1007 static inline ushort dos_data_crc(unsigned char *data)
1008 {
1009         return dos_crc(data, 0xe2, 0x95 ,511); /* precomputed magic */
1010 }
1011
1012 static inline unsigned char dos_decode_byte(ushort word)
1013 {
1014         register ushort w2;
1015         register unsigned char byte;
1016         register unsigned char *dec = mfmdecode;
1017
1018         w2=word;
1019         w2>>=8;
1020         w2&=127;
1021         byte = dec[w2];
1022         byte <<= 4;
1023         w2 = word & 127;
1024         byte |= dec[w2];
1025         return byte;
1026 }
1027
1028 static unsigned long dos_decode(unsigned char *data, unsigned short *raw, int len)
1029 {
1030         int i;
1031
1032         for (i = 0; i < len; i++)
1033                 *data++=dos_decode_byte(*raw++);
1034         return ((ulong)raw);
1035 }
1036
1037 #ifdef DEBUG
1038 static void dbg(unsigned long ptr)
1039 {
1040         printk("raw data @%08lx: %08lx, %08lx ,%08lx, %08lx\n", ptr,
1041                ((ulong *)ptr)[0], ((ulong *)ptr)[1],
1042                ((ulong *)ptr)[2], ((ulong *)ptr)[3]);
1043 }
1044 #endif
1045
1046 static int dos_read(int drive)
1047 {
1048         unsigned long end;
1049         unsigned long raw;
1050         int scnt;
1051         unsigned short crc,data_crc[2];
1052         struct dos_header hdr;
1053
1054         drive&=3;
1055         raw = (long) raw_buf;
1056         end = raw + unit[drive].type->read_size;
1057
1058         for (scnt=0; scnt < unit[drive].dtype->sects * unit[drive].type->sect_mult; scnt++) {
1059                 do { /* search for the right sync of each sec-hdr */
1060                         if (!(raw = scan_sync (raw, end))) {
1061                                 printk(KERN_INFO "dos_read: no hdr sync on "
1062                                        "track %d, unit %d for sector %d\n",
1063                                        unit[drive].track,drive,scnt);
1064                                 return MFM_NOSYNC;
1065                         }
1066 #ifdef DEBUG
1067                         dbg(raw);
1068 #endif
1069                 } while (*((ushort *)raw)!=0x5554); /* loop usually only once done */
1070                 raw+=2; /* skip over headermark */
1071                 raw = dos_decode((unsigned char *)&hdr,(ushort *) raw,8);
1072                 crc = dos_hdr_crc(&hdr);
1073
1074 #ifdef DEBUG
1075                 printk("(%3d,%d,%2d,%d) %x\n", hdr.track, hdr.side,
1076                        hdr.sec, hdr.len_desc, hdr.crc);
1077 #endif
1078
1079                 if (crc != hdr.crc) {
1080                         printk(KERN_INFO "dos_read: MFM_HEADER %04x,%04x\n",
1081                                hdr.crc, crc);
1082                         return MFM_HEADER;
1083                 }
1084                 if (hdr.track != unit[drive].track/unit[drive].type->heads) {
1085                         printk(KERN_INFO "dos_read: MFM_TRACK %d, %d\n",
1086                                hdr.track,
1087                                unit[drive].track/unit[drive].type->heads);
1088                         return MFM_TRACK;
1089                 }
1090
1091                 if (hdr.side != unit[drive].track%unit[drive].type->heads) {
1092                         printk(KERN_INFO "dos_read: MFM_SIDE %d, %d\n",
1093                                hdr.side,
1094                                unit[drive].track%unit[drive].type->heads);
1095                         return MFM_TRACK;
1096                 }
1097
1098                 if (hdr.len_desc != 2) {
1099                         printk(KERN_INFO "dos_read: unknown sector len "
1100                                "descriptor %d\n", hdr.len_desc);
1101                         return MFM_DATA;
1102                 }
1103 #ifdef DEBUG
1104                 printk("hdr accepted\n");
1105 #endif
1106                 if (!(raw = scan_sync (raw, end))) {
1107                         printk(KERN_INFO "dos_read: no data sync on track "
1108                                "%d, unit %d for sector%d, disk sector %d\n",
1109                                unit[drive].track, drive, scnt, hdr.sec);
1110                         return MFM_NOSYNC;
1111                 }
1112 #ifdef DEBUG
1113                 dbg(raw);
1114 #endif
1115
1116                 if (*((ushort *)raw)!=0x5545) {
1117                         printk(KERN_INFO "dos_read: no data mark after "
1118                                "sync (%d,%d,%d,%d) sc=%d\n",
1119                                hdr.track,hdr.side,hdr.sec,hdr.len_desc,scnt);
1120                         return MFM_NOSYNC;
1121                 }
1122
1123                 raw+=2;  /* skip data mark (included in checksum) */
1124                 raw = dos_decode((unsigned char *)(unit[drive].trackbuf + (hdr.sec - 1) * 512), (ushort *) raw, 512);
1125                 raw = dos_decode((unsigned char  *)data_crc,(ushort *) raw,4);
1126                 crc = dos_data_crc(unit[drive].trackbuf + (hdr.sec - 1) * 512);
1127
1128                 if (crc != data_crc[0]) {
1129                         printk(KERN_INFO "dos_read: MFM_DATA (%d,%d,%d,%d) "
1130                                "sc=%d, %x %x\n", hdr.track, hdr.side,
1131                                hdr.sec, hdr.len_desc, scnt,data_crc[0], crc);
1132                         printk(KERN_INFO "data=(%lx,%lx,%lx,%lx,...)\n",
1133                                ((ulong *)(unit[drive].trackbuf+(hdr.sec-1)*512))[0],
1134                                ((ulong *)(unit[drive].trackbuf+(hdr.sec-1)*512))[1],
1135                                ((ulong *)(unit[drive].trackbuf+(hdr.sec-1)*512))[2],
1136                                ((ulong *)(unit[drive].trackbuf+(hdr.sec-1)*512))[3]);
1137                         return MFM_DATA;
1138                 }
1139         }
1140         return 0;
1141 }
1142
1143 static inline ushort dos_encode_byte(unsigned char byte)
1144 {
1145         register unsigned char *enc, b2, b1;
1146         register ushort word;
1147
1148         enc=mfmencode;
1149         b1=byte;
1150         b2=b1>>4;
1151         b1&=15;
1152         word=enc[b2] <<8 | enc [b1];
1153         return (word|((word&(256|64)) ? 0: 128));
1154 }
1155
1156 static void dos_encode_block(ushort *dest, unsigned char *src, int len)
1157 {
1158         int i;
1159
1160         for (i = 0; i < len; i++) {
1161                 *dest=dos_encode_byte(*src++);
1162                 *dest|=((dest[-1]&1)||(*dest&0x4000))? 0: 0x8000;
1163                 dest++;
1164         }
1165 }
1166
1167 static unsigned long *ms_putsec(int drive, unsigned long *raw, int cnt)
1168 {
1169         static struct dos_header hdr={0,0,0,2,0,
1170           {78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78}};
1171         int i;
1172         static ushort crc[2]={0,0x4e4e};
1173
1174         drive&=3;
1175 /* id gap 1 */
1176 /* the MFM word before is always 9254 */
1177         for(i=0;i<6;i++)
1178                 *raw++=0xaaaaaaaa;
1179 /* 3 sync + 1 headermark */
1180         *raw++=0x44894489;
1181         *raw++=0x44895554;
1182
1183 /* fill in the variable parts of the header */
1184         hdr.track=unit[drive].track/unit[drive].type->heads;
1185         hdr.side=unit[drive].track%unit[drive].type->heads;
1186         hdr.sec=cnt+1;
1187         hdr.crc=dos_hdr_crc(&hdr);
1188
1189 /* header (without "magic") and id gap 2*/
1190         dos_encode_block((ushort *)raw,(unsigned char *) &hdr.track,28);
1191         raw+=14;
1192
1193 /*id gap 3 */
1194         for(i=0;i<6;i++)
1195                 *raw++=0xaaaaaaaa;
1196
1197 /* 3 syncs and 1 datamark */
1198         *raw++=0x44894489;
1199         *raw++=0x44895545;
1200
1201 /* data */
1202         dos_encode_block((ushort *)raw,
1203                          (unsigned char *)unit[drive].trackbuf+cnt*512,512);
1204         raw+=256;
1205
1206 /*data crc + jd's special gap (long words :-/) */
1207         crc[0]=dos_data_crc(unit[drive].trackbuf+cnt*512);
1208         dos_encode_block((ushort *) raw,(unsigned char *)crc,4);
1209         raw+=2;
1210
1211 /* data gap */
1212         for(i=0;i<38;i++)
1213                 *raw++=0x92549254;
1214
1215         return raw; /* wrote 652 MFM words */
1216 }
1217
1218 static void dos_write(int disk)
1219 {
1220         int cnt;
1221         unsigned long raw = (unsigned long) raw_buf;
1222         unsigned long *ptr=(unsigned long *)raw;
1223
1224         disk&=3;
1225 /* really gap4 + indexgap , but we write it first and round it up */
1226         for (cnt=0;cnt<425;cnt++)
1227                 *ptr++=0x92549254;
1228
1229 /* the following is just guessed */
1230         if (unit[disk].type->sect_mult==2)  /* check for HD-Disks */
1231                 for(cnt=0;cnt<473;cnt++)
1232                         *ptr++=0x92549254;
1233
1234 /* now the index marks...*/
1235         for (cnt=0;cnt<20;cnt++)
1236                 *ptr++=0x92549254;
1237         for (cnt=0;cnt<6;cnt++)
1238                 *ptr++=0xaaaaaaaa;
1239         *ptr++=0x52245224;
1240         *ptr++=0x52245552;
1241         for (cnt=0;cnt<20;cnt++)
1242                 *ptr++=0x92549254;
1243
1244 /* sectors */
1245         for(cnt = 0; cnt < unit[disk].dtype->sects * unit[disk].type->sect_mult; cnt++)
1246                 ptr=ms_putsec(disk,ptr,cnt);
1247
1248         *(ushort *)ptr = 0xaaa8; /* MFM word before is always 0x9254 */
1249 }
1250
1251 /*
1252  * Here comes the high level stuff (i.e. the filesystem interface)
1253  * and helper functions.
1254  * Normally this should be the only part that has to be adapted to
1255  * different kernel versions.
1256  */
1257
1258 /* FIXME: this assumes the drive is still spinning -
1259  * which is only true if we complete writing a track within three seconds
1260  */
1261 static void flush_track_callback(unsigned long nr)
1262 {
1263         nr&=3;
1264         writefromint = 1;
1265         if (!try_fdc(nr)) {
1266                 /* we might block in an interrupt, so try again later */
1267                 flush_track_timer[nr].expires = jiffies + 1;
1268                 add_timer(flush_track_timer + nr);
1269                 return;
1270         }
1271         get_fdc(nr);
1272         (*unit[nr].dtype->write_fkt)(nr);
1273         if (!raw_write(nr)) {
1274                 printk (KERN_NOTICE "floppy disk write protected\n");
1275                 writefromint = 0;
1276                 writepending = 0;
1277         }
1278         rel_fdc();
1279 }
1280
1281 static int non_int_flush_track (unsigned long nr)
1282 {
1283         unsigned long flags;
1284
1285         nr&=3;
1286         writefromint = 0;
1287         del_timer(&post_write_timer);
1288         get_fdc(nr);
1289         if (!fd_motor_on(nr)) {
1290                 writepending = 0;
1291                 rel_fdc();
1292                 return 0;
1293         }
1294         local_irq_save(flags);
1295         if (writepending != 2) {
1296                 local_irq_restore(flags);
1297                 (*unit[nr].dtype->write_fkt)(nr);
1298                 if (!raw_write(nr)) {
1299                         printk (KERN_NOTICE "floppy disk write protected "
1300                                 "in write!\n");
1301                         writepending = 0;
1302                         return 0;
1303                 }
1304                 while (block_flag == 2)
1305                         sleep_on (&wait_fd_block);
1306         }
1307         else {
1308                 local_irq_restore(flags);
1309                 ms_delay(2); /* 2 ms post_write delay */
1310                 post_write(nr);
1311         }
1312         rel_fdc();
1313         return 1;
1314 }
1315
1316 static int get_track(int drive, int track)
1317 {
1318         int error, errcnt;
1319
1320         drive&=3;
1321         if (unit[drive].track == track)
1322                 return 0;
1323         get_fdc(drive);
1324         if (!fd_motor_on(drive)) {
1325                 rel_fdc();
1326                 return -1;
1327         }
1328
1329         if (unit[drive].dirty == 1) {
1330                 del_timer (flush_track_timer + drive);
1331                 non_int_flush_track (drive);
1332         }
1333         errcnt = 0;
1334         while (errcnt < MAX_ERRORS) {
1335                 if (!fd_seek(drive, track))
1336                         return -1;
1337                 raw_read(drive);
1338                 error = (*unit[drive].dtype->read_fkt)(drive);
1339                 if (error == 0) {
1340                         rel_fdc();
1341                         return 0;
1342                 }
1343                 /* Read Error Handling: recalibrate and try again */
1344                 unit[drive].track = -1;
1345                 errcnt++;
1346         }
1347         rel_fdc();
1348         return -1;
1349 }
1350
1351 static void redo_fd_request(void)
1352 {
1353         unsigned int cnt, block, track, sector;
1354         int drive;
1355         struct amiga_floppy_struct *floppy;
1356         char *data;
1357         unsigned long flags;
1358
1359  repeat:
1360         if (!CURRENT) {
1361                 /* Nothing left to do */
1362                 return;
1363         }
1364
1365         floppy = CURRENT->rq_disk->private_data;
1366         drive = floppy - unit;
1367
1368         /* Here someone could investigate to be more efficient */
1369         for (cnt = 0; cnt < CURRENT->current_nr_sectors; cnt++) { 
1370 #ifdef DEBUG
1371                 printk("fd: sector %ld + %d requested for %s\n",
1372                        CURRENT->sector,cnt,
1373                        (CURRENT->cmd==READ)?"read":"write");
1374 #endif
1375                 block = CURRENT->sector + cnt;
1376                 if ((int)block > floppy->blocks) {
1377                         end_request(CURRENT, 0);
1378                         goto repeat;
1379                 }
1380
1381                 track = block / (floppy->dtype->sects * floppy->type->sect_mult);
1382                 sector = block % (floppy->dtype->sects * floppy->type->sect_mult);
1383                 data = CURRENT->buffer + 512 * cnt;
1384 #ifdef DEBUG
1385                 printk("access to track %d, sector %d, with buffer at "
1386                        "0x%08lx\n", track, sector, data);
1387 #endif
1388
1389                 if ((rq_data_dir(CURRENT) != READ) && (rq_data_dir(CURRENT) != WRITE)) {
1390                         printk(KERN_WARNING "do_fd_request: unknown command\n");
1391                         end_request(CURRENT, 0);
1392                         goto repeat;
1393                 }
1394                 if (get_track(drive, track) == -1) {
1395                         end_request(CURRENT, 0);
1396                         goto repeat;
1397                 }
1398
1399                 switch (rq_data_dir(CURRENT)) {
1400                 case READ:
1401                         memcpy(data, floppy->trackbuf + sector * 512, 512);
1402                         break;
1403
1404                 case WRITE:
1405                         memcpy(floppy->trackbuf + sector * 512, data, 512);
1406
1407                         /* keep the drive spinning while writes are scheduled */
1408                         if (!fd_motor_on(drive)) {
1409                                 end_request(CURRENT, 0);
1410                                 goto repeat;
1411                         }
1412                         /*
1413                          * setup a callback to write the track buffer
1414                          * after a short (1 tick) delay.
1415                          */
1416                         local_irq_save(flags);
1417
1418                         floppy->dirty = 1;
1419                         /* reset the timer */
1420                         mod_timer (flush_track_timer + drive, jiffies + 1);
1421                         local_irq_restore(flags);
1422                         break;
1423                 }
1424         }
1425         CURRENT->nr_sectors -= CURRENT->current_nr_sectors;
1426         CURRENT->sector += CURRENT->current_nr_sectors;
1427
1428         end_request(CURRENT, 1);
1429         goto repeat;
1430 }
1431
1432 static void do_fd_request(request_queue_t * q)
1433 {
1434         redo_fd_request();
1435 }
1436
1437 static int fd_ioctl(struct inode *inode, struct file *filp,
1438                     unsigned int cmd, unsigned long param)
1439 {
1440         int drive = iminor(inode) & 3;
1441         static struct floppy_struct getprm;
1442
1443         switch(cmd){
1444         case HDIO_GETGEO:
1445         {
1446                 struct hd_geometry loc;
1447                 loc.heads = unit[drive].type->heads;
1448                 loc.sectors = unit[drive].dtype->sects * unit[drive].type->sect_mult;
1449                 loc.cylinders = unit[drive].type->tracks;
1450                 loc.start = 0;
1451                 if (copy_to_user((void *)param, (void *)&loc,
1452                                  sizeof(struct hd_geometry)))
1453                         return -EFAULT;
1454                 break;
1455         }
1456         case FDFMTBEG:
1457                 get_fdc(drive);
1458                 if (fd_ref[drive] > 1) {
1459                         rel_fdc();
1460                         return -EBUSY;
1461                 }
1462                 fsync_bdev(inode->i_bdev);
1463                 if (fd_motor_on(drive) == 0) {
1464                         rel_fdc();
1465                         return -ENODEV;
1466                 }
1467                 if (fd_calibrate(drive) == 0) {
1468                         rel_fdc();
1469                         return -ENXIO;
1470                 }
1471                 floppy_off(drive);
1472                 rel_fdc();
1473                 break;
1474         case FDFMTTRK:
1475                 if (param < unit[drive].type->tracks * unit[drive].type->heads)
1476                 {
1477                         get_fdc(drive);
1478                         if (fd_seek(drive,param) != 0){
1479                                 memset(unit[drive].trackbuf, FD_FILL_BYTE,
1480                                        unit[drive].dtype->sects * unit[drive].type->sect_mult * 512);
1481                                 non_int_flush_track(drive);
1482                         }
1483                         floppy_off(drive);
1484                         rel_fdc();
1485                 }
1486                 else
1487                         return -EINVAL;
1488                 break;
1489         case FDFMTEND:
1490                 floppy_off(drive);
1491                 invalidate_bdev(inode->i_bdev, 0);
1492                 break;
1493         case FDGETPRM:
1494                 memset((void *)&getprm, 0, sizeof (getprm));
1495                 getprm.track=unit[drive].type->tracks;
1496                 getprm.head=unit[drive].type->heads;
1497                 getprm.sect=unit[drive].dtype->sects * unit[drive].type->sect_mult;
1498                 getprm.size=unit[drive].blocks;
1499                 if (copy_to_user((void *)param,
1500                                  (void *)&getprm,
1501                                  sizeof(struct floppy_struct)))
1502                         return -EFAULT;
1503                 break;
1504         case FDSETPRM:
1505         case FDDEFPRM:
1506                 return -EINVAL;
1507         case FDFLUSH: /* unconditionally, even if not needed */
1508                 del_timer (flush_track_timer + drive);
1509                 non_int_flush_track(drive);
1510                 break;
1511 #ifdef RAW_IOCTL
1512         case IOCTL_RAW_TRACK:
1513                 if (copy_to_user((void *)param, raw_buf,
1514                                  unit[drive].type->read_size))
1515                         return -EFAULT;
1516                 else
1517                         return unit[drive].type->read_size;
1518 #endif
1519         default:
1520                 printk(KERN_DEBUG "fd_ioctl: unknown cmd %d for drive %d.",
1521                        cmd, drive);
1522                 return -ENOSYS;
1523         }
1524         return 0;
1525 }
1526
1527 static void fd_probe(int dev)
1528 {
1529         unsigned long code;
1530         int type;
1531         int drive;
1532
1533         drive = dev & 3;
1534         code = fd_get_drive_id(drive);
1535
1536         /* get drive type */
1537         for (type = 0; type < num_dr_types; type++)
1538                 if (drive_types[type].code == code)
1539                         break;
1540
1541         if (type >= num_dr_types) {
1542                 printk(KERN_WARNING "fd_probe: unsupported drive type "
1543                        "%08lx found\n", code);
1544                 unit[drive].type = &drive_types[num_dr_types-1]; /* FD_NODRIVE */
1545                 return;
1546         }
1547
1548         unit[drive].type = drive_types + type;
1549         unit[drive].track = -1;
1550
1551         unit[drive].disk = -1;
1552         unit[drive].motor = 0;
1553         unit[drive].busy = 0;
1554         unit[drive].status = -1;
1555 }
1556
1557 /*
1558  * floppy_open check for aliasing (/dev/fd0 can be the same as
1559  * /dev/PS0 etc), and disallows simultaneous access to the same
1560  * drive with different device numbers.
1561  */
1562 static int floppy_open(struct inode *inode, struct file *filp)
1563 {
1564         int drive = iminor(inode) & 3;
1565         int system =  (iminor(inode) & 4) >> 2;
1566         int old_dev;
1567         unsigned long flags;
1568
1569         old_dev = fd_device[drive];
1570
1571         if (fd_ref[drive] && old_dev != system)
1572                 return -EBUSY;
1573
1574         if (filp && filp->f_mode & 3) {
1575                 check_disk_change(inode->i_bdev);
1576                 if (filp->f_mode & 2 ) {
1577                         int wrprot;
1578
1579                         get_fdc(drive);
1580                         fd_select (drive);
1581                         wrprot = !(ciaa.pra & DSKPROT);
1582                         fd_deselect (drive);
1583                         rel_fdc();
1584
1585                         if (wrprot)
1586                                 return -EROFS;
1587                 }
1588         }
1589
1590         local_irq_save(flags);
1591         fd_ref[drive]++;
1592         fd_device[drive] = system;
1593 #ifdef MODULE
1594         if (unit[drive].motor == 0)
1595                 MOD_INC_USE_COUNT;
1596 #endif
1597         local_irq_restore(flags);
1598
1599         unit[drive].dtype=&data_types[system];
1600         unit[drive].blocks=unit[drive].type->heads*unit[drive].type->tracks*
1601                 data_types[system].sects*unit[drive].type->sect_mult;
1602         set_capacity(unit[drive].gendisk, unit[drive].blocks);
1603
1604         printk(KERN_INFO "fd%d: accessing %s-disk with %s-layout\n",drive,
1605                unit[drive].type->name, data_types[system].name);
1606
1607         return 0;
1608 }
1609
1610 static int floppy_release(struct inode * inode, struct file * filp)
1611 {
1612         int drive = iminor(inode) & 3;
1613
1614         if (unit[drive].dirty == 1) {
1615                 del_timer (flush_track_timer + drive);
1616                 non_int_flush_track (drive);
1617         }
1618   
1619         if (!fd_ref[drive]--) {
1620                 printk(KERN_CRIT "floppy_release with fd_ref == 0");
1621                 fd_ref[drive] = 0;
1622         }
1623 #ifdef MODULE
1624 /* the mod_use counter is handled this way */
1625         floppy_off (drive | 0x40000000);
1626 #endif
1627         return 0;
1628 }
1629
1630 /*
1631  * floppy-change is never called from an interrupt, so we can relax a bit
1632  * here, sleep etc. Note that floppy-on tries to set current_DOR to point
1633  * to the desired drive, but it will probably not survive the sleep if
1634  * several floppies are used at the same time: thus the loop.
1635  */
1636 static int amiga_floppy_change(struct gendisk *disk)
1637 {
1638         struct amiga_floppy_struct *p = disk->private_data;
1639         int drive = p - unit;
1640         int changed;
1641         static int first_time = 1;
1642
1643         if (first_time)
1644                 changed = first_time--;
1645         else {
1646                 get_fdc(drive);
1647                 fd_select (drive);
1648                 changed = !(ciaa.pra & DSKCHANGE);
1649                 fd_deselect (drive);
1650                 rel_fdc();
1651         }
1652
1653         if (changed) {
1654                 fd_probe(drive);
1655                 p->track = -1;
1656                 p->dirty = 0;
1657                 writepending = 0; /* if this was true before, too bad! */
1658                 writefromint = 0;
1659                 return 1;
1660         }
1661         return 0;
1662 }
1663
1664 static struct block_device_operations floppy_fops = {
1665         .owner          = THIS_MODULE,
1666         .open           = floppy_open,
1667         .release        = floppy_release,
1668         .ioctl          = fd_ioctl,
1669         .media_changed  = amiga_floppy_change,
1670 };
1671
1672 void __init amiga_floppy_setup (char *str, int *ints)
1673 {
1674         printk (KERN_INFO "amiflop: Setting default df0 to %x\n", ints[1]);
1675         fd_def_df0 = ints[1];
1676 }
1677
1678 static int __init fd_probe_drives(void)
1679 {
1680         int drive,drives,nomem;
1681
1682         printk(KERN_INFO "FD: probing units\n" KERN_INFO "found ");
1683         drives=0;
1684         nomem=0;
1685         for(drive=0;drive<FD_MAX_UNITS;drive++) {
1686                 struct gendisk *disk;
1687                 fd_probe(drive);
1688                 if (unit[drive].type->code == FD_NODRIVE)
1689                         continue;
1690                 disk = alloc_disk(1);
1691                 if (!disk) {
1692                         unit[drive].type->code = FD_NODRIVE;
1693                         continue;
1694                 }
1695                 unit[drive].gendisk = disk;
1696                 drives++;
1697                 if ((unit[drive].trackbuf = kmalloc(FLOPPY_MAX_SECTORS * 512, GFP_KERNEL)) == NULL) {
1698                         printk("no mem for ");
1699                         unit[drive].type = &drive_types[num_dr_types - 1]; /* FD_NODRIVE */
1700                         drives--;
1701                         nomem = 1;
1702                 }
1703                 printk("fd%d ",drive);
1704                 disk->major = FLOPPY_MAJOR;
1705                 disk->first_minor = drive;
1706                 disk->fops = &floppy_fops;
1707                 sprintf(disk->disk_name, "fd%d", drive);
1708                 disk->private_data = &unit[drive];
1709                 disk->queue = floppy_queue;
1710                 set_capacity(disk, 880*2);
1711                 add_disk(disk);
1712         }
1713         if ((drives > 0) || (nomem == 0)) {
1714                 if (drives == 0)
1715                         printk("no drives");
1716                 printk("\n");
1717                 return drives;
1718         }
1719         printk("\n");
1720         return -ENOMEM;
1721 }
1722  
1723 static struct kobject *floppy_find(dev_t dev, int *part, void *data)
1724 {
1725         int drive = *part & 3;
1726         if (unit[drive].type->code == FD_NODRIVE)
1727                 return NULL;
1728         *part = 0;
1729         return get_disk(unit[drive].gendisk);
1730 }
1731
1732 int __init amiga_floppy_init(void)
1733 {
1734         int i, ret;
1735
1736         if (!AMIGAHW_PRESENT(AMI_FLOPPY))
1737                 return -ENXIO;
1738
1739         if (register_blkdev(FLOPPY_MAJOR,"fd"))
1740                 return -EBUSY;
1741
1742         /*
1743          *  We request DSKPTR, DSKLEN and DSKDATA only, because the other
1744          *  floppy registers are too spreaded over the custom register space
1745          */
1746         ret = -EBUSY;
1747         if (!request_mem_region(CUSTOM_PHYSADDR+0x20, 8, "amiflop [Paula]")) {
1748                 printk("fd: cannot get floppy registers\n");
1749                 goto out_blkdev;
1750         }
1751
1752         ret = -ENOMEM;
1753         if ((raw_buf = (char *)amiga_chip_alloc (RAW_BUF_SIZE, "Floppy")) ==
1754             NULL) {
1755                 printk("fd: cannot get chip mem buffer\n");
1756                 goto out_memregion;
1757         }
1758
1759         ret = -EBUSY;
1760         if (request_irq(IRQ_AMIGA_DSKBLK, fd_block_done, 0, "floppy_dma", NULL)) {
1761                 printk("fd: cannot get irq for dma\n");
1762                 goto out_irq;
1763         }
1764
1765         if (request_irq(IRQ_AMIGA_CIAA_TB, ms_isr, 0, "floppy_timer", NULL)) {
1766                 printk("fd: cannot get irq for timer\n");
1767                 goto out_irq2;
1768         }
1769
1770         ret = -ENOMEM;
1771         floppy_queue = blk_init_queue(do_fd_request, &amiflop_lock);
1772         if (!floppy_queue)
1773                 goto out_queue;
1774
1775         ret = -ENXIO;
1776         if (fd_probe_drives() < 1) /* No usable drives */
1777                 goto out_probe;
1778
1779         blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE,
1780                                 floppy_find, NULL, NULL);
1781
1782         /* initialize variables */
1783         init_timer(&motor_on_timer);
1784         motor_on_timer.expires = 0;
1785         motor_on_timer.data = 0;
1786         motor_on_timer.function = motor_on_callback;
1787         for (i = 0; i < FD_MAX_UNITS; i++) {
1788                 init_timer(&motor_off_timer[i]);
1789                 motor_off_timer[i].expires = 0;
1790                 motor_off_timer[i].data = i|0x80000000;
1791                 motor_off_timer[i].function = fd_motor_off;
1792                 init_timer(&flush_track_timer[i]);
1793                 flush_track_timer[i].expires = 0;
1794                 flush_track_timer[i].data = i;
1795                 flush_track_timer[i].function = flush_track_callback;
1796
1797                 unit[i].track = -1;
1798         }
1799
1800         init_timer(&post_write_timer);
1801         post_write_timer.expires = 0;
1802         post_write_timer.data = 0;
1803         post_write_timer.function = post_write;
1804   
1805         for (i = 0; i < 128; i++)
1806                 mfmdecode[i]=255;
1807         for (i = 0; i < 16; i++)
1808                 mfmdecode[mfmencode[i]]=i;
1809
1810         /* make sure that disk DMA is enabled */
1811         custom.dmacon = DMAF_SETCLR | DMAF_DISK;
1812
1813         /* init ms timer */
1814         ciaa.crb = 8; /* one-shot, stop */
1815         return 0;
1816
1817 out_probe:
1818         blk_cleanup_queue(floppy_queue);
1819 out_queue:
1820         free_irq(IRQ_AMIGA_CIAA_TB, NULL);
1821 out_irq2:
1822         free_irq(IRQ_AMIGA_DSKBLK, NULL);
1823 out_irq:
1824         amiga_chip_free(raw_buf);
1825 out_memregion:
1826         release_mem_region(CUSTOM_PHYSADDR+0x20, 8);
1827 out_blkdev:
1828         unregister_blkdev(FLOPPY_MAJOR,"fd");
1829         return ret;
1830 }
1831
1832 #ifdef MODULE
1833 #include <linux/version.h>
1834
1835 int init_module(void)
1836 {
1837         if (!MACH_IS_AMIGA)
1838                 return -ENXIO;
1839         return amiga_floppy_init();
1840 }
1841
1842 void cleanup_module(void)
1843 {
1844         int i;
1845
1846         for( i = 0; i < FD_MAX_UNITS; i++) {
1847                 if (unit[i].type->code != FD_NODRIVE) {
1848                         del_gendisk(unit[i].gendisk);
1849                         put_disk(unit[i].gendisk);
1850                         kfree(unit[i].trackbuf);
1851                 }
1852         }
1853         blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256);
1854         free_irq(IRQ_AMIGA_CIAA_TB, NULL);
1855         free_irq(IRQ_AMIGA_DSKBLK, NULL);
1856         custom.dmacon = DMAF_DISK; /* disable DMA */
1857         amiga_chip_free(raw_buf);
1858         blk_cleanup_queue(floppy_queue);
1859         release_mem_region(CUSTOM_PHYSADDR+0x20, 8);
1860         unregister_blkdev(FLOPPY_MAJOR, "fd");
1861 }
1862 #endif