patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / drivers / char / tpqic02.c
1 /* $Id: tpqic02.c,v 1.10 1997/01/26 07:13:20 davem Exp $
2  *
3  * Driver for tape drive support for Linux-i386
4  *
5  * Copyright (c) 1992--1996 by H. H. Bergman. All rights reserved.
6  * Current e-mail address: hennus@cybercomm.nl
7  *
8  * Distribution of this program in executable form is only allowed if
9  * all of the corresponding source files are made available through the same
10  * medium at no extra cost.
11  *
12  * I will not accept any responsibility for damage caused directly or
13  * indirectly by this program, or code derived from this program.
14  *
15  * Use this code at your own risk. Don't blame me if it destroys your data!
16  * Make sure you have a backup before you try this code.
17  *
18  * If you make changes to my code and redistribute it in source or binary
19  * form you must make it clear to even casual users of your code that you
20  * have modified my code, clearly point out what the changes exactly are
21  * (preferably in the form of a context diff file), how to undo your changes,
22  * where the original can be obtained, and that complaints/requests about the
23  * modified code should be directed to you instead of me.
24  *
25  * This driver was partially inspired by the 'wt' driver in the 386BSD
26  * source distribution, which carries the following copyright notice:
27  *
28  *  Copyright (c) 1991 The Regents of the University of California.
29  *  All rights reserved.
30  *
31  * You are not allowed to change this line nor the text above.
32  *
33  * 2001/02/26   Minor s/suser/capable/
34  *
35  * 1996/10/10   Emerald changes
36  *
37  * 1996/05/21   Misc changes+merges+cleanups + I/O reservations
38  *
39  * 1996/05/20   Module support patches submitted by Brian McCauley.
40  *
41  * 1994/05/03   Initial attempt at Mountain support for the Mountain 7150.
42  * Based on patches provided by Erik Jacobson. Still incomplete, I suppose.
43  *
44  * 1994/02/07   Archive changes & some cleanups by Eddy Olk.
45  *
46  * 1994/01/19   Speed measuring stuff moved from aperf.h to delay.h.
47  *              BogoMips (tm) introduced by Linus.
48  *
49  * 1993/01/25   Kernel udelay. Eof fixups.
50  * 
51  * 1992/09/19   Some changes based on patches by Eddy Olk to support
52  *              Archive SC402/SC499R controller cards.
53  *
54  * 1992/05/27   First release.
55  *
56  * 1992/05/26   Initial version. Copyright H. H. Bergman 1992
57  */
58
59 /* After the legalese, now the important bits:
60  * 
61  * This is a driver for the Wangtek 5150 tape drive with 
62  * a QIC-02 controller for ISA-PC type computers.
63  * Hopefully it will work with other QIC-02 tape drives as well.
64  *
65  * Make sure your setup matches the configuration parameters.
66  * Also, be careful to avoid IO conflicts with other devices!
67  */
68
69
70 /*
71 #define TDEBUG
72 */
73
74 #define REALLY_SLOW_IO          /* it sure is ... */
75
76 #include <linux/module.h>
77
78 #include <linux/config.h>
79
80 #include <linux/interrupt.h>
81 #include <linux/sched.h>
82 #include <linux/timer.h>
83 #include <linux/fs.h>
84 #include <linux/kernel.h>
85 #include <linux/major.h>
86 #include <linux/errno.h>
87 #include <linux/mtio.h>
88 #include <linux/fcntl.h>
89 #include <linux/delay.h>
90 #include <linux/ioport.h>
91 #include <linux/tpqic02.h>
92 #include <linux/mm.h>
93 #include <linux/slab.h>
94 #include <linux/init.h>
95 #include <linux/smp_lock.h>
96 #include <linux/devfs_fs_kernel.h>
97 #include <linux/device.h>
98
99 #include <asm/dma.h>
100 #include <asm/system.h>
101 #include <asm/io.h>
102 #include <asm/uaccess.h>
103
104 /* check existence of required configuration parameters */
105 #if !defined(QIC02_CMD_PORT) || !defined(QIC02_TAPE_IRQ) || !defined(QIC02_TAPE_DMA)
106 # error qic02_tape configuration error
107 #endif
108
109
110 #define TPQIC02_NAME    "tpqic02"
111
112 /* Linux outb() commands have (value,port) as parameters.
113  * One might expect (port,value) instead, so beware!
114  */
115
116 #ifdef CONFIG_QIC02_DYNCONF
117 /* This holds the dynamic configuration info for the interface
118  * card+drive info if runtime configuration has been selected.
119  */
120
121 static struct mtconfiginfo qic02_tape_dynconf =  {
122         /* user settable */
123         0, 0, BOGUS_IRQ, 0, 0, TPQD_DEFAULT_FLAGS, 
124 };
125 static struct qic02_ccb qic02_tape_ccb; /* private stuff */
126
127 #else
128
129 static unsigned long qic02_tape_debug = TPQD_DEFAULT_FLAGS;
130
131 # if ((QIC02_TAPE_IFC!=WANGTEK) && (QIC02_TAPE_IFC!=ARCHIVE) && (QIC02_TAPE_IFC!=MOUNTAIN))
132 #  error No valid interface card specified
133 # endif
134 #endif                          /* CONFIG_QIC02_DYNCONF */
135
136 static int ctlbits;     /* control reg bits for tape interface */
137
138 static wait_queue_head_t qic02_tape_transfer;   /* sync rw with interrupts */
139
140 static struct mtget ioctl_status;       /* current generic status */
141
142 static struct tpstatus tperror; /* last drive status */
143
144 static char rcs_revision[] = "$Revision: 1.10 $";
145 static char rcs_date[] = "$Date: 1997/01/26 07:13:20 $";
146
147 /* Flag bits for status and outstanding requests.
148  * (Could all be put in one bit-field-struct.)
149  * Some variables need `volatile' because they may be modified
150  * by an interrupt.
151  */
152 static flag status_dead = YES;  /* device is legally dead until proven alive */
153 static flag status_zombie = YES;        /* it's `zombie' until irq/dma allocated */
154
155 static flag status_bytes_wr = NO;       /* write FM at close or not */
156 static flag status_bytes_rd = NO;       /* (rd|wr) used for rewinding */
157
158 static volatile unsigned long status_cmd_pending;       /* cmd in progress */
159 static flag status_expect_int = NO;     /* ready for interrupts */
160 static flag status_timer_on = NO;       /* using time-out */
161 static int status_error;        /* int handler may detect error */
162 static flag status_eof_detected = NO;   /* end of file */
163 static flag status_eom_detected = NO;   /* end of recorded media */
164 static flag status_eot_detected = NO;   /* end of tape */
165 static flag doing_read = NO;
166 static flag doing_write = NO;
167
168 static unsigned long dma_bytes_todo;
169 static unsigned long dma_bytes_done;
170 static volatile unsigned dma_mode;      /* !=0 also means DMA in use */
171 static flag need_rewind = YES;
172
173 static int current_type;
174 static int extra_blocks_left = BLOCKS_BEYOND_EW;
175 static struct timer_list tp_timer;
176
177 static unsigned long tape_open;         /* Guard open one only */
178 static DECLARE_MUTEX(tape_op);          /* Serialize tape operations */
179
180 /* return_*_eof:
181  *      NO:     not at EOF,
182  *      YES:    tell app EOF was reached (return 0).
183  *
184  * return_*_eof==YES && reported_*_eof==NO  ==>
185  *      return current buffer, next time(s) return EOF.
186  *
187  * return_*_eof==YES && reported_*_eof==YES  ==>
188  *      at EOF and application knows it, so we can
189  *      move on to the next file.
190  *
191  */
192  
193 static flag return_read_eof = NO;       /* set to signal app EOF was reached */
194 static flag return_write_eof = NO;
195 static flag reported_read_eof = NO;     /* set when we've done that */
196 static flag reported_write_eof = NO;
197
198
199 /* This is for doing `mt seek <blocknr>' */
200 static char seek_addr_buf[AR_SEEK_BUF_SIZE];
201
202
203 /* In write mode, we have to write a File Mark after the last block written, 
204  * when the tape device is closed. Tape repositioning and reading in write
205  * mode is allowed as long as no actual writing has been done. After writing
206  * the File Mark, repositioning and reading are allowed again.
207  */
208 static int mode_access;         /* access mode: READ or WRITE */
209
210 static int qic02_get_resources(void);
211 static void qic02_release_resources(void);
212
213 /* This is a pointer to the actual kernel buffer where the interrupt routines
214  * read from/write to. It is needed because the DMA channels 1 and 3 cannot
215  * always access the user buffers. [The kernel buffer must reside in the
216  * lower 16MBytes of system memory because of the DMA controller.] The user
217  * must ensure that a large enough buffer is passed to the kernel, in order
218  * to reduce tape repositioning wear and tear.
219  */
220 static void *buffaddr;          /* virtual address of buffer */
221
222 /* This translates minor numbers to the corresponding recording format: */
223 static const char *format_names[] = {
224         "not set",              /* for dumb drives unable to handle format selection */
225         "11",                   /* extinct */
226         "24",
227         "120",
228         "150",
229         "300",                  /* untested. */
230         "600"                   /* untested. */
231 };
232
233 static struct class_simple *tpqic02_class;
234
235
236 /* `exception_list' is needed for exception status reporting.
237  * Exceptions 1..14 are defined by QIC-02 rev F.
238  * The drive status is matched sequentially to each entry,
239  * ignoring irrelevant bits, until a match is found. If no
240  * match is found, exception number 0 is used. (That should of
241  * course never happen...) The original table was based on the
242  * "Exception Status Summary" in QIC-02 rev F, but some changes
243  * were required to make it work with real-world drives.
244  *
245  * Exception 2 (CNI) is changed to also cover status 0x00e0 (mask USL),
246  * Exception 4 (EOM) is changed to also cover status 0x8288 (mask EOR),
247  * Exception 11 (FIL) is changed to also cover status 0x0089 (mask EOM).
248  * Exception 15 (EOR) is added for seek-to-end-of-data (catch EOR),
249  * Exception 16 (BOM) is added for beginning-of-media (catch BOM).
250  *
251  * Had to swap EXC_NDRV and EXC_NCART to ensure that extended EXC_NCART
252  * (because of the incorrect Wangtek status code) doesn't catch the
253  * EXC_NDRV first.
254  */
255 static struct exception_list_type {
256         unsigned short mask, code;
257         const char *msg;
258         /* EXC_nr attribute should match with tpqic02.h */
259 } exception_list[] = {
260         { 0, 0, "Unknown exception status code", /* extra: 0 */ },
261         { ~(0), TP_ST0 | TP_CNI | TP_USL | TP_WRP, "Drive not online" /* 1 */ }, /* Drive presence goes before cartridge presence. */
262         { ~(TP_WRP | TP_USL), TP_ST0 | TP_CNI,
263                     /* My Wangtek 5150EQ sometimes reports a status code
264                      * of 0x00e0, which is not a valid exception code, but
265                      * I think it should be recognized as "NO CARTRIDGE".
266                      */
267                         "Cartridge not in place" /* 2 */ },
268         { (unsigned short) ~(TP_ST1 | TP_BOM), (TP_ST0 | TP_WRP), "Write protected cartridge" /* 3 */ },
269         { (unsigned short) ~(TP_ST1 | TP_EOR), (TP_ST0 | TP_EOM), "End of media" /* 4 */ },
270         { ~TP_WRP, TP_ST0 | TP_UDA | TP_ST1 | TP_BOM, "Read or Write abort. Rewind tape." /* 5 */ },
271         { ~TP_WRP, TP_ST0 | TP_UDA, "Read error. Bad block transferred." /* 6 */ },
272         { ~TP_WRP, TP_ST0 | TP_UDA | TP_BNL, "Read error. Filler block transferred." /* 7 */ },
273         { ~TP_WRP, TP_ST0 | TP_UDA | TP_BNL | TP_ST1 | TP_NDT, "Read error. No data detected." /* 8 */ },
274         { ~TP_WRP, TP_ST0 | TP_EOM | TP_UDA | TP_BNL | TP_ST1 | TP_NDT, "Read error. No data detected. EOM." /* 9 */ },
275         { ~(TP_WRP | TP_MBD | TP_PAR | TP_EOR), TP_ST0 | TP_UDA | TP_BNL | TP_ST1 | TP_NDT | TP_BOM, "Read error. No data detected. BOM." /* 10 */ },
276         { ~(TP_WRP | TP_EOM), TP_ST0 | TP_FIL,
277                     /* Status 0x0089 (EOM & FM) is viewed as an FM,
278                      * because it can only happen during a read.
279                      * EOM is checked separately for an FM condition.
280                      */
281                         "File mark detected" /* 11 */ },
282         { ~(TP_ST0 | TP_CNI | TP_USL | TP_WRP | TP_BOM), TP_ST1 | TP_ILL, "Illegal command" /* 12 */ },
283         { ~(TP_ST0 | TP_CNI | TP_USL | TP_WRP | TP_BOM), TP_ST1 | TP_POR, "Reset occurred" /* 13 */ },
284         { ~TP_WRP, TP_ST0 | TP_FIL | TP_MBD,    /* NOTE: ST1 not set! */ "Marginal block detected" /* 14 */ },
285         { ~(TP_ST0 | TP_WRP | TP_EOM | TP_UDA | TP_BNL | TP_FIL |  TP_NDT), TP_ST1 | TP_EOR,    /********** Is the extra TP_NDT really needed Eddy? **********/ "End of recorded media" /* extra: 15 */ },
286             /* 15 is returned when SEEKEOD completes successfully */
287         { ~(TP_WRP | TP_ST0), TP_ST1 | TP_BOM, "Beginning of media" /* extra: 16 */ }
288 };
289
290 #define NR_OF_EXC       (sizeof(exception_list)/sizeof(struct exception_list_type))
291
292 /* Compare expected struct size and actual struct size. This
293  * is useful to catch programs compiled with old #includes.
294  */
295 #define CHECK_IOC_SIZE(structure) \
296         if (_IOC_SIZE(iocmd) != sizeof(struct structure)) { \
297                 tpqputs(TPQD_ALWAYS, "sizeof(struct " #structure \
298                         ") does not match!"); \
299                 return -EFAULT; \
300         } \
301
302 static void tpqputs(unsigned long flags, const char *s)
303 {
304         if ((flags & TPQD_ALWAYS) || (flags & QIC02_TAPE_DEBUG))
305                 printk(TPQIC02_NAME ": %s\n", s);
306 }                               /* tpqputs */
307
308
309 /* Init control register bits on interface card.
310  * For Archive, interrupts must be enabled explicitly.
311  * Wangtek interface card requires ONLINE to be set, Archive SC402/SC499R
312  * cards keep it active all the time.
313  */
314
315 static void ifc_init(void)
316 {
317         if (QIC02_TAPE_IFC == WANGTEK) {        /* || (QIC02_TAPE_IFC == EVEREX) */
318                 ctlbits = WT_CTL_ONLINE;        /* online */
319                 outb_p(ctlbits, QIC02_CTL_PORT);
320         } else if (QIC02_TAPE_IFC == ARCHIVE) {
321                 ctlbits = 0;    /* no interrupts yet */
322                 outb_p(ctlbits, QIC02_CTL_PORT);
323                 outb_p(0, AR_RESET_DMA_PORT);   /* dummy write to reset DMA */
324         } else {                /* MOUNTAIN */
325
326                 ctlbits = MTN_CTL_ONLINE;       /* online, and logic enabled */
327                 outb_p(ctlbits, QIC02_CTL_PORT);
328         }
329 }                               /* ifc_init */
330
331
332 static void report_qic_exception(unsigned n)
333 {
334         if (n >= NR_OF_EXC) {
335                 tpqputs(TPQD_ALWAYS, "Oops -- report_qic_exception");
336                 n = 0;
337         }
338         if (TPQDBG(SENSE_TEXT) || n == 0)
339                 printk(TPQIC02_NAME ": sense: %s\n", exception_list[n].msg);
340 }                               /* report_qic_exception */
341
342
343 /* Try to map the drive-exception bits `s' to a predefined "exception number",
344  * by comparing the significant exception bits for each entry in the
345  * exception table (`exception_list[]').
346  * It is assumed that s!=0.
347  */
348 static int decode_qic_exception_nr(unsigned s)
349 {
350         int i;
351
352         for (i = 1; i < NR_OF_EXC; i++) {
353                 if ((s & exception_list[i].mask) == exception_list[i].code) {
354                         return i;
355                 }
356         }
357         printk(TPQIC02_NAME ": decode_qic_exception_nr: exception(%x) not recognized\n", s);
358         return 0;
359 }                               /* decode_qic_exception_nr */
360
361
362
363 /* Perform appropriate action for certain exceptions.
364  * should return a value to indicate stop/continue (in case of bad blocks)
365  */
366 static void handle_qic_exception(int exnr, int exbits)
367 {
368         if (exnr == EXC_NCART) {
369                 /* Cartridge was changed. Redo sense().
370                  * EXC_NCART should be handled in open().
371                  * It is not permitted to remove the tape while
372                  * the tape driver has open files. 
373                  */
374                 need_rewind = YES;
375                 status_eof_detected = NO;
376                 status_eom_detected = NO;
377         } else if (exnr == EXC_XFILLER) {
378                 tpqputs(TPQD_ALWAYS,
379                         "[Bad block -- filler data transferred.]");
380         } else if (exnr == EXC_XBAD) {
381                 tpqputs(TPQD_ALWAYS, "[CRC failed!]");
382         } else if (exnr == EXC_MARGINAL) {
383                 /* A marginal block behaves much like a FM.
384                  * User may continue reading, if desired.
385                  */
386                 tpqputs(TPQD_ALWAYS, "[Marginal block]");
387                 doing_read = NO;
388         } else if (exnr == EXC_FM) {
389                 doing_read = NO;
390         }
391 }                               /* handle_qic_exception */
392
393
394 static inline int is_exception(void)
395 {
396         return (inb(QIC02_STAT_PORT) & QIC02_STAT_EXCEPTION) == 0;
397 }                               /* is_exception */
398
399
400 /* Reset the tape drive and controller.
401  * When reset fails, it marks  the drive as dead and all
402  * requests (except reset) are to be ignored (ENXIO).
403  */
404 static int tape_reset(int verbose)
405 {
406         ifc_init();             /* reset interface card */
407
408         /* assert reset */
409         if (QIC02_TAPE_IFC == MOUNTAIN) {
410                 outb_p(ctlbits & ~MTN_QIC02_CTL_RESET_NOT, QIC02_CTL_PORT);
411         } else {                /* WANGTEK, ARCHIVE */
412
413                 outb_p(ctlbits | QIC02_CTL_RESET, QIC02_CTL_PORT);
414         }
415
416         /* Next, we need to wait >=25 usec. */
417         udelay(30);
418
419         /* after reset, we will be at BOT (modulo an automatic rewind) */
420         status_eof_detected = NO;
421         status_eom_detected = NO;
422         status_cmd_pending = 0;
423         need_rewind = YES;
424         doing_read = doing_write = NO;
425         ioctl_status.mt_fileno = ioctl_status.mt_blkno = 0;
426
427         /* de-assert reset */
428         if (QIC02_TAPE_IFC == MOUNTAIN) {
429                 outb_p(ctlbits | MTN_QIC02_CTL_RESET_NOT, QIC02_CTL_PORT);
430         } else {
431                 outb_p(ctlbits & ~QIC02_CTL_RESET, QIC02_CTL_PORT);
432         }
433
434         /* KLUDGE FOR G++ BUG */
435         {
436                 int stat = inb_p(QIC02_STAT_PORT);
437                 status_dead = ((stat & QIC02_STAT_RESETMASK) != QIC02_STAT_RESETVAL);
438         }
439         /* if successful, inb(STAT) returned RESETVAL */
440         if (status_dead == YES)
441                 printk(TPQIC02_NAME ": reset failed!\n");
442         else if (verbose)
443                 printk(TPQIC02_NAME ": reset successful\n");
444
445         return (status_dead == YES) ? TE_DEAD : TE_OK;
446 }                               /* tape_reset */
447
448
449
450 /* Notify tape drive of a new command. It only waits for the
451  * command to be accepted, not for the actual command to complete.
452  *
453  * Before calling this routine, QIC02_CMD_PORT must have been loaded
454  * with the command to be executed.
455  * After this routine, the exception bit must be checked.
456  * This routine is also used by rdstatus(), so in that case, any exception
457  * must be ignored (`ignore_ex' flag).
458  */
459 static int notify_cmd(char cmd, short ignore_ex)
460 {
461         int i;
462
463         outb_p(cmd, QIC02_CMD_PORT);    /* output the command */
464
465         /* wait 1 usec before asserting /REQUEST */
466         udelay(1);
467
468         if ((!ignore_ex) && is_exception()) {
469                 tpqputs(TPQD_ALWAYS, "*** exception detected in notify_cmd");
470                 /** force a reset here **/
471                 if (tape_reset(1) == TE_DEAD)
472                         return TE_DEAD;
473                 if (is_exception()) {
474                         tpqputs(TPQD_ALWAYS, "exception persists after reset.");
475                         tpqputs(TPQD_ALWAYS, " ^ exception ignored.");
476                 }
477         }
478
479         outb_p(ctlbits | QIC02_CTL_REQUEST, QIC02_CTL_PORT);    /* set request bit */
480         i = TAPE_NOTIFY_TIMEOUT;
481         /* The specs say this takes about 500 usec, but there is no upper limit!
482          * If the drive were busy retensioning or something like that,
483          * it could be *much* longer!
484          */
485         while ((inb_p(QIC02_STAT_PORT) & QIC02_STAT_READY) && (--i > 0))
486                 udelay(1);
487         /* wait for ready */
488         if (i == 0) {
489                 tpqputs(TPQD_ALWAYS, "timed out waiting for ready in notify_cmd");
490                 status_dead = YES;
491                 return TE_TIM;
492         }
493
494         outb_p(ctlbits & ~QIC02_CTL_REQUEST, QIC02_CTL_PORT);   /* reset request bit */
495         i = TAPE_NOTIFY_TIMEOUT;
496         /* according to the specs this one should never time-out */
497         while (((inb_p(QIC02_STAT_PORT) & QIC02_STAT_READY) == 0) && (--i > 0))
498                 udelay(1);
499         /* wait for not ready */
500         if (i == 0) {
501                 tpqputs(TPQD_ALWAYS, "timed out waiting for !ready in notify_cmd");
502                 status_dead = YES;
503                 return TE_TIM;
504         }
505         /* command accepted */
506         return TE_OK;
507 }                               /* notify_cmd */
508
509
510
511 /* Wait for a command to complete, with timeout */
512 static int wait_for_ready(time_t timeout)
513 {
514         int stat;
515         unsigned long spin_t;
516
517         /* Wait for ready or exception, without driving the loadavg up too much.
518          * In most cases, the tape drive already has READY asserted,
519          * so optimize for that case.
520          *
521          * First, busy wait a few usec:
522          */
523         spin_t = 50;
524         while (((stat = inb_p(QIC02_STAT_PORT) & QIC02_STAT_MASK) == QIC02_STAT_MASK) && (--spin_t > 0))
525                 udelay(1);
526         if ((stat & QIC02_STAT_READY) == 0)
527                 return TE_OK;   /* covers 99.99% of all calls */
528
529         /* Then use schedule() a few times */
530         spin_t = 3;             /* max 0.03 sec busy waiting */
531         if (spin_t > timeout)
532                 spin_t = timeout;
533         timeout -= spin_t;
534         spin_t += jiffies;
535
536         /* FIXME...*/
537         while (((stat = inb_p(QIC02_STAT_PORT) & QIC02_STAT_MASK) == QIC02_STAT_MASK)  && time_before(jiffies, spin_t))
538         {
539                 set_current_state(TASK_UNINTERRUPTIBLE);
540                 schedule_timeout(1);    /* don't waste all the CPU time */
541         }
542         if ((stat & QIC02_STAT_READY) == 0)
543                 return TE_OK;
544
545         /* If we reach this point, we probably need to wait much longer, or
546          * an exception occurred. Either case is not very time-critical.
547          * Check the status port only a few times every second.
548          * A interval of less than 0.10 sec will not be noticed by the user,
549          * more than 0.40 sec may give noticeable delays.
550          */
551         spin_t += timeout;
552         TPQDEB({printk("wait_for_ready: additional timeout: %d\n", spin_t);})
553
554             /* not ready and no exception && timeout not expired yet */
555         while (((stat = inb_p(QIC02_STAT_PORT) & QIC02_STAT_MASK) == QIC02_STAT_MASK) && time_before(jiffies, spin_t)) {
556                 /* be `nice` to other processes on long operations... */
557                 current->state = TASK_INTERRUPTIBLE;
558                 /* nap 0.30 sec between checks, */
559                 /* but could be woken up earlier by signals... */
560                 schedule_timeout(3 * HZ / 10);
561         }
562
563         /* don't use jiffies for this test because it may have changed by now */
564         if ((stat & QIC02_STAT_MASK) == QIC02_STAT_MASK) {
565                 tpqputs(TPQD_ALWAYS, "wait_for_ready() timed out");
566                 return TE_TIM;
567         }
568
569         if ((stat & QIC02_STAT_EXCEPTION) == 0) {
570                 tpqputs(TPQD_ALWAYS, "exception detected after waiting_for_ready");
571                 return TE_EX;
572         } else {
573                 return TE_OK;
574         }
575 }                               /* wait_for_ready */
576
577
578
579 /* Send some data to the drive */
580 static int send_qic02_data(char sb[], unsigned size, int ignore_ex)
581 {
582         int i, stat;
583
584         for (i = 0; i < size; i++) {
585                 stat = wait_for_ready(TIM_S);
586                 if (stat != TE_OK)
587                         return stat;
588
589                 stat = notify_cmd(sb[i], ignore_ex);
590                 if (stat != TE_OK)
591                         return stat;
592         }
593         return TE_OK;
594
595 }                               /* send_qic02_data */
596
597
598 /* Send a QIC-02 command (`cmd') to the tape drive, with
599  * a time-out (`timeout').
600  * This one is also used by tp_sense(), so we must have
601  * a flag to disable exception checking (`ignore_ex'). 
602  *
603  * On entry, the controller is supposed to be READY.
604  */
605 static int send_qic02_cmd(int cmd, time_t timeout, int ignore_ex)
606 {
607         int stat;
608
609         stat = inb_p(QIC02_STAT_PORT);
610         if ((stat & QIC02_STAT_EXCEPTION) == 0) {       /* if exception */
611                 tpqputs(TPQD_ALWAYS, "send_qic02_cmd: Exception!");
612                 return TE_EX;
613         }
614         if (stat & QIC02_STAT_READY) {  /* if not ready */
615                 tpqputs(TPQD_ALWAYS, "send_qic02_cmd: not Ready!");
616                 return TE_ERR;
617         }
618
619         /* assert(ready & !exception) */
620
621         /* Remember current command for later re-use with dma transfers.
622          * (For reading/writing multiple blocks.)
623          */
624         status_cmd_pending = cmd;
625
626         stat = notify_cmd(cmd, ignore_ex);      /* tell drive new command was loaded, */
627         /* inherit exception check. */
628         if (TP_HAVE_SEEK && (cmd == AR_QCMDV_SEEK_BLK)) {
629                 /* This one needs to send 3 more bytes, MSB first */
630                 stat = send_qic02_data(seek_addr_buf, sizeof(seek_addr_buf), ignore_ex);
631         }
632
633         if (stat != TE_OK) {
634                 tpqputs(TPQD_ALWAYS, "send_qic02_cmd failed");
635         }
636         return stat;
637 }                               /* send_qic02_cmd */
638
639
640
641 /* Get drive status. Assume drive is ready or has exception set.
642  * (or will be in <1000 usec.)
643  * Extra parameters added because of 'Read Extended Status 3' command.
644  */
645 static int rdstatus(char *stp, unsigned size, char qcmd)
646 {
647         int s, n;
648         char *q = stp;
649
650         /* Try to busy-wait a few (700) usec, after that de-schedule.
651          *
652          * The problem is, if we don't de-schedule, performance will
653          * drop to zero when the drive is not responding and if we
654          * de-schedule immediately, we waste a lot of time because a
655          * task switch is much longer than we usually have to wait here.
656          */
657         n = 700;
658         while ((n > 0) && ((inb_p(QIC02_STAT_PORT) & QIC02_STAT_MASK) == QIC02_STAT_MASK))
659         {
660                 udelay(1);
661                 n--;            /* wait for ready or exception or timeout */
662         }
663         if (n == 0) {
664                 /* n (above) should be chosen such that on your machine
665                  * you rarely ever see the message below, and it should
666                  * be small enough to give reasonable response time.]
667                  */
668                 /* FIXME */
669                 tpqputs(TPQD_ALWAYS, "waiting looong in rdstatus() -- drive dead?");
670                 while ((inb_p(QIC02_STAT_PORT) & QIC02_STAT_MASK) == QIC02_STAT_MASK)
671                 {
672                         set_current_state(TASK_UNINTERRUPTIBLE);
673                         schedule_timeout(1);
674                 }
675                 tpqputs(TPQD_ALWAYS, "finished waiting in rdstatus()");
676         }
677
678         (void) notify_cmd(qcmd, 1);     /* send read status command */
679         /* ignore return code -- should always be ok, STAT may contain 
680          * exception flag from previous exception which we are trying to clear.
681          */
682
683         if (TP_DIAGS(current_type))
684                 printk(TPQIC02_NAME ": reading status bytes: ");
685
686         for (q = stp; q < stp + size; q++) {
687                 do
688                         s = inb_p(QIC02_STAT_PORT);
689                 while ((s & QIC02_STAT_MASK) == QIC02_STAT_MASK);       /* wait for ready or exception */
690
691                 if ((s & QIC02_STAT_EXCEPTION) == 0) {  /* if exception */
692                         tpqputs(TPQD_ALWAYS, "rdstatus: exception error");
693                         ioctl_status.mt_erreg = 0;      /* dunno... */
694                         return TE_NS;   /* error, shouldn't happen... */
695                 }
696
697                 *q = inb_p(QIC02_DATA_PORT);    /* read status byte */
698
699                 if (TP_DIAGS(current_type))
700                         printk("[%1zd]=0x%x  ", q - stp, (unsigned) (*q) & 0xff);
701
702                 outb_p(ctlbits | QIC02_CTL_REQUEST, QIC02_CTL_PORT);    /* set request */
703
704                 while ((inb_p(QIC02_STAT_PORT) & QIC02_STAT_READY) == 0)
705                         cpu_relax();    /* wait for not ready */
706
707                 udelay(22);     /* delay >20 usec */
708
709                 outb_p(ctlbits & ~QIC02_CTL_REQUEST, QIC02_CTL_PORT);   /* un-set request */
710
711         }
712
713         /* Specs say we should wait for READY here.
714          * My drive doesn't seem to need it here yet, but others do?
715          */
716         while (inb_p(QIC02_STAT_PORT) & QIC02_STAT_READY)
717                 cpu_relax();
718         /* wait for ready */
719
720         if (TP_DIAGS(current_type))
721                 printk("\n");
722
723         return TE_OK;
724 }                               /* rdstatus */
725
726
727
728 /* Get standard status (6 bytes).
729  * The `.dec' and `.urc' fields are in MSB-first byte-order,
730  * so they have to be swapped first.
731  */
732 static int get_status(volatile struct tpstatus *stp)
733 {
734         int stat = rdstatus((char *) stp, TPSTATSIZE, QCMD_RD_STAT);
735         stp->dec = be16_to_cpu(stp->dec);
736         stp->urc = be16_to_cpu(stp->urc);
737         return stat;
738 }                               /* get_status */
739
740
741 #if 0
742 /* This fails for my Wangtek drive */
743 /* get "Extended Status Register 3" (64 bytes)
744  *
745  * If the meaning of the returned bytes were known, the MT_TYPE
746  * identifier could be used to decode them, since they are
747  * "vendor unique". :-(
748  */
749 static int get_ext_status3(void)
750 {
751         char vus[64];           /* vendor unique status */
752         int stat, i;
753
754         tpqputs(TPQD_ALWAYS, "Attempting to read Extended Status 3...");
755         stat = rdstatus(vus, sizeof(vus), QCMD_RD_STAT_X3);
756         if (stat != TE_OK)
757                 return stat;
758
759         tpqputs(TPQD_ALWAYS, "Returned status bytes:");
760         for (i = 0; i < sizeof(vus); i++) {
761                 if (i % 8 == 0)
762                         printk("\n" TPQIC02_NAME ": %2d:");
763                 printk(" %2x", vus[i] & 0xff);
764         }
765         printk("\n");
766
767         return TE_OK;
768 }                               /* get_ext_status3 */
769 #endif
770
771
772 /* Read drive status and set generic status too.
773  * NOTE: Once we do a tp_sense(), read/write transfers are killed.
774  */
775 static int tp_sense(int ignore)
776 {
777         unsigned err = 0, exnr = 0, gs = 0;
778         static void finish_rw(int cmd);
779
780         if (TPQDBG(SENSE_TEXT))
781                 printk(TPQIC02_NAME ": tp_sense(ignore=0x%x) enter\n", ignore);
782
783         /* sense() is not allowed during a read or write cycle */
784         if (doing_write == YES)
785                 tpqputs(TPQD_ALWAYS, "Warning: File Mark inserted because of sense() request");
786         /* The extra test is to avoid calling finish_rw during booting */
787         if ((doing_read != NO) || (doing_write != NO))
788                 finish_rw(QCMD_RD_STAT);
789
790         if (get_status(&tperror) != TE_OK) {
791                 tpqputs(TPQD_ALWAYS, "tp_sense: could not read tape drive status");
792                 return TE_ERR;
793         }
794
795         err = tperror.exs;      /* get exception status bits */
796         if (err & (TP_ST0 | TP_ST1))
797                 printk(TPQIC02_NAME ": tp_sense: status: %x, error count: %d, underruns: %d\n",
798                        tperror.exs, tperror.dec, tperror.urc);
799         else if ((tperror.dec != 0) || (tperror.urc != 0) || TPQDBG(SENSE_CNTS))
800                 printk(TPQIC02_NAME ": tp_sense: no hard errors, soft error count: %d, underruns: %d\n", tperror.dec, tperror.urc);
801
802         /* Set generic status. HP-UX defines these, but some extra would 
803          * be useful. Problem is to remain compatible. [Do we want to be
804          * compatible??]
805          */
806         if (err & TP_ST0) {
807                 if (err & TP_CNI)       /* no cartridge */
808                         gs |= GMT_DR_OPEN(-1);
809                 if (status_dead == NO)
810                         gs |= GMT_ONLINE(-1);   /* always online */
811                 if (err & TP_USL)       /* not online */
812                         gs &= ~GMT_ONLINE(-1);
813                 if (err & TP_WRP)
814                         gs |= GMT_WR_PROT(-1);
815                 if (err & TP_EOM) {     /* end of media */
816                         gs |= GMT_EOT(-1);      /* not sure this is correct for writes */
817                         status_eom_detected = YES;
818                         /* I don't know whether drive always reports EOF at or before EOM. */
819                         status_eof_detected = YES;
820                 }
821                 /** if (err & TP_UDA) "Unrecoverable data error" **/
822                 /** if (err & TP_BNL) "Bad block not located" **/
823                 if (err & TP_FIL) {
824                         gs |= GMT_EOF(-1);
825                         status_eof_detected = YES;
826                 }
827         }
828         if (err & TP_ST1) {
829                 /** if (err & TP_ILL) "Illegal command" **/
830                 /** if (err & TP_NDT) "No data detected" **/
831                 /** if (err & TP_MBD) "Marginal block detected" **/
832                 if (err & TP_BOM)
833                         gs |= GMT_BOT(-1);      /* beginning of tape */
834         }
835         ioctl_status.mt_gstat = gs;
836         ioctl_status.mt_dsreg = tperror.exs;    /* "drive status" */
837         ioctl_status.mt_erreg = tperror.dec;    /* "sense key error" */
838
839         if (err & (TP_ST0 | TP_ST1)) {
840                 /* My Wangtek occasionally reports `status' 1212 which should be ignored. */
841                 exnr = decode_qic_exception_nr(err);
842                 handle_qic_exception(exnr, err);        /* update driver state wrt drive status */
843                 report_qic_exception(exnr);
844         }
845         err &= ~ignore;         /* mask unwanted errors -- not the correct way, use exception nrs?? */
846         if (((err & TP_ST0) && (err & REPORT_ERR0)) ||
847             ((err & TP_ST1) && (err & REPORT_ERR1)))
848                 return TE_ERR;
849         return TE_OK;
850 }                               /* tp_sense */
851
852
853
854 /* Wait for a wind or rewind operation to finish or
855  * to time-out. (May take very long).
856  */
857 static int wait_for_rewind(time_t timeout)
858 {
859         int stat;
860
861         stat = inb(QIC02_STAT_PORT) & QIC02_STAT_MASK;
862         if (TPQDBG(REWIND))
863                 printk(TPQIC02_NAME ": Waiting for (re-)wind to finish: stat=0x%x\n", stat);
864
865         stat = wait_for_ready(timeout);
866
867         if (stat != TE_OK) {
868                 tpqputs(TPQD_ALWAYS, "(re-) winding failed\n");
869         }
870         return stat;
871 }                               /* wait_for_rewind */
872
873
874
875 /* Perform a full QIC02 command, and wait for completion,
876  * check status when done. Complain about exceptions.
877  *
878  * This function should return an OS error code when
879  * something goes wrong, 0 otherwise.
880  */
881 static int ll_do_qic_cmd(int cmd, time_t timeout)
882 {
883         int stat;
884
885         if (status_dead == YES) {
886                 tpqputs(TPQD_ALWAYS, "Drive is dead. Do a `mt reset`.");
887                 return -ENXIO;  /* User should do an MTRESET. */
888         }
889
890         stat = wait_for_ready(timeout); /* wait for ready or exception */
891         if (stat == TE_EX) {
892                 if (tp_sense(TP_WRP | TP_BOM | TP_EOM | TP_FIL) != TE_OK)
893                         return -EIO;
894                 /* else nothing to worry about, I hope */
895                 stat = TE_OK;
896         }
897         if (stat != TE_OK) {
898                 printk(TPQIC02_NAME ": ll_do_qic_cmd(%x, %ld) failed\n", cmd, (long) timeout);
899                 return -EIO;
900         }
901 #if OBSOLETE
902         /* wait for ready since it may not be active immediately after reading status */
903         while ((inb_p(QIC02_STAT_PORT) & QIC02_STAT_READY) != 0)
904                 cpu_relax();
905 #endif
906
907         stat = send_qic02_cmd(cmd, timeout, 0); /* (checks for exceptions) */
908
909         if (cmd == QCMD_RD_FM) {
910                 status_eof_detected = NO;
911                 ioctl_status.mt_fileno++;
912                 /* Should update block count as well, but can't.
913                  * Can do a `read address' for some drives, when MTNOP is done.
914                  */
915         } else if (cmd == QCMD_WRT_FM) {
916                 status_eof_detected = NO;
917                 ioctl_status.mt_fileno++;
918         } else if ((cmd == QCMD_REWIND) || (cmd == QCMD_ERASE)
919                    || (cmd == QCMD_RETEN)) {
920                 status_eof_detected = NO;
921                 status_eom_detected = NO;
922                 status_eot_detected = NO;
923                 need_rewind = NO;
924                 ioctl_status.mt_fileno = ioctl_status.mt_blkno = 0;
925                 extra_blocks_left = BLOCKS_BEYOND_EW;
926                 return_write_eof = NO;
927                 return_read_eof = NO;
928                 reported_read_eof = NO;
929                 reported_write_eof = NO;
930         }
931         /* sense() will set eof/eom as required */
932         if (stat == TE_EX) {
933                 if (tp_sense(TP_WRP | TP_BOM | TP_EOM | TP_FIL) != TE_OK) {
934                         printk(TPQIC02_NAME ": Exception persist in ll_do_qic_cmd[1](%x, %ld)", cmd, (long) timeout);
935                         status_dead = YES;
936                         return -ENXIO;
937                         /* if rdstatus fails too, we're in trouble */
938                 }
939         } else if (stat != TE_OK) {
940                 printk(TPQIC02_NAME ": ll_do_qic_cmd: send_qic02_cmd failed, stat = 0x%x\n", stat);
941                 return -EIO;    /*** -EIO is probably not always appropriate */
942         }
943
944         if (timeout == TIM_R)
945                 stat = wait_for_rewind(timeout);
946         else
947                 stat = wait_for_ready(timeout);
948
949         if (stat == TE_EX) {
950                 if (tp_sense((cmd == QCMD_SEEK_EOD ?            /*****************************/
951                               TP_EOR | TP_NDT | TP_UDA | TP_BNL | TP_WRP |
952                               TP_BOM | TP_EOM | TP_FIL : TP_WRP | TP_BOM |
953                               TP_EOM | TP_FIL)) != TE_OK) {
954                         printk(TPQIC02_NAME ": Exception persist in ll_do_qic_cmd[2](%x, %ld)\n", cmd, (long) timeout);
955                         if (cmd != QCMD_RD_FM)
956                                 status_dead = YES;
957                         return -ENXIO;
958                         /* if rdstatus fails too, we're in trouble */
959                 }
960         } else if (stat != TE_OK) {
961                 printk(TPQIC02_NAME ": ll_do_qic_cmd %x: wait failed, stat == 0x%x\n", cmd, stat);
962                 return -EIO;
963         }
964         return 0;
965 }                               /* ll_do_qic_cmd */
966
967
968 /* 
969  * Problem: What to do when the user cancels a read/write operation
970  * in-progress?
971  *
972  * "Deactivating ONLINE during a READ also causes the"
973  * "tape to be rewound to BOT." Ditto for WRITEs, except
974  * a FM is written first. "The host may alternatively terminate
975  * the READ/WRITE command by issuing a RFM/WFM command."
976  *
977  * For READs:
978  * Neither option will leave the tape positioned where it was.
979  * Another (better?) solution is to terminate the READ by two
980  * subsequent sense() operations, the first to stop the current
981  * READ cycle, the second to clear the `Illegal command' exception,
982  * because the QIC-02 specs didn't anticipate this. This is
983  * delayed until actually needed, so a tar listing can be aborted
984  * by the user and continued later.
985  * If anybody has a better solution, let me know! [Also, let me
986  * know if your drive (mine is a Wangtek5150EQ) does not accept
987  * this sequence for canceling the read-cycle.]
988  *
989  * For WRITEs it's simple: Just do a WRITE_FM, leaving the tape
990  * positioned after the FM.
991  */
992
993 static void terminate_read(int cmd)
994 {
995         if (doing_read != YES)
996                 return;
997                 
998         doing_read = NO;
999         
1000         if (cmd == QCMD_RD_FM)
1001                 return;
1002                 
1003         /* if the command is a RFM, there is no need to do this
1004          * because a RFM will legally terminate the read-cycle.
1005          */
1006         tpqputs(TPQD_ALWAYS, "terminating pending read-cycle");
1007
1008         /* I'm not too sure about this part  -- hhb */
1009         if (QIC02_TAPE_IFC == MOUNTAIN) {
1010                 /* Mountain reference says can terminate by de-asserting online */
1011                 ctlbits &= ~MTN_QIC02_CTL_ONLINE;
1012         }
1013
1014         if (tp_sense(TP_FIL | TP_EOM | TP_WRP) != TE_OK) {
1015                 tpqputs(TPQD_ALWAYS, "finish_rw[read1]: ignore the 2 lines above");
1016                 if (is_exception()) {
1017                         if (tp_sense(TP_ILL | TP_FIL | TP_EOM | TP_WRP) != TE_OK)
1018                                 tpqputs(TPQD_ALWAYS,"finish_rw[read2]: read cycle error");
1019                 }
1020         }
1021 }                               /* terminate_read */
1022
1023
1024 static void terminate_write(int cmd)
1025 {
1026         int stat;
1027
1028         if (doing_write != YES)
1029                 return;
1030
1031         doing_write = NO;
1032         /* Finish writing by appending a FileMark at the end. */
1033         if (cmd != QCMD_WRT_FM) {
1034                 /* finish off write cycle */
1035                 stat = ll_do_qic_cmd(QCMD_WRT_FM, TIM_M);
1036                 if (stat != TE_OK)
1037                         tpqputs(TPQD_ALWAYS, "Couldn't finish write cycle properly");
1038                 (void) tp_sense(0);
1039         }
1040         /* If there is an EOF token waiting to be returned to
1041          * the (writing) application, discard it now.
1042          * We could be at EOT, so don't reset return_write_eof.
1043          */
1044         reported_write_eof = YES;
1045 }                               /* terminate_write */
1046
1047
1048 /* terminate read or write cycle because of command `cmd' */
1049 static void finish_rw(int cmd)
1050 {
1051         if (wait_for_ready(TIM_S) != TE_OK) {
1052                 tpqputs(TPQD_ALWAYS, "error: drive not ready in finish_rw() !");
1053                 return;
1054         }
1055         terminate_read(cmd);
1056         terminate_write(cmd);
1057 }                               /* finish_rw */
1058
1059
1060 /* Perform a QIC command through ll_do_qic_cmd().
1061  * If necessary, rewind the tape first.
1062  * Return an OS error code if something goes wrong, 0 if all is well.
1063  */
1064 static int do_qic_cmd(int cmd, time_t timeout)
1065 {
1066         int stat;
1067
1068
1069         finish_rw(cmd);
1070
1071         if (need_rewind) {
1072                 tpqputs(TPQD_REWIND, "Rewinding tape...");
1073                 stat = ll_do_qic_cmd(QCMD_REWIND, TIM_R);
1074                 if (stat != 0) {
1075                         printk(TPQIC02_NAME ": rewind failed in do_qic_cmd(). stat=0x%2x", stat);
1076                         return stat;
1077                 }
1078                 need_rewind = NO;
1079                 if (cmd == QCMD_REWIND) /* don't wind beyond BOT ;-) */
1080                         return 0;
1081         }
1082
1083         return ll_do_qic_cmd(cmd, timeout);
1084 }                               /* do_qic_cmd */
1085
1086
1087 /* Not all ioctls are supported for all drives. Some rely on
1088  * optional QIC-02 commands. Check tpqic02.h for configuration.
1089  * Some of these commands may require ONLINE to be active.
1090  */
1091 static int do_ioctl_cmd(int cmd)
1092 {
1093         int stat;
1094
1095         /* It is not permitted to read or wind the tape after bytes have
1096          * been written. It is not permitted to write the tape while in
1097          * read mode.
1098          * We try to be kind and allow reading again after writing a FM...
1099          */
1100
1101         switch (cmd) {
1102         case MTRESET:
1103                 /* reset verbose */
1104                 return (tape_reset(1) == TE_OK) ? 0 : -EIO;
1105
1106         case MTFSF:
1107                 tpqputs(TPQD_IOCTLS, "MTFSF forward searching filemark");
1108                 if ((mode_access == WRITE) && status_bytes_wr)
1109                         return -EACCES;
1110                 return do_qic_cmd(QCMD_RD_FM, TIM_F);
1111
1112         case MTBSF:
1113                 if (TP_HAVE_BSF) {
1114                         tpqputs(TPQD_IOCTLS, "MTBSF backward searching filemark -- optional command");
1115                         if ((mode_access == WRITE) && status_bytes_wr)
1116                                 return -EACCES;
1117                         stat = do_qic_cmd(QCMD_RD_FM_BCK, TIM_F);
1118                 } else {
1119                         stat = -ENXIO;
1120                 }
1121                 status_eom_detected = status_eof_detected = NO;
1122                 return stat;
1123
1124         case MTFSR:
1125                 if (TP_HAVE_FSR) {      /* This is an optional QIC-02 command */
1126                         tpqputs(TPQD_IOCTLS, "MTFSR forward space record");
1127                         if ((mode_access == WRITE) && status_bytes_wr)
1128                                 return -EACCES;
1129                         stat = do_qic_cmd(QCMD_SPACE_FWD, TIM_F);
1130                 } else {
1131                                 /**** fake it by doing a read data block command? ******/
1132                         tpqputs(TPQD_IOCTLS, "MTFSR not supported");
1133                         stat = -ENXIO;
1134                 }
1135                 return stat;
1136
1137         case MTBSR:
1138                 if (TP_HAVE_BSR) {      /* This is an optional QIC-02 command */
1139                         /* we need this for appending files with GNU tar!! */
1140                         tpqputs(TPQD_IOCTLS, "MTFSR backward space record");
1141                         if ((mode_access == WRITE) && status_bytes_wr)
1142                                 return -EACCES;
1143                         stat = do_qic_cmd(QCMD_SPACE_BCK, TIM_F);
1144                 } else {
1145                         tpqputs(TPQD_IOCTLS, "MTBSR not supported");
1146                         stat = -ENXIO;
1147                 }
1148                 status_eom_detected = status_eof_detected = NO;
1149                 return stat;
1150
1151         case MTWEOF:
1152                 tpqputs(TPQD_IOCTLS, "MTWEOF write eof mark");
1153                 /* Plain GNU mt(1) 2.2 uses read-only mode for writing FM. :-( */
1154                 if (mode_access == READ)
1155                         return -EACCES;
1156
1157                 /* allow tape movement after writing FM */
1158                 status_bytes_rd = status_bytes_wr;      /* Kludge-O-Matic */
1159                 status_bytes_wr = NO;
1160                 return do_qic_cmd(QCMD_WRT_FM, TIM_M);
1161                 /* not sure what to do with status_bytes when WFM should fail */
1162
1163         case MTREW:
1164                 tpqputs(TPQD_IOCTLS, "MTREW rewinding tape");
1165                 if ((mode_access == WRITE) && status_bytes_wr)
1166                         return -EACCES;
1167                 status_eom_detected = status_eof_detected = NO;
1168                 return do_qic_cmd(QCMD_REWIND, TIM_R);
1169
1170         case MTOFFL:
1171                 tpqputs(TPQD_IOCTLS, "MTOFFL rewinding & going offline");
1172                 /* Doing a drive select will clear (unlock) the current drive.
1173                  * But that requires support for multiple drives and locking.
1174                  */
1175                 if ((mode_access == WRITE) && status_bytes_wr)
1176                         return -EACCES;
1177                 status_eom_detected = status_eof_detected = NO;
1178                         /**** do rewind depending on minor bits??? ***/
1179                 stat = do_qic_cmd(QCMD_REWIND, TIM_R);
1180                 return stat;
1181
1182         case MTNOP:
1183                 tpqputs(TPQD_IOCTLS, "MTNOP setting status only");
1184                 /********** should do `read position' for drives that support it **********/
1185                 return (tp_sense(-1) == TE_OK) ? 0 : -EIO;      /**** check return codes ****/
1186
1187         case MTRETEN:
1188                 tpqputs(TPQD_IOCTLS, "MTRETEN retension tape");
1189                 if ((mode_access == WRITE) && status_bytes_wr)
1190                         return -EACCES;
1191                 status_eom_detected = status_eof_detected = NO;
1192                 return do_qic_cmd(QCMD_RETEN, TIM_R);
1193
1194         case MTBSFM:
1195                 /* Think think is like MTBSF, except that
1196                  * we shouldn't skip the FM. Tricky.
1197                  * Maybe use RD_FM_BCK, then do a SPACE_FWD?
1198                  */
1199                 tpqputs(TPQD_IOCTLS, "MTBSFM not supported");
1200                 if ((mode_access == WRITE) && status_bytes_wr)
1201                         return -EACCES;
1202                 return -ENXIO;
1203
1204         case MTFSFM:
1205                 /* I think this is like MTFSF, except that
1206                  * we shouldn't skip the FM. Tricky.
1207                  * Maybe use QCMD_RD_DATA until we get a TP_FIL exception?
1208                  * But then the FM will have been skipped...
1209                  * Maybe use RD_FM, then RD_FM_BCK, but not all
1210                  * drives will support that!
1211                  */
1212                 tpqputs(TPQD_IOCTLS, "MTFSFM not supported");
1213                 if ((mode_access == WRITE) && status_bytes_wr)
1214                         return -EACCES;
1215                 return -ENXIO;
1216
1217         case MTEOM:
1218                 /* This should leave the tape ready for appending
1219                  * another file to the end, such that it would append
1220                  * after the last FM on tape.
1221                  */
1222                 tpqputs(TPQD_IOCTLS, "MTEOM search for End Of recorded Media");
1223                 if ((mode_access == WRITE) && status_bytes_wr)
1224                         return -EACCES;
1225                 if (TP_HAVE_EOD) {
1226                         /* Use faster seeking when possible.
1227                          * This requires the absence of data beyond the EOM.
1228                          * It seems that my drive does not always perform the
1229                          * SEEK_EOD correctly, unless it is preceded by a
1230                          * rewind command.
1231                          */
1232 # if 0
1233                         status_eom_detected = status_eof_detected = NO;
1234 # endif
1235                         stat = do_qic_cmd(QCMD_REWIND, TIM_R);
1236                         if (stat)
1237                                 return stat;
1238                         stat = do_qic_cmd(QCMD_SEEK_EOD, TIM_F);
1239                         /* After a successful seek, TP_EOR should be returned */
1240                 } else {
1241                         /* else just seek until the drive returns exception "No Data" */
1242                         stat = 0;
1243                         while ((stat == 0) && (!status_eom_detected)) {
1244                                 stat = do_qic_cmd(QCMD_RD_FM, TIM_F);         /***** should use MTFSFM here???? ******/
1245                         }
1246                         if (tperror.exs & TP_NDT)
1247                                 return 0;
1248                 }
1249                 return stat;
1250
1251         case MTERASE:
1252                 tpqputs(TPQD_IOCTLS, "MTERASE -- ERASE TAPE !");
1253                 if ((tperror.exs & TP_ST0) && (tperror.exs & TP_WRP)) {
1254                         tpqputs(TPQD_ALWAYS, "Cartridge is write-protected.");
1255                         return -EACCES;
1256                 } else {
1257                         time_t t = jiffies;
1258
1259                         /* Plain GNU mt(1) 2.2 erases a tape in O_RDONLY. :-( */
1260                         if (mode_access == READ)
1261                                 return -EACCES;
1262
1263                         /* FIXME */
1264                         /* give user a few seconds to pull out tape */
1265                         while (jiffies - t < 4 * HZ)
1266                                 schedule();
1267                 }
1268
1269                 /* don't bother writing filemark first */
1270                 status_eom_detected = status_eof_detected = NO;
1271                 return do_qic_cmd(QCMD_ERASE, TIM_R);
1272
1273         case MTRAS1:
1274                 if (TP_HAVE_RAS1) {
1275                         tpqputs(TPQD_IOCTLS, "MTRAS1: non-destructive self test");
1276                         stat = do_qic_cmd(QCMD_SELF_TST1, TIM_R);
1277                         if (stat != 0) {
1278                                 tpqputs(TPQD_ALWAYS, "RAS1 failed");
1279                                 return stat;
1280                         }
1281                         return (tp_sense(0) == TE_OK) ? 0 : -EIO;       /* get_ext_status3(); */
1282                 }
1283                 tpqputs(TPQD_IOCTLS, "RAS1 not supported");
1284                 return -ENXIO;
1285
1286         case MTRAS2:
1287                 if (TP_HAVE_RAS2) {
1288                         tpqputs(TPQD_IOCTLS, "MTRAS2: destructive self test");
1289                         stat = do_qic_cmd(QCMD_SELF_TST2, TIM_R);
1290                         if (stat != 0) {
1291                                 tpqputs(TPQD_ALWAYS, "RAS2 failed");
1292                                 return stat;
1293                         }
1294                         return (tp_sense(0) == TE_OK) ? 0 : -EIO;       /* get_ext_status3(); */
1295                 }
1296                 tpqputs(TPQD_IOCTLS, "RAS2 not supported");
1297                 return -ENXIO;
1298
1299         case MTSEEK:
1300                 if (TP_HAVE_SEEK && (QIC02_TAPE_IFC == ARCHIVE)) {
1301                         tpqputs(TPQD_IOCTLS, "MTSEEK seeking block");
1302                         if ((mode_access == WRITE) && status_bytes_wr)
1303                                 return -EACCES;
1304                         /* NOTE: address (24 bits) is in seek_addr_buf[] */
1305                         return do_qic_cmd(AR_QCMDV_SEEK_BLK, TIM_F);
1306                 } else
1307                         return -ENOTTY;
1308
1309         default:
1310                 return -ENOTTY;
1311         }
1312 }                               /* do_ioctl_cmd */
1313
1314
1315 /* dma_transfer(): This routine is called for every 512 bytes to be read
1316  * from/written to the tape controller. Speed is important here!
1317  * (There must be enough time left for the hd controller!)
1318  * The dma lock protects the DMA controller
1319  *
1320  * This routine merely does the least possible to keep
1321  * the transfers going:
1322  *      - set the DMA count register for the next 512 bytes
1323  *      - adjust the DMA address and page registers
1324  *      - adjust the timeout
1325  *      - tell the tape controller to start transferring
1326  * We assume the dma address and mode are, and remain, valid.
1327  */
1328 static inline void dma_transfer(void)
1329 {
1330         unsigned long flags;
1331
1332         if (QIC02_TAPE_IFC == WANGTEK)  /* or EVEREX */
1333                 outb_p(WT_CTL_ONLINE, QIC02_CTL_PORT);  /* back to normal */
1334         else if (QIC02_TAPE_IFC == ARCHIVE)
1335                 outb_p(0, AR_RESET_DMA_PORT);
1336         else                    /* QIC02_TAPE_IFC == MOUNTAIN */
1337                 outb_p(ctlbits, QIC02_CTL_PORT);
1338
1339
1340         flags = claim_dma_lock();
1341         clear_dma_ff(QIC02_TAPE_DMA);
1342         set_dma_mode(QIC02_TAPE_DMA, dma_mode);
1343         set_dma_addr(QIC02_TAPE_DMA, isa_virt_to_bus(buffaddr) + dma_bytes_done);
1344         set_dma_count(QIC02_TAPE_DMA, TAPE_BLKSIZE);
1345
1346         /* start tape DMA controller */
1347         if (QIC02_TAPE_IFC == WANGTEK)  /* or EVEREX */
1348                 outb_p(WT_CTL_DMA | WT_CTL_ONLINE, QIC02_CTL_PORT);     /* trigger DMA transfer */
1349
1350         else if (QIC02_TAPE_IFC == ARCHIVE) {
1351                 outb_p(AR_CTL_IEN | AR_CTL_DNIEN, QIC02_CTL_PORT);      /* enable interrupts again */
1352                 outb_p(0, AR_START_DMA_PORT);   /* start DMA transfer */
1353                 /* In dma_end() AR_RESET_DMA_PORT is written too. */
1354
1355         } else {                /* QIC02_TAPE_IFC == MOUNTAIN */
1356
1357                 inb(MTN_R_DESELECT_DMA_PORT);
1358                 outb_p(ctlbits | (MTN_CTL_EXC_IEN | MTN_CTL_DNIEN),
1359                        QIC02_CTL_PORT);
1360                 outb_p(0, MTN_W_SELECT_DMA_PORT);       /* start DMA transfer */
1361                 if (dma_mode == DMA_MODE_WRITE)
1362                         outb_p(0, MTN_W_DMA_WRITE_PORT);        /* start DMA transfer */
1363         }
1364
1365         /* start computer DMA controller */
1366         enable_dma(QIC02_TAPE_DMA);
1367
1368         release_dma_lock(flags);
1369
1370         /* block transfer should start now, jumping to the 
1371          * interrupt routine when done or an exception was detected.
1372          */
1373 }                               /* dma_transfer */
1374
1375
1376 /* start_dma() sets a DMA transfer up between the tape controller and
1377  * the kernel qic02_tape_buf buffer.
1378  * Normally bytes_todo==dma_bytes_done at the end of a DMA transfer. If not,
1379  * a filemark was read, or an attempt to write beyond the End Of Tape 
1380  * was made. [Or some other bad thing happened.]
1381  * Must do a sense() before returning error.
1382  */
1383 static int start_dma(short mode, unsigned long bytes_todo)
1384 /* assume 'bytes_todo'>0 */
1385 {
1386         int stat;
1387
1388         tpqputs(TPQD_DEBUG, "start_dma() enter");
1389         TPQDEB( {printk(TPQIC02_NAME ": doing_read==%d, doing_write==%d\n",
1390                       doing_read, doing_write);})
1391
1392         dma_bytes_done = 0;
1393         dma_bytes_todo = bytes_todo;
1394         status_error = NO;
1395         /* dma_mode!=0 indicates that the dma controller is in use */
1396         dma_mode = (mode == WRITE) ? DMA_MODE_WRITE : DMA_MODE_READ;
1397
1398         /* Only give READ/WRITE DATA command to tape drive if we haven't
1399          * done that already. Otherwise the drive will rewind to the beginning
1400          * of the current file on tape. Any QIC command given other than
1401          * R/W FM will break the read/write transfer cycle.
1402          * do_qic_cmd() will terminate doing_{read,write}
1403          */
1404         if ((doing_read == NO) && (doing_write == NO)) {
1405                 /* First, we have to clear the status -- maybe remove TP_FIL???
1406                  */
1407
1408 #if 0
1409                 /* Next dummy get status is to make sure CNI is valid,
1410                    since we're only just starting a read/write it doesn't
1411                    matter some exceptions are cleared by reading the status;
1412                    we're only interested in CNI and WRP. -Eddy */
1413                 get_status(&tperror);
1414 #else
1415                 /* TP_CNI should now be handled in open(). -Hennus */
1416 #endif
1417
1418                 stat = tp_sense(((mode == WRITE) ? 0 : TP_WRP) | TP_BOM | TP_FIL);
1419                 if (stat != TE_OK)
1420                         return stat;
1421
1422 #if OBSOLETE
1423                 /************* not needed iff rd_status() would wait for ready!!!!!! **********/
1424                 if (wait_for_ready(TIM_S) != TE_OK) {   /*** not sure this is needed ***/
1425                         tpqputs(TPQD_ALWAYS, "wait_for_ready failed in start_dma");
1426                         return -EIO;
1427                 }
1428 #endif
1429
1430                 if (QIC02_TAPE_IFC == MOUNTAIN) {
1431                         /* Set control bits to select ONLINE during command */
1432                         ctlbits |= MTN_QIC02_CTL_ONLINE;
1433                 }
1434
1435                 /* Tell the controller the data direction */
1436
1437                 /* r/w, timeout medium, check exceptions, sets status_cmd_pending. */
1438                 stat = send_qic02_cmd((mode == WRITE) ? QCMD_WRT_DATA : QCMD_RD_DATA, TIM_M, 0);
1439                 if (stat != TE_OK) {
1440                         printk(TPQIC02_NAME ": start_dma: init %s failed\n", (mode == WRITE) ? "write" : "read");
1441                         (void) tp_sense(0);
1442                         return stat;
1443                 }
1444
1445                 /* Do this last, because sense() will clear the doing_{read,write}
1446                  * flags, causing trouble next time around.
1447                  */
1448                 if (wait_for_ready(TIM_M) != TE_OK)
1449                         return -EIO;
1450                 switch (mode) {
1451                 case READ:
1452                         doing_read = YES;
1453                         break;
1454                 case WRITE:
1455                         doing_write = YES;
1456                         break;
1457                 default:
1458                         printk(TPQIC02_NAME ": requested unknown mode %d\n", mode);
1459                         panic(TPQIC02_NAME ": invalid mode in start_dma()");
1460                 }
1461
1462         } else if (is_exception()) {
1463                 /* This is for Archive drives, to handle reads with 0 bytes
1464                  * left for the last read request.
1465                  *
1466                  * ******** this also affects EOF/EOT handling! ************
1467                  */
1468                 tpqputs(TPQD_ALWAYS, "detected exception in start_dma() while transfer in progress");
1469                 status_error = YES;
1470                 return TE_END;
1471         }
1472
1473
1474         status_expect_int = YES;
1475
1476         /* This assumes tape is already positioned, but these
1477          * semi-'intelligent' drives are unpredictable...
1478          */
1479         TIMERON(TIM_M * 2);
1480
1481         /* initiate first data block read from/write to the tape controller */
1482
1483         dma_transfer();
1484
1485         TPQPUTS("start_dma() end");
1486         return TE_OK;
1487 }                               /* start_dma */
1488
1489
1490 /* This cleans up after the dma transfer has completed
1491  * (or failed). If an exception occurred, a sense()
1492  * must be done. If the exception was caused by a FM,
1493  * sense() will set `status_eof_detected' and
1494  * `status_eom_detected', as required.
1495  */
1496 static void end_dma(unsigned long *bytes_done)
1497 {
1498         int stat = TE_OK;
1499         unsigned long flags;
1500
1501         TIMEROFF;
1502
1503         TPQPUTS("end_dma() enter");
1504
1505         flags = claim_dma_lock();
1506
1507         disable_dma(QIC02_TAPE_DMA);
1508         clear_dma_ff(QIC02_TAPE_DMA);
1509
1510         release_dma_lock(flags);
1511
1512         if (QIC02_TAPE_IFC == WANGTEK)  /* or EVEREX */
1513                 outb_p(WT_CTL_ONLINE, QIC02_CTL_PORT);  /* back to normal */
1514         else if (QIC02_TAPE_IFC == ARCHIVE)
1515                 outb_p(0, AR_RESET_DMA_PORT);
1516         else {                  /* QIC02_TAPE_IFC == MOUNTAIN */
1517                 /* Clear control bits, de-select ONLINE during tp_sense */
1518                 ctlbits &= ~MTN_QIC02_CTL_ONLINE;
1519         }
1520
1521         stat = wait_for_ready(TIM_M);
1522         if (status_error || (stat != TE_OK)) {
1523                 tpqputs(TPQD_DMAX, "DMA transfer exception");
1524                 stat = tp_sense((dma_mode == READ) ? TP_WRP : 0);
1525                 /* no return here -- got to clean up first! */
1526         } else {                /* if (QIC02_TAPE_IFC == MOUNTAIN) */
1527                 outb_p(ctlbits, QIC02_CTL_PORT);
1528         }
1529
1530         if (QIC02_TAPE_IFC == MOUNTAIN)
1531                 inb(MTN_R_DESELECT_DMA_PORT);
1532
1533         /* take the tape controller offline */
1534
1535         /* finish off DMA stuff */
1536
1537
1538         dma_mode = 0;
1539         /* Note: The drive is left on-line, ready for the next
1540          * data transfer.
1541          * If the next command to the drive does not continue
1542          * the pending cycle, it must do 2 sense()s first.
1543          */
1544
1545         *bytes_done = dma_bytes_done;
1546         status_expect_int = NO;
1547         ioctl_status.mt_blkno += (dma_bytes_done / TAPE_BLKSIZE);
1548
1549         TPQPUTS("end_dma() exit");
1550         /*** could return stat here ***/
1551 }                               /* end_dma */
1552
1553 /*********** Below are the (public) OS-interface procedures ***********/
1554
1555
1556 /* qic02_tape_times_out() is called when a DMA transfer doesn't complete
1557  * quickly enough. Usually this means there is something seriously wrong
1558  * with the hardware/software, but it could just be that the controller
1559  * has decided to do a long rewind, just when I didn't expect it.
1560  * Just try again.
1561  */
1562 static void qic02_tape_times_out(unsigned long dummy)
1563 {
1564         printk("time-out in %s driver\n", TPQIC02_NAME);
1565         if ((status_cmd_pending > 0) || dma_mode) {
1566                 /* takes tooo long, shut it down */
1567                 status_dead = YES;
1568                 status_cmd_pending = 0;
1569                 status_timer_on = NO;
1570                 status_expect_int = NO;
1571                 status_error = YES;
1572                 if (dma_mode) {
1573                         dma_mode = 0;   /* signal end to read/write routine */
1574                         wake_up(&qic02_tape_transfer);
1575                 }
1576         }
1577 }                               /* qic02_tape_times_out */
1578
1579 /*
1580  * Interrupt handling:
1581  *
1582  * 1) Interrupt is generated iff at the end of 
1583  *    a 512-DMA-block transfer.
1584  * 2) EXCEPTION is not raised unless something 
1585  *    is wrong or EOT/FM is detected.
1586  * 3) FM EXCEPTION is set *after* the last byte has
1587  *    been transferred by DMA. By the time the interrupt
1588  *    is handled, the EXCEPTION may already be set.
1589  *
1590  * So,
1591  * 1) On EXCEPTION, assume data has been transferred, so
1592  *    continue as usual, but set a flag to indicate the
1593  *    exception was detected.
1594  *    Do a sense status when the flag is found set.
1595  * 2) Do not attempt to continue a transfer after an exception.
1596  *    [??? What about marginal blocks???????]
1597  */
1598
1599
1600 /* qic02_tape_interrupt() is called when the tape controller completes 
1601  * a DMA transfer.
1602  * We are not allowed to sleep here! 
1603  *
1604  * Check if the transfer was successful, check if we need to transfer
1605  * more. If the buffer contains enough data/is empty enough, signal the
1606  * read/write() thread to copy to/from user space.
1607  * When we are finished, set flags to indicate end, disable timer.
1608  * NOTE: This *must* be fast! 
1609  */
1610 static irqreturn_t qic02_tape_interrupt(int irq, void *dev_id,
1611                                  struct pt_regs *regs)
1612 {
1613         int stat, r, i;
1614         unsigned long flags;
1615
1616         TIMEROFF;
1617
1618         if (status_expect_int) {
1619 #ifdef WANT_EXTRA_FULL_DEBUGGING
1620                 if (TP_DIAGS(current_type))
1621                         printk("@");
1622 #endif
1623                 stat = inb(QIC02_STAT_PORT);    /* Knock, knock */
1624                 if (QIC02_TAPE_IFC == ARCHIVE) {        /* "Who's there?" */
1625                         if (((stat & (AR_STAT_DMADONE)) == 0) &&
1626                             ((stat & (QIC02_STAT_EXCEPTION)) != 0)) {
1627                                 TIMERCONT;
1628                                 return IRQ_NONE;/* "Linux with IRQ sharing" */
1629                         }
1630                 }
1631
1632                 if ((stat & QIC02_STAT_EXCEPTION) == 0) {       /* exception occurred */
1633                         /* Possible causes for an exception during a transfer:
1634                          *      - during a write-cycle: end of tape (EW) hole detected.
1635                          *      - during a read-cycle: filemark or EOD detected.
1636                          *      - something went wrong
1637                          * So don't continue with the next block.
1638                          */
1639                         tpqputs(TPQD_ALWAYS, "isr: exception on tape controller");
1640                         printk("      status %02x\n", stat);
1641                         status_error = TE_EX;
1642
1643                         dma_bytes_done += TAPE_BLKSIZE;
1644
1645                         dma_mode = 0;   /* wake up rw() */
1646                         status_expect_int = NO;
1647                         wake_up(&qic02_tape_transfer);
1648                         return IRQ_HANDLED;
1649                 }
1650                 /* return if tape controller not ready, or
1651                  * if dma channel hasn't finished last byte yet.
1652                  */
1653                 r = 0;
1654
1655                 /* Skip next ready check for Archive controller because
1656                  * it may be busy reading ahead. Weird. --hhb
1657                  */
1658                 if (QIC02_TAPE_IFC == WANGTEK)  /* I think this is a drive-dependency, not IFC -- hhb */
1659                         if (stat & QIC02_STAT_READY) {  /* not ready */
1660                                 tpqputs(TPQD_ALWAYS, "isr: ? Tape controller not ready");
1661                                 r = 1;
1662                         }
1663
1664                 flags = claim_dma_lock();
1665
1666                 if ((i = get_dma_residue(QIC02_TAPE_DMA)) != 0) {
1667                         printk(TPQIC02_NAME ": dma_residue == %x !!!\n", i);
1668                         r = 1;  /* big trouble, but can't do much about it... */
1669                 }
1670
1671                 release_dma_lock(flags);
1672
1673                 if (r)
1674                         return IRQ_HANDLED;
1675
1676                 /* finish DMA cycle */
1677
1678                 /* no errors detected, continue */
1679                 dma_bytes_done += TAPE_BLKSIZE;
1680                 if (dma_bytes_done >= dma_bytes_todo) {
1681                         /* finished! Wakeup rw() */
1682                         dma_mode = 0;
1683                         status_expect_int = NO;
1684                         TPQPUTS("isr: dma_bytes_done");
1685                         wake_up(&qic02_tape_transfer);
1686                 } else {
1687                         /* start next transfer, account for track-switching time */
1688                         mod_timer(&tp_timer, jiffies + 6 * HZ);
1689                         dma_transfer();
1690                 }
1691         } else {
1692                 printk(TPQIC02_NAME ": Unexpected interrupt, stat == %x\n", inb(QIC02_STAT_PORT));
1693         }
1694         return IRQ_HANDLED;
1695 }                               /* qic02_tape_interrupt */
1696
1697
1698 /* read/write routines:
1699  * This code copies between a kernel buffer and a user buffer. The 
1700  * actual data transfer is done using DMA and interrupts. Time-outs
1701  * are also used.
1702  *
1703  * When a filemark is read, we return '0 bytes read' and continue with the
1704  * next file after that.
1705  * When EOM is read, we return '0 bytes read' twice.
1706  * When the EOT marker is detected on writes, '0 bytes read' should be
1707  * returned twice. If user program does a MTNOP after that, 2 additional
1708  * blocks may be written.       ------- FIXME: Implement this correctly  *************************************************
1709  *
1710  * Only read/writes in multiples of 512 bytes are accepted.
1711  * When no bytes are available, we sleep() until they are. The controller will
1712  * generate an interrupt, and we (should) get a wake_up() call.
1713  *
1714  * Simple buffering is used. User program should ensure that a large enough
1715  * buffer is used. Usually the drive does some buffering as well (something
1716  * like 4k or so).
1717  *
1718  * Scott S. Bertilson suggested to continue filling the user buffer, rather
1719  * than waste time on a context switch, when the kernel buffer fills up.
1720  */
1721
1722 /*
1723  * Problem: tar(1) doesn't always read the entire file. Sometimes the entire file
1724  * has been read, but the EOF token is never returned to tar(1), simply because
1725  * tar(1) knows it has already read all of the data it needs. So we must use
1726  * open/release to reset the `reported_read_eof' flag. If we don't, the next read
1727  * request would return the EOF flag for the previous file.
1728  */
1729
1730 static ssize_t qic02_tape_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
1731 {
1732         int type = iminor(filp->f_dentry->d_inode);
1733         unsigned short flags = filp->f_flags;
1734         unsigned long bytes_todo, bytes_done, total_bytes_done = 0;
1735         int stat;
1736
1737         if (status_zombie == YES) {
1738                 tpqputs(TPQD_ALWAYS, "configs not set");
1739                 return -ENXIO;
1740         }
1741
1742         if (TP_DIAGS(current_type))
1743                 printk(TPQIC02_NAME ": request READ, minor=%x, buf=%p, count=%lx, pos=%Lx, flags=%x\n", type, buf,
1744                        (long) count, filp->f_pos, flags);
1745
1746         if (count % TAPE_BLKSIZE) {     /* Only allow mod 512 bytes at a time. */
1747                 tpqputs(TPQD_BLKSZ, "Wrong block size");
1748                 return -EINVAL;
1749         }
1750
1751         /* Just assume everything is ok. Controller will scream if not. */
1752
1753         if (status_bytes_wr) {  /* Once written, no more reads, 'till after WFM. */
1754                 return -EACCES;
1755         }
1756
1757         /* This is rather ugly because it has to implement a finite state
1758          * machine in order to handle the EOF situations properly.
1759          */
1760         while ((signed) count >= 0) {
1761                 bytes_done = 0;
1762                 /* see how much fits in the kernel buffer */
1763                 bytes_todo = TPQBUF_SIZE;
1764                 if (bytes_todo > count) {
1765                         bytes_todo = count;
1766                 }
1767
1768                 /* Must ensure that user program sees exactly one EOF token (==0) */
1769                 if (return_read_eof == YES) {
1770                         if (TPQDBG(DEBUG)) {
1771                                 printk("read: return_read_eof==%d, reported_read_eof==%d, total_bytes_done==%lu\n", return_read_eof, reported_read_eof, total_bytes_done);
1772                         }
1773
1774                         if (reported_read_eof == NO) {
1775                                 /* have not yet returned EOF to user program */
1776                                 if (total_bytes_done > 0) {
1777                                         return total_bytes_done;        /* next time return EOF */
1778                                 } else {
1779                                         reported_read_eof = YES;        /* move on next time */
1780                                         return 0;       /* return EOF */
1781                                 }
1782                         } else {
1783                                 /* Application program has already received EOF
1784                                  * (above), now continue with next file on tape,
1785                                  * if possible.
1786                                  * When the FM is reached, EXCEPTION is set,
1787                                  * causing a sense(). Subsequent read/writes will
1788                                  * continue after the FM.
1789                                  */
1790                 /*********** ?????????? this should check for (EOD|NDT), not EOM, 'cause we can read past EW: ************/
1791                                 if (status_eom_detected) {
1792                                         /* If EOM, nothing left to read, so keep returning EOFs.
1793                                          *** should probably set some flag to avoid clearing
1794                                          *** status_eom_detected through ioctls or something
1795                                          */
1796                                         return 0;
1797                                 } else {
1798                                         /* just eof, there may be more files ahead... */
1799                                         return_read_eof = NO;
1800                                         reported_read_eof = NO;
1801                                         status_eof_detected = NO;       /* reset this too */
1802                                         /*fall through */
1803                                 }
1804                         }
1805                 }
1806
1807                 if (bytes_todo == 0) {
1808                         return total_bytes_done;
1809                 }
1810
1811                 if (bytes_todo > 0) {
1812                         /* start reading data */
1813                         if (is_exception()) {
1814                                 tpqputs(TPQD_DMAX, "is_exception() before start_dma()!");
1815                         }
1816
1817 /******************************************************************
1818  ***** if start_dma() fails because the head is positioned 0 bytes
1819  ***** before the FM, (causing EXCEPTION to be set) return_read_eof should
1820  ***** be set to YES, and we should return total_bytes_done, rather than -ENXIO.
1821  ***** The app should recognize this as an EOF condition.
1822  ***************************************************************************/
1823                         stat = start_dma(READ, bytes_todo);
1824                         if (stat == TE_OK) {
1825                                 /* Wait for transfer to complete, interrupt should wake us */
1826                                 
1827                                 wait_event(qic02_tape_transfer, dma_mode != 0);
1828
1829                                 if (status_error)
1830                                         return_read_eof = YES;
1831
1832                         } else if (stat != TE_END) {
1833                                 /* should do sense() on error here */
1834 #if 0
1835                                 return -ENXIO;
1836 #else
1837                                 printk("Trouble: stat==%02x\n", stat);
1838                                 return_read_eof = YES;
1839                 /*************** check EOF/EOT handling!!!!!! **/
1840 #endif
1841                         }
1842                         end_dma(&bytes_done);
1843                         if (bytes_done > bytes_todo) {
1844                                 tpqputs(TPQD_ALWAYS, "read: Oops, read more bytes than requested");
1845                                 return -EIO;
1846                         }
1847                         /* copy buffer to user-space in one go */
1848                         if (bytes_done > 0) {
1849                                 if (copy_to_user(buf, buffaddr, bytes_done))
1850                                         return -EFAULT;
1851                         }
1852 #if 1
1853                         /* Checks Ton's patch below */
1854                         if ((return_read_eof == NO)  && (status_eof_detected == YES)) {
1855                                 printk(TPQIC02_NAME ": read(): return_read_eof=%d, status_eof_detected=YES. return_read_eof:=YES\n",
1856                                        return_read_eof);
1857                         }
1858 #endif
1859                         if ((bytes_todo != bytes_done) || (status_eof_detected == YES)) {
1860                                 /* EOF or EOM detected. return EOF next time. */
1861                                 return_read_eof = YES;
1862                         }
1863
1864                 }
1865                 /* else: ignore read request for 0 bytes */
1866                 if (bytes_done > 0) {
1867                         status_bytes_rd = YES;
1868                         buf += bytes_done;
1869                         *ppos += bytes_done;
1870                         total_bytes_done += bytes_done;
1871                         count -= bytes_done;
1872                 }
1873         }
1874         tpqputs(TPQD_ALWAYS, "read request for <0 bytes");
1875         return -EINVAL;
1876 }                               /* qic02_tape_read */
1877
1878
1879
1880 /* The drive detects near-EOT by means of the holes in the tape.
1881  * When the holes are detected, there is some space left. The drive
1882  * reports this as a TP_EOM exception. After clearing the exception,
1883  * the drive should accept two extra blocks.
1884  *
1885  * It seems there are some archiver programs that would like to use the
1886  * extra space for writing a continuation marker. The driver should return
1887  * end-of-file to the user program on writes, when the holes are detected.
1888  * If the user-program wants to use the extra space, it should use the
1889  * MTNOP ioctl() to get the generic status register and may then continue
1890  * writing (max 1kB).   ----------- doesn't work yet...............
1891  *
1892  * EOF behaviour on writes:
1893  * If there is enough room, write all of the data.
1894  * If there is insufficient room, write as much as will fit and
1895  * return the amount written. If the requested amount differs from the
1896  * written amount, the application program should recognize that as the
1897  * end of file. Subsequent writes will return -ENOSPC.
1898  * Unless the minor bits specify a rewind-on-close, the tape will not
1899  * be rewound when it is full. The user-program should do that, if desired.
1900  * If the driver were to do that automatically, a user-program could be 
1901  * confused about the EOT/BOT condition after re-opening the tape device.
1902  *
1903  * Multiple volume support: Tar closes the tape device before prompting for
1904  * the next tape. The user may then insert a new tape and tar will open the
1905  * tape device again. The driver will detect an exception status in (No Cartridge)
1906  * and force a rewind. After that tar may continue writing.
1907  */
1908 static ssize_t qic02_tape_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
1909 {
1910         int type = iminor(filp->f_dentry->d_inode);
1911         unsigned short flags = filp->f_flags;
1912         unsigned long bytes_todo, bytes_done, total_bytes_done = 0;
1913
1914         if (status_zombie == YES) {
1915                 tpqputs(TPQD_ALWAYS, "configs not set");
1916                 return -ENXIO;
1917         }
1918
1919         if (TP_DIAGS(current_type)) {
1920                 printk(TPQIC02_NAME ": request WRITE, minor=%x, buf=%p, count=%lx, pos=%Lx, flags=%x\n",
1921                        type, buf, (long) count, filp->f_pos, flags);
1922         }
1923
1924         if (count % TAPE_BLKSIZE) {     /* only allow mod 512 bytes at a time */
1925                 tpqputs(TPQD_BLKSZ, "Wrong block size");
1926                 return -EINVAL;
1927         }
1928
1929         if (mode_access == READ) {
1930                 tpqputs(TPQD_ALWAYS, "Not in write mode");
1931                 return -EACCES;
1932         }
1933
1934         /* open() does a sense() and we can assume the tape isn't changed
1935          * between open() and release(), so the tperror.exs bits will still
1936          * be valid.
1937          */
1938         if ((tperror.exs & TP_ST0) && (tperror.exs & TP_WRP)) {
1939                 tpqputs(TPQD_ALWAYS, "Cartridge is write-protected.");
1940                 return -EACCES; /* don't even try when write protected */
1941         }
1942
1943         if (doing_read == YES) {
1944                 terminate_read(0);
1945         }
1946
1947         while ((signed) count >= 0) {
1948                 /* see how much fits in the kernel buffer */
1949                 bytes_done = 0;
1950                 bytes_todo = TPQBUF_SIZE;
1951                 if (bytes_todo > count) {
1952                         bytes_todo = count;
1953                 }
1954
1955                 if (return_write_eof == YES) {
1956                         /* return_write_eof should be reset on reverse tape movements. */
1957
1958                         if (reported_write_eof == NO) {
1959                                 if (bytes_todo > 0) {
1960                                         tpqputs(TPQD_ALWAYS, "partial write");
1961                                         /* partial write signals EOF to user program */
1962                                 }
1963                                 reported_write_eof = YES;
1964                                 return total_bytes_done;
1965                         } else {
1966                                 return -ENOSPC; /* return error */
1967                         }
1968                 }
1969
1970                 /* Quit when done. */
1971                 if (bytes_todo == 0) {
1972                         return total_bytes_done;
1973                 }
1974
1975                 /* copy from user to DMA buffer and initiate transfer. */
1976                 if (bytes_todo > 0) {
1977                         if (copy_from_user(buffaddr, buf, bytes_todo))
1978                                 return -EFAULT;
1979
1980 /****************** similar problem with read() at FM could happen here at EOT.
1981  ******************/
1982
1983 /***** if at EOT, 0 bytes can be written. start_dma() will
1984  ***** fail and write() will return ENXIO error
1985  *****/
1986                         if (start_dma(WRITE, bytes_todo) != TE_OK) {
1987                                 tpqputs(TPQD_ALWAYS, "write: start_dma() failed");
1988                                 /* should do sense() on error here */
1989                                 return -ENXIO;
1990                                 /*********** FIXTHIS **************/
1991                         }
1992
1993                         /* Wait for write to complete, interrupt should wake us. */
1994                         wait_event(qic02_tape_transfer, (status_error == 0 && dma_mode != 0));
1995
1996                         end_dma(&bytes_done);
1997                         if (bytes_done > bytes_todo) {
1998                                 tpqputs(TPQD_ALWAYS, "write: Oops, wrote more bytes than requested");
1999                                 return -EIO;
2000                         }
2001                         /* If the dma-transfer was aborted because of an exception,
2002                          * status_error will have been set in the interrupt handler.
2003                          * Then end_dma() will do a sense().
2004                          * If the exception was EXC_EOM, the EW-hole was encountered
2005                          * and two more blocks could be written. For the time being we'll
2006                          * just consider this to be the EOT.
2007                          * Otherwise, something Bad happened, such as the maximum number
2008                          * of block-rewrites was exceeded. [e.g. A very bad spot on tape was
2009                          * encountered. Normally short dropouts are compensated for by
2010                          * rewriting the block in error, up to 16 times. I'm not sure
2011                          * QIC-24 drives can do this.]
2012                          */
2013                         if (status_error) {
2014                                 if (status_eom_detected == YES) {
2015                                         tpqputs(TPQD_ALWAYS, "write: EW detected");
2016                                         return_write_eof = YES;
2017                                 } else {
2018                                         /* probably EXC_RWA */
2019                                         tpqputs(TPQD_ALWAYS, "write: dma: error in writing");
2020                                         return -EIO;
2021                                 }
2022                         }
2023                         if (bytes_todo != bytes_done) {
2024                                 /* EOF or EOM detected. return EOT next time. */
2025                                 return_write_eof = YES;
2026                         }
2027                 }
2028                 /* else: ignore write request for 0 bytes. */
2029
2030                 if (bytes_done > 0) {
2031                         status_bytes_wr = YES;
2032                         buf += bytes_done;
2033                         *ppos += bytes_done;
2034                         total_bytes_done += bytes_done;
2035                         count -= bytes_done;
2036                 }
2037         }
2038
2039         tpqputs(TPQD_ALWAYS, "write request for <0 bytes");
2040         if (TPQDBG(DEBUG)) {
2041                 printk(TPQIC02_NAME ": status_bytes_wr %x, buf %p"
2042                        ", total_bytes_done %lx, count %lx\n",
2043                        status_bytes_wr, buf, total_bytes_done,
2044                        (long) count);
2045         }
2046         return -EINVAL;
2047 }                               /* qic02_tape_write */
2048
2049
2050
2051 /* qic02_tape_open()
2052  * We allow the device to be opened, even if it is marked 'dead' because
2053  * we want to be able to reset the tape device without rebooting.
2054  * Only one open tape file at a time, except when minor=255.
2055  * Minor 255 is only allowed for resetting and always returns <0.
2056  * 
2057  * The density command is only allowed when TP_BOM is set. Thus, remember
2058  * the most recently used minor bits. When they are different from the
2059  * remembered values, rewind the tape and set the required density.
2060  * Don't rewind if the minor bits specify density 0.
2061  */
2062
2063 static int qic02_tape_open(struct inode *inode, struct file *filp)
2064 {
2065         static int qic02_tape_open_no_use_count(struct inode *,
2066                                                 struct file *);
2067         int open_error;
2068
2069         open_error = qic02_tape_open_no_use_count(inode, filp);
2070         return open_error;
2071 }
2072
2073 static int qic02_tape_open_no_use_count(struct inode *inode,
2074                                         struct file *filp)
2075 {
2076         int type = iminor(inode);
2077         unsigned short flags = filp->f_flags;
2078         unsigned short dens = 0;
2079         int s;
2080
2081
2082         if (TP_DIAGS(type)) {
2083                 printk("qic02_tape_open: dev=tpqic2(%d), flags=%x     ",
2084                         type, flags);
2085         }
2086
2087         if (type == 255) {      /* special case for resetting */
2088                 if (capable(CAP_SYS_ADMIN)) {
2089                         return (tape_reset(1) == TE_OK) ? -EAGAIN : -ENXIO;
2090                 } else {
2091                         return -EPERM;
2092                 }
2093         }
2094
2095         if (status_dead == YES) {
2096                 /* Allow `mt reset' ioctl() even when already open()ed. */
2097                 return 0;
2098         }
2099
2100         if(test_and_set_bit(0, &tape_open))
2101                 return -EBUSY;
2102                 
2103         if (status_zombie == YES) {
2104                 /* no irq/dma/port stuff allocated yet, no reset done
2105                  * yet, so return until MTSETCONFIG has been done.
2106                  */
2107                 return 0;
2108         }
2109
2110         status_bytes_rd = NO;
2111         status_bytes_wr = NO;
2112
2113         return_read_eof = NO;   /********????????????????*****/
2114         return_write_eof = (status_eot_detected) ? YES : NO;
2115
2116         /* Clear this in case user app close()d before reading EOF token */
2117         status_eof_detected = NO;
2118
2119         reported_read_eof = NO;
2120         reported_write_eof = NO;
2121
2122
2123         switch (flags & O_ACCMODE) {
2124         case O_RDONLY:
2125                 mode_access = READ;
2126                 break;
2127         case O_WRONLY:          /* Fallthru... Strictly speaking this is not correct... */
2128         case O_RDWR:            /* Reads are allowed as long as nothing is written */
2129                 mode_access = WRITE;
2130                 break;
2131         }
2132
2133         /* This is to avoid tape-changed problems (TP_CNI exception).
2134          *
2135          * Since removing the cartridge will not raise an exception,
2136          * we always do a tp_sense() to make sure we have the proper
2137          * CNI status, the 2150L may need an additional sense.... - Eddy
2138          */
2139         s = tp_sense(TP_WRP | TP_EOM | TP_BOM | TP_CNI | TP_EOR);
2140
2141         if (s == TE_OK) {
2142                 /* Try to clear cartridge-changed status for Archive-2150L */
2143                 if ((tperror.exs & TP_ST0) && (tperror.exs & TP_CNI)) {
2144                         s = tp_sense(TP_WRP | TP_EOM | TP_BOM | TP_CNI | TP_EOR);
2145                 }
2146         }
2147
2148         if (s != TE_OK) {
2149                 tpqputs(TPQD_ALWAYS, "open: sense() failed");
2150                 clear_bit(0, &tape_open);
2151                 return -EIO;
2152         }
2153
2154         /* exception bits should be up-to-date now, so check for
2155          * tape presence and exit if absent.
2156          * Even `mt stat' will fail without a tape.
2157          */
2158         if ((tperror.exs & TP_ST0) && (tperror.exs & TP_CNI)) {
2159                 tpqputs(TPQD_ALWAYS, "No tape present.");
2160                 clear_bit(0, &tape_open);
2161                 return -EIO;
2162         }
2163
2164         /* At this point we can assume that a tape is present and
2165          * that it will remain present until release() is called.
2166          */
2167
2168         /* not allowed to do QCMD_DENS_* unless tape is rewound */
2169         if ((TP_DENS(type) != 0) && (TP_DENS(current_type) != TP_DENS(type))) {
2170                 /* force rewind if minor bits have changed,
2171                  * i.e. user wants to use tape in different format.
2172                  * [assuming single drive operation]
2173                  */
2174                 if (TP_HAVE_DENS) {
2175                         tpqputs(TPQD_REWIND, "Density minor bits have changed. Forcing rewind.");
2176                         need_rewind = YES;
2177                 }
2178         } else {
2179                 /* density bits still the same, but TP_DIAGS bit 
2180                  * may have changed.
2181                  */
2182                 current_type = type;
2183         }
2184
2185         if (need_rewind == YES) {
2186 /***************** CHECK THIS!!!!!!!! **********/
2187                 s = do_qic_cmd(QCMD_REWIND, TIM_R);
2188                 if (s != 0) {
2189                         tpqputs(TPQD_ALWAYS, "open: rewind failed");
2190                         return -EIO;
2191                 }
2192         }
2193
2194
2195 /* Note: After a reset command, the controller will rewind the tape
2196  *       just before performing any tape movement operation! ************ SO SET need_rewind flag!!!!!
2197  */
2198         if (status_dead == YES) {
2199                 tpqputs(TPQD_ALWAYS, "open: tape dead, attempting reset");
2200                 if (tape_reset(1) != TE_OK) {
2201                         return -ENXIO;
2202                 } else {
2203                         status_dead = NO;
2204                         if (tp_sense(~(TP_ST1 | TP_ILL)) != TE_OK) {
2205                                 tpqputs(TPQD_ALWAYS, "open: tp_sense() failed\n");
2206                                 status_dead = YES;      /* try reset next time */
2207                                 return -EIO;
2208                         }
2209                 }
2210         }
2211
2212         /* things should be ok, once we get here */
2213
2214
2215         /* set density: only allowed when TP_BOM status bit is set,
2216          * so we must have done a rewind by now. If not, just skip over.
2217          * Only give set density command when minor bits have changed.
2218          */
2219         if (TP_DENS(current_type) == TP_DENS(type)) {
2220                 return 0;
2221         }
2222
2223         current_type = type;
2224         need_rewind = NO;
2225         if (TP_HAVE_DENS) {
2226                 dens = TP_DENS(type);
2227         }
2228
2229         if (dens < sizeof(format_names) / sizeof(char *))
2230                 printk(TPQIC02_NAME ": format: %s%s\n", (dens != 0) ? "QIC-" : "", format_names[dens]);
2231         else
2232                 tpqputs(TPQD_REWIND, "Wait for retensioning...");
2233
2234         switch (TP_DENS(type)) {
2235         case 0:         /* Minor 0 is for drives without set-density support */
2236                 s = 0;
2237                 break;
2238         case 1:
2239                 s = do_qic_cmd(QCMD_DENS_11, TIM_S);
2240                 break;
2241         case 2:
2242                 s = do_qic_cmd(QCMD_DENS_24, TIM_S);
2243                 break;
2244         case 3:
2245                 s = do_qic_cmd(QCMD_DENS_120, TIM_S);
2246                 break;
2247         case 4:
2248                 s = do_qic_cmd(QCMD_DENS_150, TIM_S);
2249                 break;
2250         case 5:
2251                 s = do_qic_cmd(QCMD_DENS_300, TIM_S);
2252                 break;
2253         case 6:
2254                 s = do_qic_cmd(QCMD_DENS_600, TIM_S);
2255                 break;
2256         default:                /* otherwise do a retension before anything else */
2257                 s = do_qic_cmd(QCMD_RETEN, TIM_R);
2258         }
2259         if (s != 0) {
2260                 status_dead = YES;      /* force reset */
2261                 current_type = 0;/* earlier 0xff80 */
2262                 return -EIO;
2263         }
2264
2265         return 0;
2266 }                               /* qic02_tape_open */
2267
2268
2269 static int qic02_tape_release(struct inode *inode, struct file *filp)
2270 {
2271         int type = iminor(inode);
2272
2273         if (TP_DIAGS(type)) {
2274                 printk("qic02_tape_release: dev=tpqic2(%d)\n", type);
2275         }
2276
2277         if (status_zombie == NO) {      /* don't rewind in zombie mode */
2278                 /* Terminate any pending write cycle. Terminating the read-cycle
2279                  * is delayed until it is required to do so for a new command.
2280                  */
2281                 terminate_write(-1);
2282
2283                 if (status_dead == YES) {
2284                         tpqputs(TPQD_ALWAYS, "release: device dead!?");
2285                 }
2286
2287                 /* Rewind only if minor number requires it AND 
2288                  * read/writes have been done. ************* IS THIS CORRECT??????????
2289                  */
2290                 if (TP_REWCLOSE(type) && (status_bytes_rd | status_bytes_wr)) {
2291                         tpqputs(TPQD_REWIND, "release: Doing rewind...");
2292                         (void) do_qic_cmd(QCMD_REWIND, TIM_R);
2293                 }
2294         }
2295         clear_bit(0, &tape_open);
2296         return 0;
2297 }                               /* qic02_tape_release */
2298
2299
2300 #ifdef CONFIG_QIC02_DYNCONF
2301 /* Set masks etc. based on the interface card type. */
2302 static int update_ifc_masks(int ifc)
2303 {
2304         QIC02_TAPE_IFC = ifc;
2305
2306         if ((QIC02_TAPE_IFC == WANGTEK) || (QIC02_TAPE_IFC == EVEREX)) {
2307                 QIC02_STAT_PORT = QIC02_TAPE_PORT;
2308                 QIC02_CTL_PORT = QIC02_TAPE_PORT;
2309                 QIC02_CMD_PORT = QIC02_TAPE_PORT + 1;
2310                 QIC02_DATA_PORT = QIC02_TAPE_PORT + 1;
2311                 QIC02_STAT_READY = WT_QIC02_STAT_READY;
2312                 QIC02_STAT_EXCEPTION = WT_QIC02_STAT_EXCEPTION;
2313                 QIC02_STAT_MASK = WT_QIC02_STAT_MASK;
2314
2315                 QIC02_STAT_RESETMASK = WT_QIC02_STAT_RESETMASK;
2316                 QIC02_STAT_RESETVAL = WT_QIC02_STAT_RESETVAL;
2317
2318                 QIC02_CTL_RESET = WT_QIC02_CTL_RESET;
2319                 QIC02_CTL_REQUEST = WT_QIC02_CTL_REQUEST;
2320
2321                 if (QIC02_TAPE_DMA == 3) {
2322                         WT_CTL_DMA = WT_CTL_DMA3;
2323                 } else if (QIC02_TAPE_DMA == 1) {
2324                         WT_CTL_DMA = WT_CTL_DMA1;
2325                 } else {
2326                         tpqputs(TPQD_ALWAYS,
2327                                 "Unsupported or incorrect DMA channel");
2328                         return -EIO;
2329                 }
2330
2331                 if (QIC02_TAPE_IFC == EVEREX) {
2332                         /* Everex is a special case for Wangtek (actually
2333                          * it's the other way 'round, but I saw Wangtek first)
2334                          */
2335                         if (QIC02_TAPE_DMA == 3) {
2336                                 WT_CTL_DMA = WT_CTL_DMA1;
2337                         }
2338
2339                         /* Fixup the kernel copy of the IFC type to that
2340                          * we don't have to distinguish between Wangtek and
2341                          * and Everex at runtime.
2342                          */
2343                         QIC02_TAPE_IFC = WANGTEK;
2344                 }
2345         } else if (QIC02_TAPE_IFC == ARCHIVE) {
2346                 QIC02_STAT_PORT = QIC02_TAPE_PORT + 1;
2347                 QIC02_CTL_PORT = QIC02_TAPE_PORT + 1;
2348                 QIC02_CMD_PORT = QIC02_TAPE_PORT;
2349                 QIC02_DATA_PORT = QIC02_TAPE_PORT;
2350                 QIC02_STAT_READY = AR_QIC02_STAT_READY;
2351                 QIC02_STAT_EXCEPTION = AR_QIC02_STAT_EXCEPTION;
2352                 QIC02_STAT_MASK = AR_QIC02_STAT_MASK;
2353
2354                 QIC02_STAT_RESETMASK = AR_QIC02_STAT_RESETMASK;
2355                 QIC02_STAT_RESETVAL = AR_QIC02_STAT_RESETVAL;
2356
2357                 QIC02_CTL_RESET = AR_QIC02_CTL_RESET;
2358                 QIC02_CTL_REQUEST = AR_QIC02_CTL_REQUEST;
2359
2360                 if (QIC02_TAPE_DMA > 3) {
2361                         tpqputs(TPQD_ALWAYS,
2362                                 "Unsupported or incorrect DMA channel");
2363                         return -EIO;
2364                 }
2365         } else if (QIC02_TAPE_IFC == MOUNTAIN) {
2366                 QIC02_STAT_PORT = QIC02_TAPE_PORT + 1;
2367                 QIC02_CTL_PORT = QIC02_TAPE_PORT + 1;
2368                 QIC02_CMD_PORT = QIC02_TAPE_PORT;
2369                 QIC02_DATA_PORT = QIC02_TAPE_PORT;
2370
2371                 QIC02_STAT_READY = MTN_QIC02_STAT_READY;
2372                 QIC02_STAT_EXCEPTION = MTN_QIC02_STAT_EXCEPTION;
2373                 QIC02_STAT_MASK = MTN_QIC02_STAT_MASK;
2374
2375                 QIC02_STAT_RESETMASK = MTN_QIC02_STAT_RESETMASK;
2376                 QIC02_STAT_RESETVAL = MTN_QIC02_STAT_RESETVAL;
2377
2378                 QIC02_CTL_RESET = MTN_QIC02_CTL_RESET;
2379                 QIC02_CTL_REQUEST = MTN_QIC02_CTL_REQUEST;
2380
2381                 if (QIC02_TAPE_DMA > 3) {
2382                         tpqputs(TPQD_ALWAYS,
2383                                 "Unsupported or incorrect DMA channel");
2384                         return -EIO;
2385                 }
2386         } else {
2387                 tpqputs(TPQD_ALWAYS, "Invalid interface type");
2388                 return -ENXIO;
2389         }
2390         return qic02_get_resources();
2391 }                               /* update_ifc_masks */
2392 #endif
2393
2394
2395 /* ioctl allows user programs to rewind the tape and stuff like that */
2396 static int qic02_tape_ioctl(struct inode *inode, struct file *filp, unsigned int iocmd, unsigned long ioarg)
2397 {
2398         int error;
2399         int c;
2400         struct mtop operation;
2401         unsigned char blk_addr[6];
2402         struct mtpos ioctl_tell;
2403         void __user *argp = (void __user *)ioarg;
2404
2405
2406         if (TP_DIAGS(current_type))
2407                 printk(TPQIC02_NAME ": ioctl(%4x, %4lx)\n", iocmd, ioarg);
2408
2409         if (!inode)
2410                 return -EINVAL;
2411
2412         /* check iocmd first */
2413
2414         c = _IOC_NR(iocmd);
2415
2416 #ifdef CONFIG_QIC02_DYNCONF
2417         if (c == _IOC_NR(MTIOCGETCONFIG)) {
2418                 CHECK_IOC_SIZE(mtconfiginfo);
2419
2420                 if (copy_to_user(argp, &qic02_tape_dynconf, sizeof(qic02_tape_dynconf)))
2421                         return -EFAULT;
2422                 return 0;
2423         } else if (c == _IOC_NR(MTIOCSETCONFIG)) {
2424                 /* One should always do a MTIOCGETCONFIG first, then update
2425                  * user-settings, then write back with MTIOCSETCONFIG.
2426                  * The qic02conf program should re-open() the device before actual
2427                  * use, to make sure everything is initialized.
2428                  */
2429
2430                 CHECK_IOC_SIZE(mtconfiginfo);
2431
2432                 if (!capable(CAP_SYS_RAWIO))
2433                         return -EPERM;
2434
2435                 if (doing_read != NO || doing_write != NO)
2436                         return -EBUSY;
2437
2438                 if (status_zombie == NO)
2439                         qic02_release_resources();      /* and go zombie */
2440
2441                 /* copy struct from user space to kernel space */
2442                 if (copy_from_user(&qic02_tape_dynconf, argp, sizeof(qic02_tape_dynconf)))
2443                         return -EFAULT;
2444                 
2445                 return update_ifc_masks(qic02_tape_dynconf.ifc_type);
2446         }
2447         if (status_zombie == YES) {
2448                 tpqputs(TPQD_ALWAYS, "Configs not set");
2449                 return -ENXIO;
2450         }
2451 #endif
2452         if (c == _IOC_NR(MTIOCTOP)) {
2453                 CHECK_IOC_SIZE(mtop);
2454
2455                 /* copy mtop struct from user space to kernel space */
2456                 if (copy_from_user(&operation, argp, sizeof(operation)))
2457                         return -EFAULT;
2458
2459                 /* ---note: mt_count is signed, negative seeks must be
2460                  * ---      translated to seeks in opposite direction!
2461                  * (only needed for Sun-programs, I think.)
2462                  */
2463                 /* ---note: MTFSF with count 0 should position the
2464                  * ---      tape at the beginning of the current file.
2465                  */
2466
2467                 if (TP_DIAGS(current_type))
2468                         printk("OP op=%4x, count=%4x\n", operation.mt_op, operation.mt_count);
2469
2470                 if (operation.mt_count < 0)
2471                         tpqputs(TPQD_ALWAYS, "Warning: negative mt_count ignored");
2472
2473                 ioctl_status.mt_resid = operation.mt_count;
2474                 if (operation.mt_op == MTSEEK) {
2475                         if (!TP_HAVE_SEEK)
2476                                 return -ENOTTY;
2477
2478                         seek_addr_buf[0] = (operation.mt_count >> 16) & 0xff;
2479                         seek_addr_buf[1] = (operation.mt_count >> 8) & 0xff;
2480                         seek_addr_buf[2] = (operation.mt_count) & 0xff;
2481                         if (operation.mt_count >> 24)
2482                                 return -EINVAL;
2483                         
2484                         if ((error = do_ioctl_cmd(operation.mt_op)) != 0)
2485                                 return error;
2486
2487                         ioctl_status.mt_resid = 0;
2488                 } else {
2489                         while (operation.mt_count > 0) {
2490                                 operation.mt_count--;
2491                                 if ((error = do_ioctl_cmd(operation.mt_op)) != 0)
2492                                         return error;
2493
2494                                 ioctl_status.mt_resid = operation.mt_count;
2495                         }
2496                 }
2497                 return 0;
2498
2499         } else if (c == _IOC_NR(MTIOCGET)) {
2500                 if (TP_DIAGS(current_type))
2501                         printk("GET ");
2502
2503                 CHECK_IOC_SIZE(mtget);
2504
2505                 /* It appears (gmt(1)) that it is normal behaviour to
2506                  * first set the status with MTNOP, and then to read
2507                  * it out with MTIOCGET
2508                  */
2509
2510                 /* copy results to user space */
2511                 if (copy_to_user(argp, &ioctl_status, sizeof(ioctl_status)))
2512                         return -EFAULT;
2513                 return 0;
2514         } else if (TP_HAVE_TELL && (c == _IOC_NR(MTIOCPOS))) {
2515                 if (TP_DIAGS(current_type))
2516                         printk("POS ");
2517
2518                 CHECK_IOC_SIZE(mtpos);
2519
2520                 tpqputs(TPQD_IOCTLS, "MTTELL reading block address");
2521                 if (doing_read == YES || doing_write == YES)
2522                         finish_rw(AR_QCMDV_TELL_BLK);
2523
2524                 c = rdstatus((char *) blk_addr, sizeof(blk_addr), AR_QCMDV_TELL_BLK);
2525                 if (c != TE_OK)
2526                         return -EIO;
2527
2528                 ioctl_tell.mt_blkno = (blk_addr[3] << 16) | (blk_addr[4] << 8) | blk_addr[5];
2529
2530                 /* copy results to user space */
2531                 if (copy_to_user(argp, &ioctl_tell, sizeof(ioctl_tell)))
2532                         return -EFAULT;
2533                 return 0;
2534
2535         } else
2536                 return -ENOTTY; /* Other cmds not supported. */
2537 }                               /* qic02_tape_ioctl */
2538
2539
2540 static ssize_t qic02_do_tape_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
2541 {
2542         int err;
2543         
2544         down(&tape_op); 
2545         err = qic02_tape_read(filp, buf, count, ppos);
2546         up(&tape_op);
2547         
2548         return err;
2549 }
2550
2551 static ssize_t qic02_do_tape_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
2552 {
2553         int err;
2554
2555         down(&tape_op); 
2556         err = qic02_tape_write(filp, buf, count, ppos);
2557         up(&tape_op);
2558         
2559         return err;
2560 }
2561
2562 static int qic02_do_tape_ioctl(struct inode *inode, struct file *filp, unsigned int iocmd, unsigned long ioarg)
2563 {
2564         int err;
2565         
2566         down(&tape_op); 
2567         err = qic02_tape_ioctl(inode, filp,  iocmd, ioarg);
2568         up(&tape_op);
2569         
2570         return err;
2571 }
2572
2573 /* These are (most) of the interface functions: */
2574 static struct file_operations qic02_tape_fops = {
2575         .owner = THIS_MODULE,
2576         .llseek = no_llseek,
2577         .read = qic02_do_tape_read,
2578         .write = qic02_do_tape_write,
2579         .ioctl = qic02_do_tape_ioctl,
2580         .open = qic02_tape_open,
2581         .release = qic02_tape_release,
2582 };
2583
2584
2585 static void qic02_release_resources(void)
2586 {
2587         free_irq(QIC02_TAPE_IRQ, NULL);
2588         free_dma(QIC02_TAPE_DMA);
2589         release_region(QIC02_TAPE_PORT, QIC02_TAPE_PORT_RANGE);
2590         if (buffaddr)
2591                 free_pages((unsigned long) buffaddr, get_order(TPQBUF_SIZE));
2592         buffaddr = 0;           /* Better to cause a panic than overwite someone else */
2593         status_zombie = YES;
2594 }                               /* qic02_release_resources */
2595
2596
2597 static int qic02_get_resources(void)
2598 {
2599         /* First perform some checks. If one of them fails,
2600          * the tape driver will not be registered to the system.
2601          */
2602
2603         /* for DYNCONF, allocating IO, DMA and IRQ should not be done until 
2604          * the config parameters have been set using MTSETCONFIG.
2605          */
2606
2607         /* Grab the IO region. */
2608         if (!request_region(QIC02_TAPE_PORT, QIC02_TAPE_PORT_RANGE, TPQIC02_NAME)) {
2609                 printk(TPQIC02_NAME ": IO space at 0x%x [%d ports] already reserved\n",
2610                        QIC02_TAPE_PORT, QIC02_TAPE_PORT_RANGE);
2611                 return -ENXIO;
2612         }
2613
2614         /* get IRQ */
2615         if (request_irq(QIC02_TAPE_IRQ, qic02_tape_interrupt, SA_INTERRUPT, "QIC-02", NULL)) {
2616                 printk(TPQIC02_NAME ": can't allocate IRQ%d for QIC-02 tape\n", QIC02_TAPE_IRQ);
2617                 release_region(QIC02_TAPE_PORT, QIC02_TAPE_PORT_RANGE);
2618                 return -EBUSY;
2619         }
2620
2621         /* After IRQ, allocate DMA channel */
2622         if (request_dma(QIC02_TAPE_DMA, "QIC-02")) {
2623                 printk(TPQIC02_NAME ": can't allocate DMA%d for QIC-02 tape\n", QIC02_TAPE_DMA);
2624                 free_irq(QIC02_TAPE_IRQ, NULL);
2625                 release_region(QIC02_TAPE_PORT, QIC02_TAPE_PORT_RANGE);
2626                 return -EBUSY;
2627         }
2628
2629         /* Setup the page-address for the dma transfer. */
2630         buffaddr = (void *) __get_dma_pages(GFP_KERNEL, get_order(TPQBUF_SIZE));
2631         if (!buffaddr) {
2632                 qic02_release_resources();
2633                 return -EBUSY;  /* Not ideal, EAGAIN perhaps? */
2634         }
2635
2636         memset(buffaddr, 0, TPQBUF_SIZE);
2637
2638         printk(TPQIC02_NAME ": Settings: IRQ %d, DMA %d, IO 0x%x, IFC %s\n",
2639                QIC02_TAPE_IRQ, QIC02_TAPE_DMA, ((QIC02_TAPE_IFC == ARCHIVE)
2640                                                 || (QIC02_TAPE_IFC ==
2641                                                     MOUNTAIN)) ?
2642                QIC02_CMD_PORT : QIC02_STAT_PORT,
2643                (QIC02_TAPE_IFC ==
2644                 MOUNTAIN) ? "Mountain" : ((QIC02_TAPE_IFC ==
2645                                            ARCHIVE) ? "Archive" :
2646                                           "Wangtek"));
2647
2648         if (tape_reset(0) != TE_OK || tp_sense(TP_WRP | TP_POR | TP_CNI) != TE_OK) {
2649                 /* No drive detected, so vanish */
2650                 tpqputs(TPQD_ALWAYS, "No drive detected -- releasing IO/IRQ/DMA.");
2651                 status_dead = YES;
2652                 qic02_release_resources();
2653                 return -EIO;
2654         }
2655
2656         /* All should be ok now */
2657         status_zombie = NO;
2658         return 0;
2659 }                               /* qic02_get_resources */
2660
2661 int __init qic02_tape_init(void)
2662 {
2663         if (TPSTATSIZE != 6) {
2664                 printk(TPQIC02_NAME ": internal error: tpstatus struct incorrect!\n");
2665                 return -ENODEV;
2666         }
2667         if ((TPQBUF_SIZE < 512) || (TPQBUF_SIZE >= 0x10000)) {
2668                 printk(TPQIC02_NAME ": internal error: DMA buffer size out of range\n");
2669                 return -ENODEV;
2670         }
2671
2672         current_type = 0;
2673
2674 #ifndef CONFIG_QIC02_DYNCONF
2675         printk(TPQIC02_NAME ": IRQ %d, DMA %d, IO 0x%x, IFC %s, %s, %s\n",
2676                QIC02_TAPE_IRQ, QIC02_TAPE_DMA,
2677 # if QIC02_TAPE_IFC == WANGTEK
2678                QIC02_STAT_PORT, "Wangtek",
2679 # elif QIC02_TAPE_IFC == ARCHIVE
2680                QIC02_CMD_PORT, "Archive",
2681 # elif QIC02_TAPE_IFC == MOUNTAIN
2682                QIC02_CMD_PORT, "Mountain",
2683 # else
2684 #  error
2685 # endif
2686                rcs_revision, rcs_date);
2687         if (qic02_get_resources())
2688                 return -ENODEV;
2689 #else
2690         printk(TPQIC02_NAME ": Runtime config, %s, %s\n", rcs_revision, rcs_date);
2691 #endif
2692         printk(TPQIC02_NAME ": DMA buffers: %u blocks\n", NR_BLK_BUF);
2693         /* If we got this far, install driver functions */
2694         if (register_chrdev(QIC02_TAPE_MAJOR, TPQIC02_NAME, &qic02_tape_fops)) 
2695         {
2696                 printk(TPQIC02_NAME ": Unable to get chrdev major %d\n", QIC02_TAPE_MAJOR);
2697 #ifndef CONFIG_QIC02_DYNCONF
2698                 qic02_release_resources();
2699 #endif
2700                 return -ENODEV;
2701         }
2702
2703         tpqic02_class = class_simple_create(THIS_MODULE, TPQIC02_NAME);
2704         class_simple_device_add(tpqic02_class, MKDEV(QIC02_TAPE_MAJOR, 2), NULL, "ntpqic11");
2705         devfs_mk_cdev(MKDEV(QIC02_TAPE_MAJOR, 2),
2706                        S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, "ntpqic11");
2707         class_simple_device_add(tpqic02_class, MKDEV(QIC02_TAPE_MAJOR, 3), NULL, "tpqic11");
2708         devfs_mk_cdev(MKDEV(QIC02_TAPE_MAJOR, 3),
2709                        S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, "tpqic11");
2710
2711         class_simple_device_add(tpqic02_class, MKDEV(QIC02_TAPE_MAJOR, 4), NULL, "ntpqic24");
2712         devfs_mk_cdev(MKDEV(QIC02_TAPE_MAJOR, 4),
2713                        S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, "ntpqic24");
2714         class_simple_device_add(tpqic02_class, MKDEV(QIC02_TAPE_MAJOR, 5), NULL, "tpqic24");
2715         devfs_mk_cdev(MKDEV(QIC02_TAPE_MAJOR, 5),
2716                        S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, "tpqic24");
2717
2718         class_simple_device_add(tpqic02_class, MKDEV(QIC02_TAPE_MAJOR, 6), NULL, "ntpqic20");
2719         devfs_mk_cdev(MKDEV(QIC02_TAPE_MAJOR, 6),
2720                        S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, "ntpqic120");
2721         class_simple_device_add(tpqic02_class, MKDEV(QIC02_TAPE_MAJOR, 7), NULL, "tpqic20");
2722         devfs_mk_cdev(MKDEV(QIC02_TAPE_MAJOR, 7),
2723                        S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, "tpqic120");
2724
2725         class_simple_device_add(tpqic02_class, MKDEV(QIC02_TAPE_MAJOR, 8), NULL, "ntpqic50");
2726         devfs_mk_cdev(MKDEV(QIC02_TAPE_MAJOR, 8),
2727                        S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, "ntpqic150");
2728         class_simple_device_add(tpqic02_class, MKDEV(QIC02_TAPE_MAJOR, 9), NULL, "tpqic50");
2729         devfs_mk_cdev(MKDEV(QIC02_TAPE_MAJOR, 9),
2730                        S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP, "tpqic150");
2731
2732         init_waitqueue_head(&qic02_tape_transfer);
2733         /* prepare timer */
2734         TIMEROFF;
2735         init_timer(&tp_timer);
2736         tp_timer.function = qic02_tape_times_out;
2737
2738 #ifndef CONFIG_QIC02_DYNCONF
2739         if (tape_reset(0) != TE_OK || tp_sense(TP_WRP | TP_POR | TP_CNI) != TE_OK) {
2740                 /* No drive detected, so vanish */
2741                 tpqputs(TPQD_ALWAYS, "No drive detected -- driver going on vacation...");
2742                 qic02_release_resources();
2743                 status_dead = YES;
2744                 return -ENODEV;
2745         } else {
2746                 if (is_exception()) {
2747                         tpqputs(TPQD_ALWAYS, "exception detected\n");
2748                         (void) tp_sense(TP_WRP | TP_POR | TP_CNI);
2749                 }
2750         }
2751 #endif
2752
2753         /* initialize generic status for ioctl requests */
2754
2755         ioctl_status.mt_type = QIC02_TAPE_DRIVE;        /* MT_IS* id nr */
2756
2757         ioctl_status.mt_resid = 0;      /* ---residual count */
2758         ioctl_status.mt_gstat = 0;      /* ---generic status */
2759         ioctl_status.mt_erreg = 0;      /* not used */
2760         ioctl_status.mt_fileno = 0;     /* number of current file on tape */
2761         ioctl_status.mt_blkno = 0;      /* number of current (logical) block */
2762
2763         return 0;
2764 }                               /* qic02_tape_init */
2765
2766 static void qic02_module_exit(void)
2767 {
2768         unregister_chrdev(QIC02_TAPE_MAJOR, TPQIC02_NAME);
2769         if (status_zombie == NO)
2770                 qic02_release_resources();
2771                 
2772         devfs_remove("ntpqic11");
2773         class_simple_device_remove(MKDEV(QIC02_TAPE_MAJOR, 2));
2774         devfs_remove("tpqic11");
2775         class_simple_device_remove(MKDEV(QIC02_TAPE_MAJOR, 3));
2776         devfs_remove("ntpqic24");
2777         class_simple_device_remove(MKDEV(QIC02_TAPE_MAJOR, 4));
2778         devfs_remove("tpqic24");
2779         class_simple_device_remove(MKDEV(QIC02_TAPE_MAJOR, 5));
2780         devfs_remove("ntpqic120");
2781         class_simple_device_remove(MKDEV(QIC02_TAPE_MAJOR, 6));
2782         devfs_remove("tpqic120");
2783         class_simple_device_remove(MKDEV(QIC02_TAPE_MAJOR, 7));
2784         devfs_remove("ntpqic150");
2785         class_simple_device_remove(MKDEV(QIC02_TAPE_MAJOR, 8));
2786         devfs_remove("tpqic150");
2787         class_simple_device_remove(MKDEV(QIC02_TAPE_MAJOR, 9));
2788
2789         class_simple_destroy(tpqic02_class);
2790 }
2791
2792 static int qic02_module_init(void)
2793 {
2794         int retval;
2795         retval = qic02_tape_init();
2796 # ifdef CONFIG_QIC02_DYNCONF
2797         /* This allows the dynamic config program to setup the card
2798          * by presetting qic02_tape_dynconf via insmod
2799          */
2800         if (!retval && qic02_tape_dynconf.ifc_type) {
2801                 retval = update_ifc_masks(qic02_tape_dynconf.ifc_type);
2802                 if (retval) {
2803                         qic02_module_exit();
2804                 }
2805         }
2806 # endif
2807         return retval;
2808 }
2809
2810 MODULE_LICENSE("GPL");
2811
2812 module_init(qic02_module_init);
2813 module_exit(qic02_module_exit);