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