ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / ide / ide-tape.c
1 /*
2  * linux/drivers/ide/ide-tape.c         Version 1.19    Nov, 2003
3  *
4  * Copyright (C) 1995 - 1999 Gadi Oxman <gadio@netvision.net.il>
5  *
6  * $Header$
7  *
8  * This driver was constructed as a student project in the software laboratory
9  * of the faculty of electrical engineering in the Technion - Israel's
10  * Institute Of Technology, with the guide of Avner Lottem and Dr. Ilana David.
11  *
12  * It is hereby placed under the terms of the GNU general public license.
13  * (See linux/COPYING).
14  */
15  
16 /*
17  * IDE ATAPI streaming tape driver.
18  *
19  * This driver is a part of the Linux ide driver and works in co-operation
20  * with linux/drivers/block/ide.c.
21  *
22  * The driver, in co-operation with ide.c, basically traverses the 
23  * request-list for the block device interface. The character device
24  * interface, on the other hand, creates new requests, adds them
25  * to the request-list of the block device, and waits for their completion.
26  *
27  * Pipelined operation mode is now supported on both reads and writes.
28  *
29  * The block device major and minor numbers are determined from the
30  * tape's relative position in the ide interfaces, as explained in ide.c.
31  *
32  * The character device interface consists of the following devices:
33  *
34  * ht0          major 37, minor 0       first  IDE tape, rewind on close.
35  * ht1          major 37, minor 1       second IDE tape, rewind on close.
36  * ...
37  * nht0         major 37, minor 128     first  IDE tape, no rewind on close.
38  * nht1         major 37, minor 129     second IDE tape, no rewind on close.
39  * ...
40  *
41  * Run linux/scripts/MAKEDEV.ide to create the above entries.
42  *
43  * The general magnetic tape commands compatible interface, as defined by
44  * include/linux/mtio.h, is accessible through the character device.
45  *
46  * General ide driver configuration options, such as the interrupt-unmask
47  * flag, can be configured by issuing an ioctl to the block device interface,
48  * as any other ide device.
49  *
50  * Our own ide-tape ioctl's can be issued to either the block device or
51  * the character device interface.
52  *
53  * Maximal throughput with minimal bus load will usually be achieved in the
54  * following scenario:
55  *
56  *      1.      ide-tape is operating in the pipelined operation mode.
57  *      2.      No buffering is performed by the user backup program.
58  *
59  * Testing was done with a 2 GB CONNER CTMA 4000 IDE ATAPI Streaming Tape Drive.
60  * 
61  * Ver 0.1   Nov  1 95   Pre-working code :-)
62  * Ver 0.2   Nov 23 95   A short backup (few megabytes) and restore procedure
63  *                        was successful ! (Using tar cvf ... on the block
64  *                        device interface).
65  *                       A longer backup resulted in major swapping, bad
66  *                        overall Linux performance and eventually failed as
67  *                        we received non serial read-ahead requests from the
68  *                        buffer cache.
69  * Ver 0.3   Nov 28 95   Long backups are now possible, thanks to the
70  *                        character device interface. Linux's responsiveness
71  *                        and performance doesn't seem to be much affected
72  *                        from the background backup procedure.
73  *                       Some general mtio.h magnetic tape operations are
74  *                        now supported by our character device. As a result,
75  *                        popular tape utilities are starting to work with
76  *                        ide tapes :-)
77  *                       The following configurations were tested:
78  *                              1. An IDE ATAPI TAPE shares the same interface
79  *                                 and irq with an IDE ATAPI CDROM.
80  *                              2. An IDE ATAPI TAPE shares the same interface
81  *                                 and irq with a normal IDE disk.
82  *                        Both configurations seemed to work just fine !
83  *                        However, to be on the safe side, it is meanwhile
84  *                        recommended to give the IDE TAPE its own interface
85  *                        and irq.
86  *                       The one thing which needs to be done here is to
87  *                        add a "request postpone" feature to ide.c,
88  *                        so that we won't have to wait for the tape to finish
89  *                        performing a long media access (DSC) request (such
90  *                        as a rewind) before we can access the other device
91  *                        on the same interface. This effect doesn't disturb
92  *                        normal operation most of the time because read/write
93  *                        requests are relatively fast, and once we are
94  *                        performing one tape r/w request, a lot of requests
95  *                        from the other device can be queued and ide.c will
96  *                        service all of them after this single tape request.
97  * Ver 1.0   Dec 11 95   Integrated into Linux 1.3.46 development tree.
98  *                       On each read / write request, we now ask the drive
99  *                        if we can transfer a constant number of bytes
100  *                        (a parameter of the drive) only to its buffers,
101  *                        without causing actual media access. If we can't,
102  *                        we just wait until we can by polling the DSC bit.
103  *                        This ensures that while we are not transferring
104  *                        more bytes than the constant referred to above, the
105  *                        interrupt latency will not become too high and
106  *                        we won't cause an interrupt timeout, as happened
107  *                        occasionally in the previous version.
108  *                       While polling for DSC, the current request is
109  *                        postponed and ide.c is free to handle requests from
110  *                        the other device. This is handled transparently to
111  *                        ide.c. The hwgroup locking method which was used
112  *                        in the previous version was removed.
113  *                       Use of new general features which are provided by
114  *                        ide.c for use with atapi devices.
115  *                        (Programming done by Mark Lord)
116  *                       Few potential bug fixes (Again, suggested by Mark)
117  *                       Single character device data transfers are now
118  *                        not limited in size, as they were before.
119  *                       We are asking the tape about its recommended
120  *                        transfer unit and send a larger data transfer
121  *                        as several transfers of the above size.
122  *                        For best results, use an integral number of this
123  *                        basic unit (which is shown during driver
124  *                        initialization). I will soon add an ioctl to get
125  *                        this important parameter.
126  *                       Our data transfer buffer is allocated on startup,
127  *                        rather than before each data transfer. This should
128  *                        ensure that we will indeed have a data buffer.
129  * Ver 1.1   Dec 14 95   Fixed random problems which occurred when the tape
130  *                        shared an interface with another device.
131  *                        (poll_for_dsc was a complete mess).
132  *                       Removed some old (non-active) code which had
133  *                        to do with supporting buffer cache originated
134  *                        requests.
135  *                       The block device interface can now be opened, so
136  *                        that general ide driver features like the unmask
137  *                        interrupts flag can be selected with an ioctl.
138  *                        This is the only use of the block device interface.
139  *                       New fast pipelined operation mode (currently only on
140  *                        writes). When using the pipelined mode, the
141  *                        throughput can potentially reach the maximum
142  *                        tape supported throughput, regardless of the
143  *                        user backup program. On my tape drive, it sometimes
144  *                        boosted performance by a factor of 2. Pipelined
145  *                        mode is enabled by default, but since it has a few
146  *                        downfalls as well, you may want to disable it.
147  *                        A short explanation of the pipelined operation mode
148  *                        is available below.
149  * Ver 1.2   Jan  1 96   Eliminated pipelined mode race condition.
150  *                       Added pipeline read mode. As a result, restores
151  *                        are now as fast as backups.
152  *                       Optimized shared interface behavior. The new behavior
153  *                        typically results in better IDE bus efficiency and
154  *                        higher tape throughput.
155  *                       Pre-calculation of the expected read/write request
156  *                        service time, based on the tape's parameters. In
157  *                        the pipelined operation mode, this allows us to
158  *                        adjust our polling frequency to a much lower value,
159  *                        and thus to dramatically reduce our load on Linux,
160  *                        without any decrease in performance.
161  *                       Implemented additional mtio.h operations.
162  *                       The recommended user block size is returned by
163  *                        the MTIOCGET ioctl.
164  *                       Additional minor changes.
165  * Ver 1.3   Feb  9 96   Fixed pipelined read mode bug which prevented the
166  *                        use of some block sizes during a restore procedure.
167  *                       The character device interface will now present a
168  *                        continuous view of the media - any mix of block sizes
169  *                        during a backup/restore procedure is supported. The
170  *                        driver will buffer the requests internally and
171  *                        convert them to the tape's recommended transfer
172  *                        unit, making performance almost independent of the
173  *                        chosen user block size.
174  *                       Some improvements in error recovery.
175  *                       By cooperating with ide-dma.c, bus mastering DMA can
176  *                        now sometimes be used with IDE tape drives as well.
177  *                        Bus mastering DMA has the potential to dramatically
178  *                        reduce the CPU's overhead when accessing the device,
179  *                        and can be enabled by using hdparm -d1 on the tape's
180  *                        block device interface. For more info, read the
181  *                        comments in ide-dma.c.
182  * Ver 1.4   Mar 13 96   Fixed serialize support.
183  * Ver 1.5   Apr 12 96   Fixed shared interface operation, broken in 1.3.85.
184  *                       Fixed pipelined read mode inefficiency.
185  *                       Fixed nasty null dereferencing bug.
186  * Ver 1.6   Aug 16 96   Fixed FPU usage in the driver.
187  *                       Fixed end of media bug.
188  * Ver 1.7   Sep 10 96   Minor changes for the CONNER CTT8000-A model.
189  * Ver 1.8   Sep 26 96   Attempt to find a better balance between good
190  *                        interactive response and high system throughput.
191  * Ver 1.9   Nov  5 96   Automatically cross encountered filemarks rather
192  *                        than requiring an explicit FSF command.
193  *                       Abort pending requests at end of media.
194  *                       MTTELL was sometimes returning incorrect results.
195  *                       Return the real block size in the MTIOCGET ioctl.
196  *                       Some error recovery bug fixes.
197  * Ver 1.10  Nov  5 96   Major reorganization.
198  *                       Reduced CPU overhead a bit by eliminating internal
199  *                        bounce buffers.
200  *                       Added module support.
201  *                       Added multiple tape drives support.
202  *                       Added partition support.
203  *                       Rewrote DSC handling.
204  *                       Some portability fixes.
205  *                       Removed ide-tape.h.
206  *                       Additional minor changes.
207  * Ver 1.11  Dec  2 96   Bug fix in previous DSC timeout handling.
208  *                       Use ide_stall_queue() for DSC overlap.
209  *                       Use the maximum speed rather than the current speed
210  *                        to compute the request service time.
211  * Ver 1.12  Dec  7 97   Fix random memory overwriting and/or last block data
212  *                        corruption, which could occur if the total number
213  *                        of bytes written to the tape was not an integral
214  *                        number of tape blocks.
215  *                       Add support for INTERRUPT DRQ devices.
216  * Ver 1.13  Jan  2 98   Add "speed == 0" work-around for HP COLORADO 5GB
217  * Ver 1.14  Dec 30 98   Partial fixes for the Sony/AIWA tape drives.
218  *                       Replace cli()/sti() with hwgroup spinlocks.
219  * Ver 1.15  Mar 25 99   Fix SMP race condition by replacing hwgroup
220  *                        spinlock with private per-tape spinlock.
221  * Ver 1.16  Sep  1 99   Add OnStream tape support.
222  *                       Abort read pipeline on EOD.
223  *                       Wait for the tape to become ready in case it returns
224  *                        "in the process of becoming ready" on open().
225  *                       Fix zero padding of the last written block in
226  *                        case the tape block size is larger than PAGE_SIZE.
227  *                       Decrease the default disconnection time to tn.
228  * Ver 1.16e Oct  3 99   Minor fixes.
229  * Ver 1.16e1 Oct 13 99  Patches by Arnold Niessen,
230  *                          niessen@iae.nl / arnold.niessen@philips.com
231  *                   GO-1)  Undefined code in idetape_read_position
232  *                              according to Gadi's email
233  *                   AJN-1) Minor fix asc == 11 should be asc == 0x11
234  *                               in idetape_issue_packet_command (did effect
235  *                               debugging output only)
236  *                   AJN-2) Added more debugging output, and
237  *                              added ide-tape: where missing. I would also
238  *                              like to add tape->name where possible
239  *                   AJN-3) Added different debug_level's 
240  *                              via /proc/ide/hdc/settings
241  *                              "debug_level" determines amount of debugging output;
242  *                              can be changed using /proc/ide/hdx/settings
243  *                              0 : almost no debugging output
244  *                              1 : 0+output errors only
245  *                              2 : 1+output all sensekey/asc
246  *                              3 : 2+follow all chrdev related procedures
247  *                              4 : 3+follow all procedures
248  *                              5 : 4+include pc_stack rq_stack info
249  *                              6 : 5+USE_COUNT updates
250  *                   AJN-4) Fixed timeout for retension in idetape_queue_pc_tail
251  *                              from 5 to 10 minutes
252  *                   AJN-5) Changed maximum number of blocks to skip when
253  *                              reading tapes with multiple consecutive write
254  *                              errors from 100 to 1000 in idetape_get_logical_blk
255  *                   Proposed changes to code:
256  *                   1) output "logical_blk_num" via /proc
257  *                   2) output "current_operation" via /proc
258  *                   3) Either solve or document the fact that `mt rewind' is
259  *                      required after reading from /dev/nhtx to be
260  *                      able to rmmod the idetape module;
261  *                      Also, sometimes an application finishes but the
262  *                      device remains `busy' for some time. Same cause ?
263  *                   Proposed changes to release-notes:
264  *                   4) write a simple `quickstart' section in the
265  *                      release notes; I volunteer if you don't want to
266  *                   5) include a pointer to video4linux in the doc
267  *                      to stimulate video applications
268  *                   6) release notes lines 331 and 362: explain what happens
269  *                      if the application data rate is higher than 1100 KB/s; 
270  *                      similar approach to lower-than-500 kB/s ?
271  *                   7) 6.6 Comparison; wouldn't it be better to allow different 
272  *                      strategies for read and write ?
273  *                      Wouldn't it be better to control the tape buffer
274  *                      contents instead of the bandwidth ?
275  *                   8) line 536: replace will by would (if I understand
276  *                      this section correctly, a hypothetical and unwanted situation
277  *                       is being described)
278  * Ver 1.16f Dec 15 99   Change place of the secondary OnStream header frames.
279  * Ver 1.17  Nov 2000 / Jan 2001  Marcel Mol, marcel@mesa.nl
280  *                      - Add idetape_onstream_mode_sense_tape_parameter_page
281  *                        function to get tape capacity in frames: tape->capacity.
282  *                      - Add support for DI-50 drives( or any DI- drive).
283  *                      - 'workaround' for read error/blank block around block 3000.
284  *                      - Implement Early warning for end of media for Onstream.
285  *                      - Cosmetic code changes for readability.
286  *                      - Idetape_position_tape should not use SKIP bit during
287  *                        Onstream read recovery.
288  *                      - Add capacity, logical_blk_num and first/last_frame_position
289  *                        to /proc/ide/hd?/settings.
290  *                      - Module use count was gone in the Linux 2.4 driver.
291  * Ver 1.17a Apr 2001 Willem Riede osst@riede.org
292  *                      - Get drive's actual block size from mode sense block descriptor
293  *                      - Limit size of pipeline
294  * Ver 1.17b Oct 2002   Alan Stern <stern@rowland.harvard.edu>
295  *                      Changed IDETAPE_MIN_PIPELINE_STAGES to 1 and actually used
296  *                       it in the code!
297  *                      Actually removed aborted stages in idetape_abort_pipeline
298  *                       instead of just changing the command code.
299  *                      Made the transfer byte count for Request Sense equal to the
300  *                       actual length of the data transfer.
301  *                      Changed handling of partial data transfers: they do not
302  *                       cause DMA errors.
303  *                      Moved initiation of DMA transfers to the correct place.
304  *                      Removed reference to unallocated memory.
305  *                      Made __idetape_discard_read_pipeline return the number of
306  *                       sectors skipped, not the number of stages.
307  *                      Replaced errant kfree() calls with __idetape_kfree_stage().
308  *                      Fixed off-by-one error in testing the pipeline length.
309  *                      Fixed handling of filemarks in the read pipeline.
310  *                      Small code optimization for MTBSF and MTBSFM ioctls.
311  *                      Don't try to unlock the door during device close if is
312  *                       already unlocked!
313  *                      Cosmetic fixes to miscellaneous debugging output messages.
314  *                      Set the minimum /proc/ide/hd?/settings values for "pipeline",
315  *                       "pipeline_min", and "pipeline_max" to 1.
316  *
317  * Here are some words from the first releases of hd.c, which are quoted
318  * in ide.c and apply here as well:
319  *
320  * | Special care is recommended.  Have Fun!
321  *
322  */
323
324 /*
325  * An overview of the pipelined operation mode.
326  *
327  * In the pipelined write mode, we will usually just add requests to our
328  * pipeline and return immediately, before we even start to service them. The
329  * user program will then have enough time to prepare the next request while
330  * we are still busy servicing previous requests. In the pipelined read mode,
331  * the situation is similar - we add read-ahead requests into the pipeline,
332  * before the user even requested them.
333  *
334  * The pipeline can be viewed as a "safety net" which will be activated when
335  * the system load is high and prevents the user backup program from keeping up
336  * with the current tape speed. At this point, the pipeline will get
337  * shorter and shorter but the tape will still be streaming at the same speed.
338  * Assuming we have enough pipeline stages, the system load will hopefully
339  * decrease before the pipeline is completely empty, and the backup program
340  * will be able to "catch up" and refill the pipeline again.
341  * 
342  * When using the pipelined mode, it would be best to disable any type of
343  * buffering done by the user program, as ide-tape already provides all the
344  * benefits in the kernel, where it can be done in a more efficient way.
345  * As we will usually not block the user program on a request, the most
346  * efficient user code will then be a simple read-write-read-... cycle.
347  * Any additional logic will usually just slow down the backup process.
348  *
349  * Using the pipelined mode, I get a constant over 400 KBps throughput,
350  * which seems to be the maximum throughput supported by my tape.
351  *
352  * However, there are some downfalls:
353  *
354  *      1.      We use memory (for data buffers) in proportional to the number
355  *              of pipeline stages (each stage is about 26 KB with my tape).
356  *      2.      In the pipelined write mode, we cheat and postpone error codes
357  *              to the user task. In read mode, the actual tape position
358  *              will be a bit further than the last requested block.
359  *
360  * Concerning (1):
361  *
362  *      1.      We allocate stages dynamically only when we need them. When
363  *              we don't need them, we don't consume additional memory. In
364  *              case we can't allocate stages, we just manage without them
365  *              (at the expense of decreased throughput) so when Linux is
366  *              tight in memory, we will not pose additional difficulties.
367  *
368  *      2.      The maximum number of stages (which is, in fact, the maximum
369  *              amount of memory) which we allocate is limited by the compile
370  *              time parameter IDETAPE_MAX_PIPELINE_STAGES.
371  *
372  *      3.      The maximum number of stages is a controlled parameter - We
373  *              don't start from the user defined maximum number of stages
374  *              but from the lower IDETAPE_MIN_PIPELINE_STAGES (again, we
375  *              will not even allocate this amount of stages if the user
376  *              program can't handle the speed). We then implement a feedback
377  *              loop which checks if the pipeline is empty, and if it is, we
378  *              increase the maximum number of stages as necessary until we
379  *              reach the optimum value which just manages to keep the tape
380  *              busy with minimum allocated memory or until we reach
381  *              IDETAPE_MAX_PIPELINE_STAGES.
382  *
383  * Concerning (2):
384  *
385  *      In pipelined write mode, ide-tape can not return accurate error codes
386  *      to the user program since we usually just add the request to the
387  *      pipeline without waiting for it to be serviced. In case an error
388  *      occurs, I will report it on the next user request.
389  *
390  *      In the pipelined read mode, subsequent read requests or forward
391  *      filemark spacing will perform correctly, as we preserve all blocks
392  *      and filemarks which we encountered during our excess read-ahead.
393  * 
394  *      For accurate tape positioning and error reporting, disabling
395  *      pipelined mode might be the best option.
396  *
397  * You can enable/disable/tune the pipelined operation mode by adjusting
398  * the compile time parameters below.
399  */
400
401 /*
402  *      Possible improvements.
403  *
404  *      1.      Support for the ATAPI overlap protocol.
405  *
406  *              In order to maximize bus throughput, we currently use the DSC
407  *              overlap method which enables ide.c to service requests from the
408  *              other device while the tape is busy executing a command. The
409  *              DSC overlap method involves polling the tape's status register
410  *              for the DSC bit, and servicing the other device while the tape
411  *              isn't ready.
412  *
413  *              In the current QIC development standard (December 1995),
414  *              it is recommended that new tape drives will *in addition* 
415  *              implement the ATAPI overlap protocol, which is used for the
416  *              same purpose - efficient use of the IDE bus, but is interrupt
417  *              driven and thus has much less CPU overhead.
418  *
419  *              ATAPI overlap is likely to be supported in most new ATAPI
420  *              devices, including new ATAPI cdroms, and thus provides us
421  *              a method by which we can achieve higher throughput when
422  *              sharing a (fast) ATA-2 disk with any (slow) new ATAPI device.
423  */
424
425 #define IDETAPE_VERSION "1.19"
426
427 #include <linux/config.h>
428 #include <linux/module.h>
429 #include <linux/types.h>
430 #include <linux/string.h>
431 #include <linux/kernel.h>
432 #include <linux/delay.h>
433 #include <linux/timer.h>
434 #include <linux/mm.h>
435 #include <linux/interrupt.h>
436 #include <linux/major.h>
437 #include <linux/devfs_fs_kernel.h>
438 #include <linux/errno.h>
439 #include <linux/genhd.h>
440 #include <linux/slab.h>
441 #include <linux/pci.h>
442 #include <linux/ide.h>
443 #include <linux/smp_lock.h>
444 #include <linux/completion.h>
445
446 #include <asm/byteorder.h>
447 #include <asm/irq.h>
448 #include <asm/uaccess.h>
449 #include <asm/io.h>
450 #include <asm/unaligned.h>
451 #include <asm/bitops.h>
452
453 /*
454  * partition
455  */
456 typedef struct os_partition_s {
457         __u8    partition_num;
458         __u8    par_desc_ver;
459         __u16   wrt_pass_cntr;
460         __u32   first_frame_addr;
461         __u32   last_frame_addr;
462         __u32   eod_frame_addr;
463 } os_partition_t;
464
465 /*
466  * DAT entry
467  */
468 typedef struct os_dat_entry_s {
469         __u32   blk_sz;
470         __u16   blk_cnt;
471         __u8    flags;
472         __u8    reserved;
473 } os_dat_entry_t;
474
475 /*
476  * DAT
477  */
478 #define OS_DAT_FLAGS_DATA       (0xc)
479 #define OS_DAT_FLAGS_MARK       (0x1)
480
481 typedef struct os_dat_s {
482         __u8            dat_sz;
483         __u8            reserved1;
484         __u8            entry_cnt;
485         __u8            reserved3;
486         os_dat_entry_t  dat_list[16];
487 } os_dat_t;
488
489 #include <linux/mtio.h>
490
491 /**************************** Tunable parameters *****************************/
492
493
494 /*
495  *      Pipelined mode parameters.
496  *
497  *      We try to use the minimum number of stages which is enough to
498  *      keep the tape constantly streaming. To accomplish that, we implement
499  *      a feedback loop around the maximum number of stages:
500  *
501  *      We start from MIN maximum stages (we will not even use MIN stages
502  *      if we don't need them), increment it by RATE*(MAX-MIN)
503  *      whenever we sense that the pipeline is empty, until we reach
504  *      the optimum value or until we reach MAX.
505  *
506  *      Setting the following parameter to 0 is illegal: the pipelined mode
507  *      cannot be disabled (calculate_speeds() divides by tape->max_stages.)
508  */
509 #define IDETAPE_MIN_PIPELINE_STAGES       1
510 #define IDETAPE_MAX_PIPELINE_STAGES     400
511 #define IDETAPE_INCREASE_STAGES_RATE     20
512
513 /*
514  *      The following are used to debug the driver:
515  *
516  *      Setting IDETAPE_DEBUG_INFO to 1 will report device capabilities.
517  *      Setting IDETAPE_DEBUG_LOG to 1 will log driver flow control.
518  *      Setting IDETAPE_DEBUG_BUGS to 1 will enable self-sanity checks in
519  *      some places.
520  *
521  *      Setting them to 0 will restore normal operation mode:
522  *
523  *              1.      Disable logging normal successful operations.
524  *              2.      Disable self-sanity checks.
525  *              3.      Errors will still be logged, of course.
526  *
527  *      All the #if DEBUG code will be removed some day, when the driver
528  *      is verified to be stable enough. This will make it much more
529  *      esthetic.
530  */
531 #define IDETAPE_DEBUG_INFO              0
532 #define IDETAPE_DEBUG_LOG               0
533 #define IDETAPE_DEBUG_LOG_VERBOSE       0
534 #define IDETAPE_DEBUG_BUGS              1
535
536 /*
537  *      After each failed packet command we issue a request sense command
538  *      and retry the packet command IDETAPE_MAX_PC_RETRIES times.
539  *
540  *      Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
541  */
542 #define IDETAPE_MAX_PC_RETRIES          3
543
544 /*
545  *      With each packet command, we allocate a buffer of
546  *      IDETAPE_PC_BUFFER_SIZE bytes. This is used for several packet
547  *      commands (Not for READ/WRITE commands).
548  */
549 #define IDETAPE_PC_BUFFER_SIZE          256
550
551 /*
552  *      In various places in the driver, we need to allocate storage
553  *      for packet commands and requests, which will remain valid while
554  *      we leave the driver to wait for an interrupt or a timeout event.
555  */
556 #define IDETAPE_PC_STACK                (10 + IDETAPE_MAX_PC_RETRIES)
557
558 /*
559  * Some drives (for example, Seagate STT3401A Travan) require a very long
560  * timeout, because they don't return an interrupt or clear their busy bit
561  * until after the command completes (even retension commands).
562  */
563 #define IDETAPE_WAIT_CMD                (900*HZ)
564
565 /*
566  *      The following parameter is used to select the point in the internal
567  *      tape fifo in which we will start to refill the buffer. Decreasing
568  *      the following parameter will improve the system's latency and
569  *      interactive response, while using a high value might improve sytem
570  *      throughput.
571  */
572 #define IDETAPE_FIFO_THRESHOLD          2
573
574 /*
575  *      DSC polling parameters.
576  *
577  *      Polling for DSC (a single bit in the status register) is a very
578  *      important function in ide-tape. There are two cases in which we
579  *      poll for DSC:
580  *
581  *      1.      Before a read/write packet command, to ensure that we
582  *              can transfer data from/to the tape's data buffers, without
583  *              causing an actual media access. In case the tape is not
584  *              ready yet, we take out our request from the device
585  *              request queue, so that ide.c will service requests from
586  *              the other device on the same interface meanwhile.
587  *
588  *      2.      After the successful initialization of a "media access
589  *              packet command", which is a command which can take a long
590  *              time to complete (it can be several seconds or even an hour).
591  *
592  *              Again, we postpone our request in the middle to free the bus
593  *              for the other device. The polling frequency here should be
594  *              lower than the read/write frequency since those media access
595  *              commands are slow. We start from a "fast" frequency -
596  *              IDETAPE_DSC_MA_FAST (one second), and if we don't receive DSC
597  *              after IDETAPE_DSC_MA_THRESHOLD (5 minutes), we switch it to a
598  *              lower frequency - IDETAPE_DSC_MA_SLOW (1 minute).
599  *
600  *      We also set a timeout for the timer, in case something goes wrong.
601  *      The timeout should be longer then the maximum execution time of a
602  *      tape operation.
603  */
604  
605 /*
606  *      DSC timings.
607  */
608 #define IDETAPE_DSC_RW_MIN              5*HZ/100        /* 50 msec */
609 #define IDETAPE_DSC_RW_MAX              40*HZ/100       /* 400 msec */
610 #define IDETAPE_DSC_RW_TIMEOUT          2*60*HZ         /* 2 minutes */
611 #define IDETAPE_DSC_MA_FAST             2*HZ            /* 2 seconds */
612 #define IDETAPE_DSC_MA_THRESHOLD        5*60*HZ         /* 5 minutes */
613 #define IDETAPE_DSC_MA_SLOW             30*HZ           /* 30 seconds */
614 #define IDETAPE_DSC_MA_TIMEOUT          2*60*60*HZ      /* 2 hours */
615
616 /*************************** End of tunable parameters ***********************/
617
618 /*
619  *      Debugging/Performance analysis
620  *
621  *      I/O trace support
622  */
623 #define USE_IOTRACE     0
624 #if USE_IOTRACE
625 #include <linux/io_trace.h>
626 #define IO_IDETAPE_FIFO 500
627 #endif
628
629 /*
630  *      Read/Write error simulation
631  */
632 #define SIMULATE_ERRORS                 0
633
634 /*
635  *      For general magnetic tape device compatibility.
636  */
637 typedef enum {
638         idetape_direction_none,
639         idetape_direction_read,
640         idetape_direction_write
641 } idetape_chrdev_direction_t;
642
643 struct idetape_bh {
644         unsigned short b_size;
645         atomic_t b_count;
646         struct idetape_bh *b_reqnext;
647         char *b_data;
648 };
649
650 /*
651  *      Our view of a packet command.
652  */
653 typedef struct idetape_packet_command_s {
654         u8 c[12];                               /* Actual packet bytes */
655         int retries;                            /* On each retry, we increment retries */
656         int error;                              /* Error code */
657         int request_transfer;                   /* Bytes to transfer */
658         int actually_transferred;               /* Bytes actually transferred */
659         int buffer_size;                        /* Size of our data buffer */
660         struct idetape_bh *bh;
661         char *b_data;
662         int b_count;
663         u8 *buffer;                             /* Data buffer */
664         u8 *current_position;                   /* Pointer into the above buffer */
665         ide_startstop_t (*callback) (ide_drive_t *);    /* Called when this packet command is completed */
666         u8 pc_buffer[IDETAPE_PC_BUFFER_SIZE];   /* Temporary buffer */
667         unsigned long flags;                    /* Status/Action bit flags: long for set_bit */
668 } idetape_pc_t;
669
670 /*
671  *      Packet command flag bits.
672  */
673 /* Set when an error is considered normal - We won't retry */
674 #define PC_ABORT                        0
675 /* 1 When polling for DSC on a media access command */
676 #define PC_WAIT_FOR_DSC                 1
677 /* 1 when we prefer to use DMA if possible */
678 #define PC_DMA_RECOMMENDED              2
679 /* 1 while DMA in progress */
680 #define PC_DMA_IN_PROGRESS              3
681 /* 1 when encountered problem during DMA */
682 #define PC_DMA_ERROR                    4
683 /* Data direction */
684 #define PC_WRITING                      5
685
686 /*
687  *      Capabilities and Mechanical Status Page
688  */
689 typedef struct {
690         unsigned        page_code       :6;     /* Page code - Should be 0x2a */
691         __u8            reserved0_6     :1;
692         __u8            ps              :1;     /* parameters saveable */
693         __u8            page_length;            /* Page Length - Should be 0x12 */
694         __u8            reserved2, reserved3;
695         unsigned        ro              :1;     /* Read Only Mode */
696         unsigned        reserved4_1234  :4;
697         unsigned        sprev           :1;     /* Supports SPACE in the reverse direction */
698         unsigned        reserved4_67    :2;
699         unsigned        reserved5_012   :3;
700         unsigned        efmt            :1;     /* Supports ERASE command initiated formatting */
701         unsigned        reserved5_4     :1;
702         unsigned        qfa             :1;     /* Supports the QFA two partition formats */
703         unsigned        reserved5_67    :2;
704         unsigned        lock            :1;     /* Supports locking the volume */
705         unsigned        locked          :1;     /* The volume is locked */
706         unsigned        prevent         :1;     /* The device defaults in the prevent state after power up */   
707         unsigned        eject           :1;     /* The device can eject the volume */
708         __u8            disconnect      :1;     /* The device can break request > ctl */        
709         __u8            reserved6_5     :1;
710         unsigned        ecc             :1;     /* Supports error correction */
711         unsigned        cmprs           :1;     /* Supports data compression */
712         unsigned        reserved7_0     :1;
713         unsigned        blk512          :1;     /* Supports 512 bytes block size */
714         unsigned        blk1024         :1;     /* Supports 1024 bytes block size */
715         unsigned        reserved7_3_6   :4;
716         unsigned        blk32768        :1;     /* slowb - the device restricts the byte count for PIO */
717                                                 /* transfers for slow buffer memory ??? */
718                                                 /* Also 32768 block size in some cases */
719         __u16           max_speed;              /* Maximum speed supported in KBps */
720         __u8            reserved10, reserved11;
721         __u16           ctl;                    /* Continuous Transfer Limit in blocks */
722         __u16           speed;                  /* Current Speed, in KBps */
723         __u16           buffer_size;            /* Buffer Size, in 512 bytes */
724         __u8            reserved18, reserved19;
725 } idetape_capabilities_page_t;
726
727 /*
728  *      Block Size Page
729  */
730 typedef struct {
731         unsigned        page_code       :6;     /* Page code - Should be 0x30 */
732         unsigned        reserved1_6     :1;
733         unsigned        ps              :1;
734         __u8            page_length;            /* Page Length - Should be 2 */
735         __u8            reserved2;
736         unsigned        play32          :1;
737         unsigned        play32_5        :1;
738         unsigned        reserved2_23    :2;
739         unsigned        record32        :1;
740         unsigned        record32_5      :1;
741         unsigned        reserved2_6     :1;
742         unsigned        one             :1;
743 } idetape_block_size_page_t;
744
745 /*
746  *      A pipeline stage.
747  */
748 typedef struct idetape_stage_s {
749         struct request rq;                      /* The corresponding request */
750         struct idetape_bh *bh;                  /* The data buffers */
751         struct idetape_stage_s *next;           /* Pointer to the next stage */
752 } idetape_stage_t;
753
754 /*
755  *      REQUEST SENSE packet command result - Data Format.
756  */
757 typedef struct {
758         unsigned        error_code      :7;     /* Current of deferred errors */
759         unsigned        valid           :1;     /* The information field conforms to QIC-157C */
760         __u8            reserved1       :8;     /* Segment Number - Reserved */
761         unsigned        sense_key       :4;     /* Sense Key */
762         unsigned        reserved2_4     :1;     /* Reserved */
763         unsigned        ili             :1;     /* Incorrect Length Indicator */
764         unsigned        eom             :1;     /* End Of Medium */
765         unsigned        filemark        :1;     /* Filemark */
766         __u32           information __attribute__ ((packed));
767         __u8            asl;                    /* Additional sense length (n-7) */
768         __u32           command_specific;       /* Additional command specific information */
769         __u8            asc;                    /* Additional Sense Code */
770         __u8            ascq;                   /* Additional Sense Code Qualifier */
771         __u8            replaceable_unit_code;  /* Field Replaceable Unit Code */
772         unsigned        sk_specific1    :7;     /* Sense Key Specific */
773         unsigned        sksv            :1;     /* Sense Key Specific information is valid */
774         __u8            sk_specific2;           /* Sense Key Specific */
775         __u8            sk_specific3;           /* Sense Key Specific */
776         __u8            pad[2];                 /* Padding to 20 bytes */
777 } idetape_request_sense_result_t;
778
779
780 /*
781  *      Most of our global data which we need to save even as we leave the
782  *      driver due to an interrupt or a timer event is stored in a variable
783  *      of type idetape_tape_t, defined below.
784  */
785 typedef struct {
786         ide_drive_t *drive;
787         /*
788          *      Since a typical character device operation requires more
789          *      than one packet command, we provide here enough memory
790          *      for the maximum of interconnected packet commands.
791          *      The packet commands are stored in the circular array pc_stack.
792          *      pc_stack_index points to the last used entry, and warps around
793          *      to the start when we get to the last array entry.
794          *
795          *      pc points to the current processed packet command.
796          *
797          *      failed_pc points to the last failed packet command, or contains
798          *      NULL if we do not need to retry any packet command. This is
799          *      required since an additional packet command is needed before the
800          *      retry, to get detailed information on what went wrong.
801          */
802         /* Current packet command */
803         idetape_pc_t *pc;
804         /* Last failed packet command */
805         idetape_pc_t *failed_pc;
806         /* Packet command stack */
807         idetape_pc_t pc_stack[IDETAPE_PC_STACK];
808         /* Next free packet command storage space */
809         int pc_stack_index;
810         struct request rq_stack[IDETAPE_PC_STACK];
811         /* We implement a circular array */
812         int rq_stack_index;
813
814         /*
815          *      DSC polling variables.
816          *
817          *      While polling for DSC we use postponed_rq to postpone the
818          *      current request so that ide.c will be able to service
819          *      pending requests on the other device. Note that at most
820          *      we will have only one DSC (usually data transfer) request
821          *      in the device request queue. Additional requests can be
822          *      queued in our internal pipeline, but they will be visible
823          *      to ide.c only one at a time.
824          */
825         struct request *postponed_rq;
826         /* The time in which we started polling for DSC */
827         unsigned long dsc_polling_start;
828         /* Timer used to poll for dsc */
829         struct timer_list dsc_timer;
830         /* Read/Write dsc polling frequency */
831         unsigned long best_dsc_rw_frequency;
832         /* The current polling frequency */
833         unsigned long dsc_polling_frequency;
834         /* Maximum waiting time */
835         unsigned long dsc_timeout;
836
837         /*
838          *      Read position information
839          */
840         u8 partition;
841         /* Current block */
842         unsigned int first_frame_position;
843         unsigned int last_frame_position;
844         unsigned int blocks_in_buffer;
845
846         /*
847          *      Last error information
848          */
849         u8 sense_key, asc, ascq;
850
851         /*
852          *      Character device operation
853          */
854         unsigned int minor;
855         /* device name */
856         char name[4];
857         /* Current character device data transfer direction */
858         idetape_chrdev_direction_t chrdev_direction;
859
860         /*
861          *      Device information
862          */
863         /* Usually 512 or 1024 bytes */
864         unsigned short tape_block_size;
865         int user_bs_factor;
866         /* Copy of the tape's Capabilities and Mechanical Page */
867         idetape_capabilities_page_t capabilities;
868
869         /*
870          *      Active data transfer request parameters.
871          *
872          *      At most, there is only one ide-tape originated data transfer
873          *      request in the device request queue. This allows ide.c to
874          *      easily service requests from the other device when we
875          *      postpone our active request. In the pipelined operation
876          *      mode, we use our internal pipeline structure to hold
877          *      more data requests.
878          *
879          *      The data buffer size is chosen based on the tape's
880          *      recommendation.
881          */
882         /* Pointer to the request which is waiting in the device request queue */
883         struct request *active_data_request;
884         /* Data buffer size (chosen based on the tape's recommendation */
885         int stage_size;
886         idetape_stage_t *merge_stage;
887         int merge_stage_size;
888         struct idetape_bh *bh;
889         char *b_data;
890         int b_count;
891         
892         /*
893          *      Pipeline parameters.
894          *
895          *      To accomplish non-pipelined mode, we simply set the following
896          *      variables to zero (or NULL, where appropriate).
897          */
898         /* Number of currently used stages */
899         int nr_stages;
900         /* Number of pending stages */
901         int nr_pending_stages;
902         /* We will not allocate more than this number of stages */
903         int max_stages, min_pipeline, max_pipeline;
904         /* The first stage which will be removed from the pipeline */
905         idetape_stage_t *first_stage;
906         /* The currently active stage */
907         idetape_stage_t *active_stage;
908         /* Will be serviced after the currently active request */
909         idetape_stage_t *next_stage;
910         /* New requests will be added to the pipeline here */
911         idetape_stage_t *last_stage;
912         /* Optional free stage which we can use */
913         idetape_stage_t *cache_stage;
914         int pages_per_stage;
915         /* Wasted space in each stage */
916         int excess_bh_size;
917
918         /* Status/Action flags: long for set_bit */
919         unsigned long flags;
920         /* protects the ide-tape queue */
921         spinlock_t spinlock;
922
923         /*
924          * Measures average tape speed
925          */
926         unsigned long avg_time;
927         int avg_size;
928         int avg_speed;
929
930         /* last sense information */
931         idetape_request_sense_result_t sense;
932
933         char vendor_id[10];
934         char product_id[18];
935         char firmware_revision[6];
936         int firmware_revision_num;
937
938         /* the door is currently locked */
939         int door_locked;
940         /* the tape hardware is write protected */
941         char drv_write_prot;
942         /* the tape is write protected (hardware or opened as read-only) */
943         char write_prot;
944
945         /*
946          * Limit the number of times a request can
947          * be postponed, to avoid an infinite postpone
948          * deadlock.
949          */
950         /* request postpone count limit */
951         int postpone_cnt;
952
953         /*
954          * Measures number of frames:
955          *
956          * 1. written/read to/from the driver pipeline (pipeline_head).
957          * 2. written/read to/from the tape buffers (idetape_bh).
958          * 3. written/read by the tape to/from the media (tape_head).
959          */
960         int pipeline_head;
961         int buffer_head;
962         int tape_head;
963         int last_tape_head;
964
965         /*
966          * Speed control at the tape buffers input/output
967          */
968         unsigned long insert_time;
969         int insert_size;
970         int insert_speed;
971         int max_insert_speed;
972         int measure_insert_time;
973
974         /*
975          * Measure tape still time, in milliseconds
976          */
977         unsigned long tape_still_time_begin;
978         int tape_still_time;
979
980         /*
981          * Speed regulation negative feedback loop
982          */
983         int speed_control;
984         int pipeline_head_speed;
985         int controlled_pipeline_head_speed;
986         int uncontrolled_pipeline_head_speed;
987         int controlled_last_pipeline_head;
988         int uncontrolled_last_pipeline_head;
989         unsigned long uncontrolled_pipeline_head_time;
990         unsigned long controlled_pipeline_head_time;
991         int controlled_previous_pipeline_head;
992         int uncontrolled_previous_pipeline_head;
993         unsigned long controlled_previous_head_time;
994         unsigned long uncontrolled_previous_head_time;
995         int restart_speed_control_req;
996
997         /*
998          * Debug_level determines amount of debugging output;
999          * can be changed using /proc/ide/hdx/settings
1000          * 0 : almost no debugging output
1001          * 1 : 0+output errors only
1002          * 2 : 1+output all sensekey/asc
1003          * 3 : 2+follow all chrdev related procedures
1004          * 4 : 3+follow all procedures
1005          * 5 : 4+include pc_stack rq_stack info
1006          * 6 : 5+USE_COUNT updates
1007          */
1008          int debug_level; 
1009 } idetape_tape_t;
1010
1011 /*
1012  *      Tape door status
1013  */
1014 #define DOOR_UNLOCKED                   0
1015 #define DOOR_LOCKED                     1
1016 #define DOOR_EXPLICITLY_LOCKED          2
1017
1018 /*
1019  *      Tape flag bits values.
1020  */
1021 #define IDETAPE_IGNORE_DSC              0
1022 #define IDETAPE_ADDRESS_VALID           1       /* 0 When the tape position is unknown */
1023 #define IDETAPE_BUSY                    2       /* Device already opened */
1024 #define IDETAPE_PIPELINE_ERROR          3       /* Error detected in a pipeline stage */
1025 #define IDETAPE_DETECT_BS               4       /* Attempt to auto-detect the current user block size */
1026 #define IDETAPE_FILEMARK                5       /* Currently on a filemark */
1027 #define IDETAPE_DRQ_INTERRUPT           6       /* DRQ interrupt device */
1028 #define IDETAPE_READ_ERROR              7
1029 #define IDETAPE_PIPELINE_ACTIVE         8       /* pipeline active */
1030 /* 0 = no tape is loaded, so we don't rewind after ejecting */
1031 #define IDETAPE_MEDIUM_PRESENT          9
1032
1033 /*
1034  *      Supported ATAPI tape drives packet commands
1035  */
1036 #define IDETAPE_TEST_UNIT_READY_CMD     0x00
1037 #define IDETAPE_REWIND_CMD              0x01
1038 #define IDETAPE_REQUEST_SENSE_CMD       0x03
1039 #define IDETAPE_READ_CMD                0x08
1040 #define IDETAPE_WRITE_CMD               0x0a
1041 #define IDETAPE_WRITE_FILEMARK_CMD      0x10
1042 #define IDETAPE_SPACE_CMD               0x11
1043 #define IDETAPE_INQUIRY_CMD             0x12
1044 #define IDETAPE_ERASE_CMD               0x19
1045 #define IDETAPE_MODE_SENSE_CMD          0x1a
1046 #define IDETAPE_MODE_SELECT_CMD         0x15
1047 #define IDETAPE_LOAD_UNLOAD_CMD         0x1b
1048 #define IDETAPE_PREVENT_CMD             0x1e
1049 #define IDETAPE_LOCATE_CMD              0x2b
1050 #define IDETAPE_READ_POSITION_CMD       0x34
1051 #define IDETAPE_READ_BUFFER_CMD         0x3c
1052 #define IDETAPE_SET_SPEED_CMD           0xbb
1053
1054 /*
1055  *      Some defines for the READ BUFFER command
1056  */
1057 #define IDETAPE_RETRIEVE_FAULTY_BLOCK   6
1058
1059 /*
1060  *      Some defines for the SPACE command
1061  */
1062 #define IDETAPE_SPACE_OVER_FILEMARK     1
1063 #define IDETAPE_SPACE_TO_EOD            3
1064
1065 /*
1066  *      Some defines for the LOAD UNLOAD command
1067  */
1068 #define IDETAPE_LU_LOAD_MASK            1
1069 #define IDETAPE_LU_RETENSION_MASK       2
1070 #define IDETAPE_LU_EOT_MASK             4
1071
1072 /*
1073  *      Special requests for our block device strategy routine.
1074  *
1075  *      In order to service a character device command, we add special
1076  *      requests to the tail of our block device request queue and wait
1077  *      for their completion.
1078  */
1079
1080 enum {
1081         REQ_IDETAPE_PC1         = (1 << 0), /* packet command (first stage) */
1082         REQ_IDETAPE_PC2         = (1 << 1), /* packet command (second stage) */
1083         REQ_IDETAPE_READ        = (1 << 2),
1084         REQ_IDETAPE_WRITE       = (1 << 3),
1085         REQ_IDETAPE_READ_BUFFER = (1 << 4),
1086 };
1087
1088 /*
1089  *      Error codes which are returned in rq->errors to the higher part
1090  *      of the driver.
1091  */
1092 #define IDETAPE_ERROR_GENERAL           101
1093 #define IDETAPE_ERROR_FILEMARK          102
1094 #define IDETAPE_ERROR_EOD               103
1095
1096 /*
1097  *      idetape_chrdev_t provides the link between out character device
1098  *      interface and our block device interface and the corresponding
1099  *      ide_drive_t structure.
1100  */
1101 typedef struct {
1102         ide_drive_t *drive;
1103 } idetape_chrdev_t;
1104
1105 /*
1106  *      The following is used to format the general configuration word of
1107  *      the ATAPI IDENTIFY DEVICE command.
1108  */
1109 struct idetape_id_gcw { 
1110         unsigned packet_size            :2;     /* Packet Size */
1111         unsigned reserved234            :3;     /* Reserved */
1112         unsigned drq_type               :2;     /* Command packet DRQ type */
1113         unsigned removable              :1;     /* Removable media */
1114         unsigned device_type            :5;     /* Device type */
1115         unsigned reserved13             :1;     /* Reserved */
1116         unsigned protocol               :2;     /* Protocol type */
1117 };
1118
1119 /*
1120  *      INQUIRY packet command - Data Format (From Table 6-8 of QIC-157C)
1121  */
1122 typedef struct {
1123         unsigned        device_type     :5;     /* Peripheral Device Type */
1124         unsigned        reserved0_765   :3;     /* Peripheral Qualifier - Reserved */
1125         unsigned        reserved1_6t0   :7;     /* Reserved */
1126         unsigned        rmb             :1;     /* Removable Medium Bit */
1127         unsigned        ansi_version    :3;     /* ANSI Version */
1128         unsigned        ecma_version    :3;     /* ECMA Version */
1129         unsigned        iso_version     :2;     /* ISO Version */
1130         unsigned        response_format :4;     /* Response Data Format */
1131         unsigned        reserved3_45    :2;     /* Reserved */
1132         unsigned        reserved3_6     :1;     /* TrmIOP - Reserved */
1133         unsigned        reserved3_7     :1;     /* AENC - Reserved */
1134         __u8            additional_length;      /* Additional Length (total_length-4) */
1135         __u8            rsv5, rsv6, rsv7;       /* Reserved */
1136         __u8            vendor_id[8];           /* Vendor Identification */
1137         __u8            product_id[16];         /* Product Identification */
1138         __u8            revision_level[4];      /* Revision Level */
1139         __u8            vendor_specific[20];    /* Vendor Specific - Optional */
1140         __u8            reserved56t95[40];      /* Reserved - Optional */
1141                                                 /* Additional information may be returned */
1142 } idetape_inquiry_result_t;
1143
1144 /*
1145  *      READ POSITION packet command - Data Format (From Table 6-57)
1146  */
1147 typedef struct {
1148         unsigned        reserved0_10    :2;     /* Reserved */
1149         unsigned        bpu             :1;     /* Block Position Unknown */    
1150         unsigned        reserved0_543   :3;     /* Reserved */
1151         unsigned        eop             :1;     /* End Of Partition */
1152         unsigned        bop             :1;     /* Beginning Of Partition */
1153         u8              partition;              /* Partition Number */
1154         u8              reserved2, reserved3;   /* Reserved */
1155         u32             first_block;            /* First Block Location */
1156         u32             last_block;             /* Last Block Location (Optional) */
1157         u8              reserved12;             /* Reserved */
1158         u8              blocks_in_buffer[3];    /* Blocks In Buffer - (Optional) */
1159         u32             bytes_in_buffer;        /* Bytes In Buffer (Optional) */
1160 } idetape_read_position_result_t;
1161
1162 /*
1163  *      Follows structures which are related to the SELECT SENSE / MODE SENSE
1164  *      packet commands. Those packet commands are still not supported
1165  *      by ide-tape.
1166  */
1167 #define IDETAPE_BLOCK_DESCRIPTOR        0
1168 #define IDETAPE_CAPABILITIES_PAGE       0x2a
1169 #define IDETAPE_PARAMTR_PAGE            0x2b   /* Onstream DI-x0 only */
1170 #define IDETAPE_BLOCK_SIZE_PAGE         0x30
1171 #define IDETAPE_BUFFER_FILLING_PAGE     0x33
1172
1173 /*
1174  *      Mode Parameter Header for the MODE SENSE packet command
1175  */
1176 typedef struct {
1177         __u8    mode_data_length;       /* Length of the following data transfer */
1178         __u8    medium_type;            /* Medium Type */
1179         __u8    dsp;                    /* Device Specific Parameter */
1180         __u8    bdl;                    /* Block Descriptor Length */
1181 #if 0
1182         /* data transfer page */
1183         __u8    page_code       :6;
1184         __u8    reserved0_6     :1;
1185         __u8    ps              :1;     /* parameters saveable */
1186         __u8    page_length;            /* page Length == 0x02 */
1187         __u8    reserved2;
1188         __u8    read32k         :1;     /* 32k blk size (data only) */
1189         __u8    read32k5        :1;     /* 32.5k blk size (data&AUX) */
1190         __u8    reserved3_23    :2;
1191         __u8    write32k        :1;     /* 32k blk size (data only) */
1192         __u8    write32k5       :1;     /* 32.5k blk size (data&AUX) */
1193         __u8    reserved3_6     :1;
1194         __u8    streaming       :1;     /* streaming mode enable */
1195 #endif
1196 } idetape_mode_parameter_header_t;
1197
1198 /*
1199  *      Mode Parameter Block Descriptor the MODE SENSE packet command
1200  *
1201  *      Support for block descriptors is optional.
1202  */
1203 typedef struct {
1204         __u8            density_code;           /* Medium density code */
1205         __u8            blocks[3];              /* Number of blocks */
1206         __u8            reserved4;              /* Reserved */
1207         __u8            length[3];              /* Block Length */
1208 } idetape_parameter_block_descriptor_t;
1209
1210 /*
1211  *      The Data Compression Page, as returned by the MODE SENSE packet command.
1212  */
1213 typedef struct {
1214         unsigned        page_code       :6;     /* Page Code - Should be 0xf */
1215         unsigned        reserved0       :1;     /* Reserved */
1216         unsigned        ps              :1;
1217         __u8            page_length;            /* Page Length - Should be 14 */
1218         unsigned        reserved2       :6;     /* Reserved */
1219         unsigned        dcc             :1;     /* Data Compression Capable */
1220         unsigned        dce             :1;     /* Data Compression Enable */
1221         unsigned        reserved3       :5;     /* Reserved */
1222         unsigned        red             :2;     /* Report Exception on Decompression */
1223         unsigned        dde             :1;     /* Data Decompression Enable */
1224         __u32           ca;                     /* Compression Algorithm */
1225         __u32           da;                     /* Decompression Algorithm */
1226         __u8            reserved[4];            /* Reserved */
1227 } idetape_data_compression_page_t;
1228
1229 /*
1230  *      The Medium Partition Page, as returned by the MODE SENSE packet command.
1231  */
1232 typedef struct {
1233         unsigned        page_code       :6;     /* Page Code - Should be 0x11 */
1234         unsigned        reserved1_6     :1;     /* Reserved */
1235         unsigned        ps              :1;
1236         __u8            page_length;            /* Page Length - Should be 6 */
1237         __u8            map;                    /* Maximum Additional Partitions - Should be 0 */
1238         __u8            apd;                    /* Additional Partitions Defined - Should be 0 */
1239         unsigned        reserved4_012   :3;     /* Reserved */
1240         unsigned        psum            :2;     /* Should be 0 */
1241         unsigned        idp             :1;     /* Should be 0 */
1242         unsigned        sdp             :1;     /* Should be 0 */
1243         unsigned        fdp             :1;     /* Fixed Data Partitions */
1244         __u8            mfr;                    /* Medium Format Recognition */
1245         __u8            reserved[2];            /* Reserved */
1246 } idetape_medium_partition_page_t;
1247
1248 /*
1249  *      Run time configurable parameters.
1250  */
1251 typedef struct {
1252         int     dsc_rw_frequency;
1253         int     dsc_media_access_frequency;
1254         int     nr_stages;
1255 } idetape_config_t;
1256
1257 /*
1258  *      The variables below are used for the character device interface.
1259  *      Additional state variables are defined in our ide_drive_t structure.
1260  */
1261 static idetape_chrdev_t idetape_chrdevs[MAX_HWIFS * MAX_DRIVES];
1262
1263 #if IDETAPE_DEBUG_LOG_VERBOSE
1264
1265 /*
1266  * DO NOT REMOVE, BUILDING A VERBOSE DEBUG SCHEME FOR ATAPI
1267  */
1268
1269 char *idetape_sense_key_verbose(u8 idetape_sense_key)
1270 {
1271         switch (idetape_sense_key) {
1272                 default: {
1273                         char buf[22];
1274                         sprintf(buf, "IDETAPE_SENSE (0x%02x)", idetape_sense_key);
1275                         return(buf);
1276                 }
1277
1278         }
1279 }
1280
1281 char *idetape_command_key_verbose(u8 idetape_command_key)
1282 {
1283         switch (idetape_command_key) {
1284                 case IDETAPE_TEST_UNIT_READY_CMD:
1285                         return("TEST_UNIT_READY_CMD");
1286                 case IDETAPE_REWIND_CMD:
1287                         return("REWIND_CMD");
1288                 case IDETAPE_REQUEST_SENSE_CMD:
1289                         return("REQUEST_SENSE_CMD");
1290                 case IDETAPE_READ_CMD:
1291                         return("READ_CMD");
1292                 case IDETAPE_WRITE_CMD:
1293                         return("WRITE_CMD");
1294                 case IDETAPE_WRITE_FILEMARK_CMD:
1295                         return("WRITE_FILEMARK_CMD");
1296                 case IDETAPE_SPACE_CMD:
1297                         return("SPACE_CMD");
1298                 case IDETAPE_INQUIRY_CMD:
1299                         return("INQUIRY_CMD");
1300                 case IDETAPE_ERASE_CMD:
1301                         return("ERASE_CMD");
1302                 case IDETAPE_MODE_SENSE_CMD:
1303                         return("MODE_SENSE_CMD");
1304                 case IDETAPE_MODE_SELECT_CMD:
1305                         return("MODE_SELECT_CMD");
1306                 case IDETAPE_LOAD_UNLOAD_CMD:
1307                         return("LOAD_UNLOAD_CMD");
1308                 case IDETAPE_PREVENT_CMD:
1309                         return("PREVENT_CMD");
1310                 case IDETAPE_LOCATE_CMD:
1311                         return("LOCATE_CMD");
1312                 case IDETAPE_READ_POSITION_CMD:
1313                         return("READ_POSITION_CMD");
1314                 case IDETAPE_READ_BUFFER_CMD:
1315                         return("READ_BUFFER_CMD");
1316                 case IDETAPE_SET_SPEED_CMD:
1317                         return("SET_SPEED_CMD");
1318                 default: {
1319                                 char buf[20];
1320                                 sprintf(buf, "CMD (0x%02x)", idetape_command_key);
1321                                 return(buf);
1322                         }
1323         }
1324 }
1325 #endif /* IDETAPE_DEBUG_LOG_VERBOSE */
1326
1327 /*
1328  *      Function declarations
1329  *
1330  */
1331 static int idetape_chrdev_release (struct inode *inode, struct file *filp);
1332 static void idetape_write_release (ide_drive_t *drive, unsigned int minor);
1333
1334 /*
1335  * Too bad. The drive wants to send us data which we are not ready to accept.
1336  * Just throw it away.
1337  */
1338 static void idetape_discard_data (ide_drive_t *drive, unsigned int bcount)
1339 {
1340         while (bcount--)
1341                 (void) HWIF(drive)->INB(IDE_DATA_REG);
1342 }
1343
1344 static void idetape_input_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
1345 {
1346         struct idetape_bh *bh = pc->bh;
1347         int count;
1348
1349         while (bcount) {
1350 #if IDETAPE_DEBUG_BUGS
1351                 if (bh == NULL) {
1352                         printk(KERN_ERR "ide-tape: bh == NULL in "
1353                                 "idetape_input_buffers\n");
1354                         idetape_discard_data(drive, bcount);
1355                         return;
1356                 }
1357 #endif /* IDETAPE_DEBUG_BUGS */
1358                 count = min((unsigned int)(bh->b_size - atomic_read(&bh->b_count)), bcount);
1359                 HWIF(drive)->atapi_input_bytes(drive, bh->b_data + atomic_read(&bh->b_count), count);
1360                 bcount -= count;
1361                 atomic_add(count, &bh->b_count);
1362                 if (atomic_read(&bh->b_count) == bh->b_size) {
1363                         bh = bh->b_reqnext;
1364                         if (bh)
1365                                 atomic_set(&bh->b_count, 0);
1366                 }
1367         }
1368         pc->bh = bh;
1369 }
1370
1371 static void idetape_output_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
1372 {
1373         struct idetape_bh *bh = pc->bh;
1374         int count;
1375
1376         while (bcount) {
1377 #if IDETAPE_DEBUG_BUGS
1378                 if (bh == NULL) {
1379                         printk(KERN_ERR "ide-tape: bh == NULL in "
1380                                 "idetape_output_buffers\n");
1381                         return;
1382                 }
1383 #endif /* IDETAPE_DEBUG_BUGS */
1384                 count = min((unsigned int)pc->b_count, (unsigned int)bcount);
1385                 HWIF(drive)->atapi_output_bytes(drive, pc->b_data, count);
1386                 bcount -= count;
1387                 pc->b_data += count;
1388                 pc->b_count -= count;
1389                 if (!pc->b_count) {
1390                         pc->bh = bh = bh->b_reqnext;
1391                         if (bh) {
1392                                 pc->b_data = bh->b_data;
1393                                 pc->b_count = atomic_read(&bh->b_count);
1394                         }
1395                 }
1396         }
1397 }
1398
1399 static void idetape_update_buffers (idetape_pc_t *pc)
1400 {
1401         struct idetape_bh *bh = pc->bh;
1402         int count;
1403         unsigned int bcount = pc->actually_transferred;
1404
1405         if (test_bit(PC_WRITING, &pc->flags))
1406                 return;
1407         while (bcount) {
1408 #if IDETAPE_DEBUG_BUGS
1409                 if (bh == NULL) {
1410                         printk(KERN_ERR "ide-tape: bh == NULL in "
1411                                 "idetape_update_buffers\n");
1412                         return;
1413                 }
1414 #endif /* IDETAPE_DEBUG_BUGS */
1415                 count = min((unsigned int)bh->b_size, (unsigned int)bcount);
1416                 atomic_set(&bh->b_count, count);
1417                 if (atomic_read(&bh->b_count) == bh->b_size)
1418                         bh = bh->b_reqnext;
1419                 bcount -= count;
1420         }
1421         pc->bh = bh;
1422 }
1423
1424 /*
1425  *      idetape_next_pc_storage returns a pointer to a place in which we can
1426  *      safely store a packet command, even though we intend to leave the
1427  *      driver. A storage space for a maximum of IDETAPE_PC_STACK packet
1428  *      commands is allocated at initialization time.
1429  */
1430 static idetape_pc_t *idetape_next_pc_storage (ide_drive_t *drive)
1431 {
1432         idetape_tape_t *tape = drive->driver_data;
1433
1434 #if IDETAPE_DEBUG_LOG
1435         if (tape->debug_level >= 5)
1436                 printk(KERN_INFO "ide-tape: pc_stack_index=%d\n",
1437                         tape->pc_stack_index);
1438 #endif /* IDETAPE_DEBUG_LOG */
1439         if (tape->pc_stack_index == IDETAPE_PC_STACK)
1440                 tape->pc_stack_index=0;
1441         return (&tape->pc_stack[tape->pc_stack_index++]);
1442 }
1443
1444 /*
1445  *      idetape_next_rq_storage is used along with idetape_next_pc_storage.
1446  *      Since we queue packet commands in the request queue, we need to
1447  *      allocate a request, along with the allocation of a packet command.
1448  */
1449  
1450 /**************************************************************
1451  *                                                            *
1452  *  This should get fixed to use kmalloc(.., GFP_ATOMIC)      *
1453  *  followed later on by kfree().   -ml                       *
1454  *                                                            *
1455  **************************************************************/
1456  
1457 static struct request *idetape_next_rq_storage (ide_drive_t *drive)
1458 {
1459         idetape_tape_t *tape = drive->driver_data;
1460
1461 #if IDETAPE_DEBUG_LOG
1462         if (tape->debug_level >= 5)
1463                 printk(KERN_INFO "ide-tape: rq_stack_index=%d\n",
1464                         tape->rq_stack_index);
1465 #endif /* IDETAPE_DEBUG_LOG */
1466         if (tape->rq_stack_index == IDETAPE_PC_STACK)
1467                 tape->rq_stack_index=0;
1468         return (&tape->rq_stack[tape->rq_stack_index++]);
1469 }
1470
1471 /*
1472  *      idetape_init_pc initializes a packet command.
1473  */
1474 static void idetape_init_pc (idetape_pc_t *pc)
1475 {
1476         memset(pc->c, 0, 12);
1477         pc->retries = 0;
1478         pc->flags = 0;
1479         pc->request_transfer = 0;
1480         pc->buffer = pc->pc_buffer;
1481         pc->buffer_size = IDETAPE_PC_BUFFER_SIZE;
1482         pc->bh = NULL;
1483         pc->b_data = NULL;
1484 }
1485
1486 /*
1487  *      idetape_analyze_error is called on each failed packet command retry
1488  *      to analyze the request sense. We currently do not utilize this
1489  *      information.
1490  */
1491 static void idetape_analyze_error (ide_drive_t *drive, idetape_request_sense_result_t *result)
1492 {
1493         idetape_tape_t *tape = drive->driver_data;
1494         idetape_pc_t *pc = tape->failed_pc;
1495
1496         tape->sense     = *result;
1497         tape->sense_key = result->sense_key;
1498         tape->asc       = result->asc;
1499         tape->ascq      = result->ascq;
1500 #if IDETAPE_DEBUG_LOG
1501         /*
1502          *      Without debugging, we only log an error if we decided to
1503          *      give up retrying.
1504          */
1505         if (tape->debug_level >= 1)
1506                 printk(KERN_INFO "ide-tape: pc = %x, sense key = %x, "
1507                         "asc = %x, ascq = %x\n",
1508                         pc->c[0], result->sense_key,
1509                         result->asc, result->ascq);
1510 #if IDETAPE_DEBUG_LOG_VERBOSE
1511         if (tape->debug_level >= 1)
1512                 printk(KERN_INFO "ide-tape: pc = %s, sense key = %x, "
1513                         "asc = %x, ascq = %x\n",
1514                         idetape_command_key_verbose((byte) pc->c[0]),
1515                         result->sense_key,
1516                         result->asc,
1517                         result->ascq);
1518 #endif /* IDETAPE_DEBUG_LOG_VERBOSE */
1519 #endif /* IDETAPE_DEBUG_LOG */
1520
1521         /*
1522          *      Correct pc->actually_transferred by asking the tape.
1523          */
1524         if (test_bit(PC_DMA_ERROR, &pc->flags)) {
1525                 pc->actually_transferred = pc->request_transfer - tape->tape_block_size * ntohl(get_unaligned(&result->information));
1526                 idetape_update_buffers(pc);
1527         }
1528
1529         /*
1530          * If error was the result of a zero-length read or write command,
1531          * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
1532          * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
1533          */
1534         if ((pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD)
1535             && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) { /* length==0 */
1536                 if (result->sense_key == 5) {
1537                         /* don't report an error, everything's ok */
1538                         pc->error = 0;
1539                         /* don't retry read/write */
1540                         set_bit(PC_ABORT, &pc->flags);
1541                 }
1542         }
1543         if (pc->c[0] == IDETAPE_READ_CMD && result->filemark) {
1544                 pc->error = IDETAPE_ERROR_FILEMARK;
1545                 set_bit(PC_ABORT, &pc->flags);
1546         }
1547         if (pc->c[0] == IDETAPE_WRITE_CMD) {
1548                 if (result->eom ||
1549                     (result->sense_key == 0xd && result->asc == 0x0 &&
1550                      result->ascq == 0x2)) {
1551                         pc->error = IDETAPE_ERROR_EOD;
1552                         set_bit(PC_ABORT, &pc->flags);
1553                 }
1554         }
1555         if (pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD) {
1556                 if (result->sense_key == 8) {
1557                         pc->error = IDETAPE_ERROR_EOD;
1558                         set_bit(PC_ABORT, &pc->flags);
1559                 }
1560                 if (!test_bit(PC_ABORT, &pc->flags) &&
1561                     pc->actually_transferred)
1562                         pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
1563         }
1564 }
1565
1566 /*
1567  * idetape_active_next_stage will declare the next stage as "active".
1568  */
1569 static void idetape_active_next_stage (ide_drive_t *drive)
1570 {
1571         idetape_tape_t *tape = drive->driver_data;
1572         idetape_stage_t *stage = tape->next_stage;
1573         struct request *rq = &stage->rq;
1574
1575 #if IDETAPE_DEBUG_LOG
1576         if (tape->debug_level >= 4)
1577                 printk(KERN_INFO "ide-tape: Reached idetape_active_next_stage\n");
1578 #endif /* IDETAPE_DEBUG_LOG */
1579 #if IDETAPE_DEBUG_BUGS
1580         if (stage == NULL) {
1581                 printk(KERN_ERR "ide-tape: bug: Trying to activate a non existing stage\n");
1582                 return;
1583         }
1584 #endif /* IDETAPE_DEBUG_BUGS */ 
1585
1586         rq->buffer = NULL;
1587         rq->special = (void *)stage->bh;
1588         tape->active_data_request = rq;
1589         tape->active_stage = stage;
1590         tape->next_stage = stage->next;
1591 }
1592
1593 /*
1594  *      idetape_increase_max_pipeline_stages is a part of the feedback
1595  *      loop which tries to find the optimum number of stages. In the
1596  *      feedback loop, we are starting from a minimum maximum number of
1597  *      stages, and if we sense that the pipeline is empty, we try to
1598  *      increase it, until we reach the user compile time memory limit.
1599  */
1600 static void idetape_increase_max_pipeline_stages (ide_drive_t *drive)
1601 {
1602         idetape_tape_t *tape = drive->driver_data;
1603         int increase = (tape->max_pipeline - tape->min_pipeline) / 10;
1604         
1605 #if IDETAPE_DEBUG_LOG
1606         if (tape->debug_level >= 4)
1607                 printk (KERN_INFO "ide-tape: Reached idetape_increase_max_pipeline_stages\n");
1608 #endif /* IDETAPE_DEBUG_LOG */
1609
1610         tape->max_stages += max(increase, 1);
1611         tape->max_stages = max(tape->max_stages, tape->min_pipeline);
1612         tape->max_stages = min(tape->max_stages, tape->max_pipeline);
1613 }
1614
1615 /*
1616  *      idetape_kfree_stage calls kfree to completely free a stage, along with
1617  *      its related buffers.
1618  */
1619 static void __idetape_kfree_stage (idetape_stage_t *stage)
1620 {
1621         struct idetape_bh *prev_bh, *bh = stage->bh;
1622         int size;
1623
1624         while (bh != NULL) {
1625                 if (bh->b_data != NULL) {
1626                         size = (int) bh->b_size;
1627                         while (size > 0) {
1628                                 free_page((unsigned long) bh->b_data);
1629                                 size -= PAGE_SIZE;
1630                                 bh->b_data += PAGE_SIZE;
1631                         }
1632                 }
1633                 prev_bh = bh;
1634                 bh = bh->b_reqnext;
1635                 kfree(prev_bh);
1636         }
1637         kfree(stage);
1638 }
1639
1640 static void idetape_kfree_stage (idetape_tape_t *tape, idetape_stage_t *stage)
1641 {
1642         __idetape_kfree_stage(stage);
1643 }
1644
1645 /*
1646  *      idetape_remove_stage_head removes tape->first_stage from the pipeline.
1647  *      The caller should avoid race conditions.
1648  */
1649 static void idetape_remove_stage_head (ide_drive_t *drive)
1650 {
1651         idetape_tape_t *tape = drive->driver_data;
1652         idetape_stage_t *stage;
1653         
1654 #if IDETAPE_DEBUG_LOG
1655         if (tape->debug_level >= 4)
1656                 printk(KERN_INFO "ide-tape: Reached idetape_remove_stage_head\n");
1657 #endif /* IDETAPE_DEBUG_LOG */
1658 #if IDETAPE_DEBUG_BUGS
1659         if (tape->first_stage == NULL) {
1660                 printk(KERN_ERR "ide-tape: bug: tape->first_stage is NULL\n");
1661                 return;         
1662         }
1663         if (tape->active_stage == tape->first_stage) {
1664                 printk(KERN_ERR "ide-tape: bug: Trying to free our active pipeline stage\n");
1665                 return;
1666         }
1667 #endif /* IDETAPE_DEBUG_BUGS */
1668         stage = tape->first_stage;
1669         tape->first_stage = stage->next;
1670         idetape_kfree_stage(tape, stage);
1671         tape->nr_stages--;
1672         if (tape->first_stage == NULL) {
1673                 tape->last_stage = NULL;
1674 #if IDETAPE_DEBUG_BUGS
1675                 if (tape->next_stage != NULL)
1676                         printk(KERN_ERR "ide-tape: bug: tape->next_stage != NULL\n");
1677                 if (tape->nr_stages)
1678                         printk(KERN_ERR "ide-tape: bug: nr_stages should be 0 now\n");
1679 #endif /* IDETAPE_DEBUG_BUGS */
1680         }
1681 }
1682
1683 /*
1684  * This will free all the pipeline stages starting from new_last_stage->next
1685  * to the end of the list, and point tape->last_stage to new_last_stage.
1686  */
1687 static void idetape_abort_pipeline(ide_drive_t *drive,
1688                                    idetape_stage_t *new_last_stage)
1689 {
1690         idetape_tape_t *tape = drive->driver_data;
1691         idetape_stage_t *stage = new_last_stage->next;
1692         idetape_stage_t *nstage;
1693
1694 #if IDETAPE_DEBUG_LOG
1695         if (tape->debug_level >= 4)
1696                 printk(KERN_INFO "ide-tape: %s: idetape_abort_pipeline called\n", tape->name);
1697 #endif
1698         while (stage) {
1699                 nstage = stage->next;
1700                 idetape_kfree_stage(tape, stage);
1701                 --tape->nr_stages;
1702                 --tape->nr_pending_stages;
1703                 stage = nstage;
1704         }
1705         if (new_last_stage)
1706                 new_last_stage->next = NULL;
1707         tape->last_stage = new_last_stage;
1708         tape->next_stage = NULL;
1709 }
1710
1711 /*
1712  *      idetape_end_request is used to finish servicing a request, and to
1713  *      insert a pending pipeline request into the main device queue.
1714  */
1715 static int idetape_end_request(ide_drive_t *drive, int uptodate, int nr_sects)
1716 {
1717         struct request *rq = HWGROUP(drive)->rq;
1718         idetape_tape_t *tape = drive->driver_data;
1719         unsigned long flags;
1720         int error;
1721         int remove_stage = 0;
1722         idetape_stage_t *active_stage;
1723
1724 #if IDETAPE_DEBUG_LOG
1725         if (tape->debug_level >= 4)
1726         printk(KERN_INFO "ide-tape: Reached idetape_end_request\n");
1727 #endif /* IDETAPE_DEBUG_LOG */
1728
1729         switch (uptodate) {
1730                 case 0: error = IDETAPE_ERROR_GENERAL; break;
1731                 case 1: error = 0; break;
1732                 default: error = uptodate;
1733         }
1734         rq->errors = error;
1735         if (error)
1736                 tape->failed_pc = NULL;
1737
1738         spin_lock_irqsave(&tape->spinlock, flags);
1739
1740         /* The request was a pipelined data transfer request */
1741         if (tape->active_data_request == rq) {
1742                 active_stage = tape->active_stage;
1743                 tape->active_stage = NULL;
1744                 tape->active_data_request = NULL;
1745                 tape->nr_pending_stages--;
1746                 if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
1747                         remove_stage = 1;
1748                         if (error) {
1749                                 set_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
1750                                 if (error == IDETAPE_ERROR_EOD)
1751                                         idetape_abort_pipeline(drive, active_stage);
1752                         }
1753                 } else if (rq->cmd[0] & REQ_IDETAPE_READ) {
1754                         if (error == IDETAPE_ERROR_EOD) {
1755                                 set_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
1756                                 idetape_abort_pipeline(drive, active_stage);
1757                         }
1758                 }
1759                 if (tape->next_stage != NULL) {
1760                         idetape_active_next_stage(drive);
1761
1762                         /*
1763                          * Insert the next request into the request queue.
1764                          */
1765                         (void) ide_do_drive_cmd(drive, tape->active_data_request, ide_end);
1766                 } else if (!error) {
1767                                 idetape_increase_max_pipeline_stages(drive);
1768                 }
1769         }
1770         ide_end_drive_cmd(drive, 0, 0);
1771 //      blkdev_dequeue_request(rq);
1772 //      drive->rq = NULL;
1773 //      end_that_request_last(rq);
1774
1775         if (remove_stage)
1776                 idetape_remove_stage_head(drive);
1777         if (tape->active_data_request == NULL)
1778                 clear_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
1779         spin_unlock_irqrestore(&tape->spinlock, flags);
1780         return 0;
1781 }
1782
1783 static ide_startstop_t idetape_request_sense_callback (ide_drive_t *drive)
1784 {
1785         idetape_tape_t *tape = drive->driver_data;
1786
1787 #if IDETAPE_DEBUG_LOG
1788         if (tape->debug_level >= 4)
1789                 printk(KERN_INFO "ide-tape: Reached idetape_request_sense_callback\n");
1790 #endif /* IDETAPE_DEBUG_LOG */
1791         if (!tape->pc->error) {
1792                 idetape_analyze_error(drive, (idetape_request_sense_result_t *) tape->pc->buffer);
1793                 idetape_end_request(drive, 1, 0);
1794         } else {
1795                 printk(KERN_ERR "ide-tape: Error in REQUEST SENSE itself - Aborting request!\n");
1796                 idetape_end_request(drive, 0, 0);
1797         }
1798         return ide_stopped;
1799 }
1800
1801 static void idetape_create_request_sense_cmd (idetape_pc_t *pc)
1802 {
1803         idetape_init_pc(pc);    
1804         pc->c[0] = IDETAPE_REQUEST_SENSE_CMD;
1805         pc->c[4] = 20;
1806         pc->request_transfer = 20;
1807         pc->callback = &idetape_request_sense_callback;
1808 }
1809
1810 static void idetape_init_rq(struct request *rq, u8 cmd)
1811 {
1812         memset(rq, 0, sizeof(*rq));
1813         rq->flags = REQ_SPECIAL;
1814         rq->cmd[0] = cmd;
1815 }
1816
1817 /*
1818  *      idetape_queue_pc_head generates a new packet command request in front
1819  *      of the request queue, before the current request, so that it will be
1820  *      processed immediately, on the next pass through the driver.
1821  *
1822  *      idetape_queue_pc_head is called from the request handling part of
1823  *      the driver (the "bottom" part). Safe storage for the request should
1824  *      be allocated with idetape_next_pc_storage and idetape_next_rq_storage
1825  *      before calling idetape_queue_pc_head.
1826  *
1827  *      Memory for those requests is pre-allocated at initialization time, and
1828  *      is limited to IDETAPE_PC_STACK requests. We assume that we have enough
1829  *      space for the maximum possible number of inter-dependent packet commands.
1830  *
1831  *      The higher level of the driver - The ioctl handler and the character
1832  *      device handling functions should queue request to the lower level part
1833  *      and wait for their completion using idetape_queue_pc_tail or
1834  *      idetape_queue_rw_tail.
1835  */
1836 static void idetape_queue_pc_head (ide_drive_t *drive, idetape_pc_t *pc,struct request *rq)
1837 {
1838         idetape_init_rq(rq, REQ_IDETAPE_PC1);
1839         rq->buffer = (char *) pc;
1840         (void) ide_do_drive_cmd(drive, rq, ide_preempt);
1841 }
1842
1843 /*
1844  *      idetape_retry_pc is called when an error was detected during the
1845  *      last packet command. We queue a request sense packet command in
1846  *      the head of the request list.
1847  */
1848 static ide_startstop_t idetape_retry_pc (ide_drive_t *drive)
1849 {
1850         idetape_tape_t *tape = drive->driver_data;
1851         idetape_pc_t *pc;
1852         struct request *rq;
1853         atapi_error_t error;
1854
1855         error.all = HWIF(drive)->INB(IDE_ERROR_REG);
1856         pc = idetape_next_pc_storage(drive);
1857         rq = idetape_next_rq_storage(drive);
1858         idetape_create_request_sense_cmd(pc);
1859         set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
1860         idetape_queue_pc_head(drive, pc, rq);
1861         return ide_stopped;
1862 }
1863
1864 /*
1865  *      idetape_postpone_request postpones the current request so that
1866  *      ide.c will be able to service requests from another device on
1867  *      the same hwgroup while we are polling for DSC.
1868  */
1869 static void idetape_postpone_request (ide_drive_t *drive)
1870 {
1871         idetape_tape_t *tape = drive->driver_data;
1872
1873 #if IDETAPE_DEBUG_LOG
1874         if (tape->debug_level >= 4)
1875                 printk(KERN_INFO "ide-tape: idetape_postpone_request\n");
1876 #endif
1877         tape->postponed_rq = HWGROUP(drive)->rq;
1878         ide_stall_queue(drive, tape->dsc_polling_frequency);
1879 }
1880
1881 /*
1882  *      idetape_pc_intr is the usual interrupt handler which will be called
1883  *      during a packet command. We will transfer some of the data (as
1884  *      requested by the drive) and will re-point interrupt handler to us.
1885  *      When data transfer is finished, we will act according to the
1886  *      algorithm described before idetape_issue_packet_command.
1887  *
1888  */
1889 static ide_startstop_t idetape_pc_intr (ide_drive_t *drive)
1890 {
1891         ide_hwif_t *hwif = drive->hwif;
1892         idetape_tape_t *tape = drive->driver_data;
1893         atapi_status_t status;
1894         atapi_bcount_t bcount;
1895         atapi_ireason_t ireason;
1896         idetape_pc_t *pc = tape->pc;
1897
1898         unsigned int temp;
1899 #if SIMULATE_ERRORS
1900         static int error_sim_count = 0;
1901 #endif
1902
1903 #if IDETAPE_DEBUG_LOG
1904         if (tape->debug_level >= 4)
1905                 printk(KERN_INFO "ide-tape: Reached idetape_pc_intr "
1906                                 "interrupt handler\n");
1907 #endif /* IDETAPE_DEBUG_LOG */  
1908
1909         /* Clear the interrupt */
1910         status.all = HWIF(drive)->INB(IDE_STATUS_REG);
1911
1912         if (test_bit(PC_DMA_IN_PROGRESS, &pc->flags)) {
1913                 if (HWIF(drive)->ide_dma_end(drive) || status.b.check) {
1914                         /*
1915                          * A DMA error is sometimes expected. For example,
1916                          * if the tape is crossing a filemark during a
1917                          * READ command, it will issue an irq and position
1918                          * itself before the filemark, so that only a partial
1919                          * data transfer will occur (which causes the DMA
1920                          * error). In that case, we will later ask the tape
1921                          * how much bytes of the original request were
1922                          * actually transferred (we can't receive that
1923                          * information from the DMA engine on most chipsets).
1924                          */
1925
1926                         /*
1927                          * On the contrary, a DMA error is never expected;
1928                          * it usually indicates a hardware error or abort.
1929                          * If the tape crosses a filemark during a READ
1930                          * command, it will issue an irq and position itself
1931                          * after the filemark (not before). Only a partial
1932                          * data transfer will occur, but no DMA error.
1933                          * (AS, 19 Apr 2001)
1934                          */
1935                         set_bit(PC_DMA_ERROR, &pc->flags);
1936                 } else {
1937                         pc->actually_transferred = pc->request_transfer;
1938                         idetape_update_buffers(pc);
1939                 }
1940 #if IDETAPE_DEBUG_LOG
1941                 if (tape->debug_level >= 4)
1942                         printk(KERN_INFO "ide-tape: DMA finished\n");
1943 #endif /* IDETAPE_DEBUG_LOG */
1944         }
1945
1946         /* No more interrupts */
1947         if (!status.b.drq) {
1948 #if IDETAPE_DEBUG_LOG
1949                 if (tape->debug_level >= 2)
1950                         printk(KERN_INFO "ide-tape: Packet command completed, %d bytes transferred\n", pc->actually_transferred);
1951 #endif /* IDETAPE_DEBUG_LOG */
1952                 clear_bit(PC_DMA_IN_PROGRESS, &pc->flags);
1953
1954                 local_irq_enable();
1955
1956 #if SIMULATE_ERRORS
1957                 if ((pc->c[0] == IDETAPE_WRITE_CMD ||
1958                      pc->c[0] == IDETAPE_READ_CMD) &&
1959                     (++error_sim_count % 100) == 0) {
1960                         printk(KERN_INFO "ide-tape: %s: simulating error\n",
1961                                 tape->name);
1962                         status.b.check = 1;
1963                 }
1964 #endif
1965                 if (status.b.check && pc->c[0] == IDETAPE_REQUEST_SENSE_CMD)
1966                         status.b.check = 0;
1967                 if (status.b.check || test_bit(PC_DMA_ERROR, &pc->flags)) {     /* Error detected */
1968 #if IDETAPE_DEBUG_LOG
1969                         if (tape->debug_level >= 1)
1970                                 printk(KERN_INFO "ide-tape: %s: I/O error\n",
1971                                         tape->name);
1972 #endif /* IDETAPE_DEBUG_LOG */
1973                         if (pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1974                                 printk(KERN_ERR "ide-tape: I/O error in request sense command\n");
1975                                 return ide_do_reset(drive);
1976                         }
1977 #if IDETAPE_DEBUG_LOG
1978                         if (tape->debug_level >= 1)
1979                                 printk(KERN_INFO "ide-tape: [cmd %x]: check condition\n", pc->c[0]);
1980 #endif
1981                         /* Retry operation */
1982                         return idetape_retry_pc(drive);
1983                 }
1984                 pc->error = 0;
1985                 if (test_bit(PC_WAIT_FOR_DSC, &pc->flags) &&
1986                     !status.b.dsc) {
1987                         /* Media access command */
1988                         tape->dsc_polling_start = jiffies;
1989                         tape->dsc_polling_frequency = IDETAPE_DSC_MA_FAST;
1990                         tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
1991                         /* Allow ide.c to handle other requests */
1992                         idetape_postpone_request(drive);
1993                         return ide_stopped;
1994                 }
1995                 if (tape->failed_pc == pc)
1996                         tape->failed_pc = NULL;
1997                 /* Command finished - Call the callback function */
1998                 return pc->callback(drive);
1999         }
2000         if (test_and_clear_bit(PC_DMA_IN_PROGRESS, &pc->flags)) {
2001                 printk(KERN_ERR "ide-tape: The tape wants to issue more "
2002                                 "interrupts in DMA mode\n");
2003                 printk(KERN_ERR "ide-tape: DMA disabled, reverting to PIO\n");
2004                 (void)__ide_dma_off(drive);
2005                 return ide_do_reset(drive);
2006         }
2007         /* Get the number of bytes to transfer on this interrupt. */
2008         bcount.b.high = hwif->INB(IDE_BCOUNTH_REG);
2009         bcount.b.low = hwif->INB(IDE_BCOUNTL_REG);
2010
2011         ireason.all = hwif->INB(IDE_IREASON_REG);
2012
2013         if (ireason.b.cod) {
2014                 printk(KERN_ERR "ide-tape: CoD != 0 in idetape_pc_intr\n");
2015                 return ide_do_reset(drive);
2016         }
2017         if (ireason.b.io == test_bit(PC_WRITING, &pc->flags)) {
2018                 /* Hopefully, we will never get here */
2019                 printk(KERN_ERR "ide-tape: We wanted to %s, ",
2020                         ireason.b.io ? "Write":"Read");
2021                 printk(KERN_ERR "ide-tape: but the tape wants us to %s !\n",
2022                         ireason.b.io ? "Read":"Write");
2023                 return ide_do_reset(drive);
2024         }
2025         if (!test_bit(PC_WRITING, &pc->flags)) {
2026                 /* Reading - Check that we have enough space */
2027                 temp = pc->actually_transferred + bcount.all;
2028                 if (temp > pc->request_transfer) {
2029                         if (temp > pc->buffer_size) {
2030                                 printk(KERN_ERR "ide-tape: The tape wants to send us more data than expected - discarding data\n");
2031                                 idetape_discard_data(drive, bcount.all);
2032                                 ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
2033                                 return ide_started;
2034                         }
2035 #if IDETAPE_DEBUG_LOG
2036                         if (tape->debug_level >= 2)
2037                                 printk(KERN_NOTICE "ide-tape: The tape wants to send us more data than expected - allowing transfer\n");
2038 #endif /* IDETAPE_DEBUG_LOG */
2039                 }
2040         }
2041         if (test_bit(PC_WRITING, &pc->flags)) {
2042                 if (pc->bh != NULL)
2043                         idetape_output_buffers(drive, pc, bcount.all);
2044                 else
2045                         /* Write the current buffer */
2046                         HWIF(drive)->atapi_output_bytes(drive, pc->current_position, bcount.all);
2047         } else {
2048                 if (pc->bh != NULL)
2049                         idetape_input_buffers(drive, pc, bcount.all);
2050                 else
2051                         /* Read the current buffer */
2052                         HWIF(drive)->atapi_input_bytes(drive, pc->current_position, bcount.all);
2053         }
2054         /* Update the current position */
2055         pc->actually_transferred += bcount.all;
2056         pc->current_position += bcount.all;
2057 #if IDETAPE_DEBUG_LOG
2058         if (tape->debug_level >= 2)
2059                 printk(KERN_INFO "ide-tape: [cmd %x] transferred %d bytes on that interrupt\n", pc->c[0], bcount.all);
2060 #endif
2061         /* And set the interrupt handler again */
2062         ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
2063         return ide_started;
2064 }
2065
2066 /*
2067  *      Packet Command Interface
2068  *
2069  *      The current Packet Command is available in tape->pc, and will not
2070  *      change until we finish handling it. Each packet command is associated
2071  *      with a callback function that will be called when the command is
2072  *      finished.
2073  *
2074  *      The handling will be done in three stages:
2075  *
2076  *      1.      idetape_issue_packet_command will send the packet command to the
2077  *              drive, and will set the interrupt handler to idetape_pc_intr.
2078  *
2079  *      2.      On each interrupt, idetape_pc_intr will be called. This step
2080  *              will be repeated until the device signals us that no more
2081  *              interrupts will be issued.
2082  *
2083  *      3.      ATAPI Tape media access commands have immediate status with a
2084  *              delayed process. In case of a successful initiation of a
2085  *              media access packet command, the DSC bit will be set when the
2086  *              actual execution of the command is finished. 
2087  *              Since the tape drive will not issue an interrupt, we have to
2088  *              poll for this event. In this case, we define the request as
2089  *              "low priority request" by setting rq_status to
2090  *              IDETAPE_RQ_POSTPONED,   set a timer to poll for DSC and exit
2091  *              the driver.
2092  *
2093  *              ide.c will then give higher priority to requests which
2094  *              originate from the other device, until will change rq_status
2095  *              to RQ_ACTIVE.
2096  *
2097  *      4.      When the packet command is finished, it will be checked for errors.
2098  *
2099  *      5.      In case an error was found, we queue a request sense packet
2100  *              command in front of the request queue and retry the operation
2101  *              up to IDETAPE_MAX_PC_RETRIES times.
2102  *
2103  *      6.      In case no error was found, or we decided to give up and not
2104  *              to retry again, the callback function will be called and then
2105  *              we will handle the next request.
2106  *
2107  */
2108 static ide_startstop_t idetape_transfer_pc(ide_drive_t *drive)
2109 {
2110         ide_hwif_t *hwif = drive->hwif;
2111         idetape_tape_t *tape = drive->driver_data;
2112         idetape_pc_t *pc = tape->pc;
2113         atapi_ireason_t ireason;
2114         int retries = 100;
2115         ide_startstop_t startstop;
2116
2117         if (ide_wait_stat(&startstop,drive,DRQ_STAT,BUSY_STAT,WAIT_READY)) {
2118                 printk(KERN_ERR "ide-tape: Strange, packet command initiated yet DRQ isn't asserted\n");
2119                 return startstop;
2120         }
2121         ireason.all = hwif->INB(IDE_IREASON_REG);
2122         while (retries-- && (!ireason.b.cod || ireason.b.io)) {
2123                 printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while issuing "
2124                                 "a packet command, retrying\n");
2125                 udelay(100);
2126                 ireason.all = hwif->INB(IDE_IREASON_REG);
2127                 if (retries == 0) {
2128                         printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while "
2129                                         "issuing a packet command, ignoring\n");
2130                         ireason.b.cod = 1;
2131                         ireason.b.io = 0;
2132                 }
2133         }
2134         if (!ireason.b.cod || ireason.b.io) {
2135                 printk(KERN_ERR "ide-tape: (IO,CoD) != (0,1) while issuing "
2136                                 "a packet command\n");
2137                 return ide_do_reset(drive);
2138         }
2139         /* Set the interrupt routine */
2140         ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
2141 #ifdef CONFIG_BLK_DEV_IDEDMA
2142         /* Begin DMA, if necessary */
2143         if (test_bit(PC_DMA_IN_PROGRESS, &pc->flags))
2144                 (void) (HWIF(drive)->ide_dma_begin(drive));
2145 #endif
2146         /* Send the actual packet */
2147         HWIF(drive)->atapi_output_bytes(drive, pc->c, 12);
2148         return ide_started;
2149 }
2150
2151 static ide_startstop_t idetape_issue_packet_command (ide_drive_t *drive, idetape_pc_t *pc)
2152 {
2153         ide_hwif_t *hwif = drive->hwif;
2154         idetape_tape_t *tape = drive->driver_data;
2155         atapi_bcount_t bcount;
2156         int dma_ok = 0;
2157
2158 #if IDETAPE_DEBUG_BUGS
2159         if (tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD &&
2160             pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
2161                 printk(KERN_ERR "ide-tape: possible ide-tape.c bug - "
2162                         "Two request sense in serial were issued\n");
2163         }
2164 #endif /* IDETAPE_DEBUG_BUGS */
2165
2166         if (tape->failed_pc == NULL && pc->c[0] != IDETAPE_REQUEST_SENSE_CMD)
2167                 tape->failed_pc = pc;
2168         /* Set the current packet command */
2169         tape->pc = pc;
2170
2171         if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
2172             test_bit(PC_ABORT, &pc->flags)) {
2173                 /*
2174                  *      We will "abort" retrying a packet command in case
2175                  *      a legitimate error code was received (crossing a
2176                  *      filemark, or end of the media, for example).
2177                  */
2178                 if (!test_bit(PC_ABORT, &pc->flags)) {
2179                         if (!(pc->c[0] == IDETAPE_TEST_UNIT_READY_CMD &&
2180                               tape->sense_key == 2 && tape->asc == 4 &&
2181                              (tape->ascq == 1 || tape->ascq == 8))) {
2182                                 printk(KERN_ERR "ide-tape: %s: I/O error, "
2183                                                 "pc = %2x, key = %2x, "
2184                                                 "asc = %2x, ascq = %2x\n",
2185                                                 tape->name, pc->c[0],
2186                                                 tape->sense_key, tape->asc,
2187                                                 tape->ascq);
2188                         }
2189                         /* Giving up */
2190                         pc->error = IDETAPE_ERROR_GENERAL;
2191                 }
2192                 tape->failed_pc = NULL;
2193                 return pc->callback(drive);
2194         }
2195 #if IDETAPE_DEBUG_LOG
2196         if (tape->debug_level >= 2)
2197                 printk(KERN_INFO "ide-tape: Retry number - %d, cmd = %02X\n", pc->retries, pc->c[0]);
2198 #endif /* IDETAPE_DEBUG_LOG */
2199
2200         pc->retries++;
2201         /* We haven't transferred any data yet */
2202         pc->actually_transferred = 0;
2203         pc->current_position = pc->buffer;
2204         /* Request to transfer the entire buffer at once */
2205         bcount.all = pc->request_transfer;
2206
2207         if (test_and_clear_bit(PC_DMA_ERROR, &pc->flags)) {
2208                 printk(KERN_WARNING "ide-tape: DMA disabled, "
2209                                 "reverting to PIO\n");
2210                 (void)__ide_dma_off(drive);
2211         }
2212         if (test_bit(PC_DMA_RECOMMENDED, &pc->flags) && drive->using_dma) {
2213                 if (test_bit(PC_WRITING, &pc->flags))
2214                         dma_ok = !HWIF(drive)->ide_dma_write(drive);
2215                 else
2216                         dma_ok = !HWIF(drive)->ide_dma_read(drive);
2217         }
2218
2219         if (IDE_CONTROL_REG)
2220                 hwif->OUTB(drive->ctl, IDE_CONTROL_REG);
2221         hwif->OUTB(dma_ok ? 1 : 0, IDE_FEATURE_REG);    /* Use PIO/DMA */
2222         hwif->OUTB(bcount.b.high, IDE_BCOUNTH_REG);
2223         hwif->OUTB(bcount.b.low, IDE_BCOUNTL_REG);
2224         hwif->OUTB(drive->select.all, IDE_SELECT_REG);
2225         if (dma_ok)                     /* Will begin DMA later */
2226                 set_bit(PC_DMA_IN_PROGRESS, &pc->flags);
2227         if (test_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags)) {
2228                 ide_set_handler(drive, &idetape_transfer_pc, IDETAPE_WAIT_CMD, NULL);
2229                 hwif->OUTB(WIN_PACKETCMD, IDE_COMMAND_REG);
2230                 return ide_started;
2231         } else {
2232                 hwif->OUTB(WIN_PACKETCMD, IDE_COMMAND_REG);
2233                 return idetape_transfer_pc(drive);
2234         }
2235 }
2236
2237 /*
2238  *      General packet command callback function.
2239  */
2240 static ide_startstop_t idetape_pc_callback (ide_drive_t *drive)
2241 {
2242         idetape_tape_t *tape = drive->driver_data;
2243         
2244 #if IDETAPE_DEBUG_LOG
2245         if (tape->debug_level >= 4)
2246                 printk(KERN_INFO "ide-tape: Reached idetape_pc_callback\n");
2247 #endif /* IDETAPE_DEBUG_LOG */
2248
2249         idetape_end_request(drive, tape->pc->error ? 0 : 1, 0);
2250         return ide_stopped;
2251 }
2252
2253 /*
2254  *      A mode sense command is used to "sense" tape parameters.
2255  */
2256 static void idetape_create_mode_sense_cmd (idetape_pc_t *pc, u8 page_code)
2257 {
2258         idetape_init_pc(pc);
2259         pc->c[0] = IDETAPE_MODE_SENSE_CMD;
2260         if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
2261                 pc->c[1] = 8;   /* DBD = 1 - Don't return block descriptors */
2262         pc->c[2] = page_code;
2263         /*
2264          * Changed pc->c[3] to 0 (255 will at best return unused info).
2265          *
2266          * For SCSI this byte is defined as subpage instead of high byte
2267          * of length and some IDE drives seem to interpret it this way
2268          * and return an error when 255 is used.
2269          */
2270         pc->c[3] = 0;
2271         pc->c[4] = 255;         /* (We will just discard data in that case) */
2272         if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
2273                 pc->request_transfer = 12;
2274         else if (page_code == IDETAPE_CAPABILITIES_PAGE)
2275                 pc->request_transfer = 24;
2276         else
2277                 pc->request_transfer = 50;
2278         pc->callback = &idetape_pc_callback;
2279 }
2280
2281 static void calculate_speeds(ide_drive_t *drive)
2282 {
2283         idetape_tape_t *tape = drive->driver_data;
2284         int full = 125, empty = 75;
2285
2286         if (time_after(jiffies, tape->controlled_pipeline_head_time + 120 * HZ)) {
2287                 tape->controlled_previous_pipeline_head = tape->controlled_last_pipeline_head;
2288                 tape->controlled_previous_head_time = tape->controlled_pipeline_head_time;
2289                 tape->controlled_last_pipeline_head = tape->pipeline_head;
2290                 tape->controlled_pipeline_head_time = jiffies;
2291         }
2292         if (time_after(jiffies, tape->controlled_pipeline_head_time + 60 * HZ))
2293                 tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_last_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_pipeline_head_time);
2294         else if (time_after(jiffies, tape->controlled_previous_head_time))
2295                 tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_previous_head_time);
2296
2297         if (tape->nr_pending_stages < tape->max_stages /*- 1 */) {
2298                 /* -1 for read mode error recovery */
2299                 if (time_after(jiffies, tape->uncontrolled_previous_head_time + 10 * HZ)) {
2300                         tape->uncontrolled_pipeline_head_time = jiffies;
2301                         tape->uncontrolled_pipeline_head_speed = (tape->pipeline_head - tape->uncontrolled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->uncontrolled_previous_head_time);
2302                 }
2303         } else {
2304                 tape->uncontrolled_previous_head_time = jiffies;
2305                 tape->uncontrolled_previous_pipeline_head = tape->pipeline_head;
2306                 if (time_after(jiffies, tape->uncontrolled_pipeline_head_time + 30 * HZ)) {
2307                         tape->uncontrolled_pipeline_head_time = jiffies;
2308                 }
2309         }
2310         tape->pipeline_head_speed = max(tape->uncontrolled_pipeline_head_speed, tape->controlled_pipeline_head_speed);
2311         if (tape->speed_control == 0) {
2312                 tape->max_insert_speed = 5000;
2313         } else if (tape->speed_control == 1) {
2314                 if (tape->nr_pending_stages >= tape->max_stages / 2)
2315                         tape->max_insert_speed = tape->pipeline_head_speed +
2316                                 (1100 - tape->pipeline_head_speed) * 2 * (tape->nr_pending_stages - tape->max_stages / 2) / tape->max_stages;
2317                 else
2318                         tape->max_insert_speed = 500 +
2319                                 (tape->pipeline_head_speed - 500) * 2 * tape->nr_pending_stages / tape->max_stages;
2320                 if (tape->nr_pending_stages >= tape->max_stages * 99 / 100)
2321                         tape->max_insert_speed = 5000;
2322         } else if (tape->speed_control == 2) {
2323                 tape->max_insert_speed = tape->pipeline_head_speed * empty / 100 +
2324                         (tape->pipeline_head_speed * full / 100 - tape->pipeline_head_speed * empty / 100) * tape->nr_pending_stages / tape->max_stages;
2325         } else
2326                 tape->max_insert_speed = tape->speed_control;
2327         tape->max_insert_speed = max(tape->max_insert_speed, 500);
2328 }
2329
2330 static ide_startstop_t idetape_media_access_finished (ide_drive_t *drive)
2331 {
2332         idetape_tape_t *tape = drive->driver_data;
2333         idetape_pc_t *pc = tape->pc;
2334         atapi_status_t status;
2335
2336         status.all = HWIF(drive)->INB(IDE_STATUS_REG);
2337         if (status.b.dsc) {
2338                 if (status.b.check) {
2339                         /* Error detected */
2340                         if (pc->c[0] != IDETAPE_TEST_UNIT_READY_CMD)
2341                                 printk(KERN_ERR "ide-tape: %s: I/O error, ",
2342                                                 tape->name);
2343                         /* Retry operation */
2344                         return idetape_retry_pc(drive);
2345                 }
2346                 pc->error = 0;
2347                 if (tape->failed_pc == pc)
2348                         tape->failed_pc = NULL;
2349         } else {
2350                 pc->error = IDETAPE_ERROR_GENERAL;
2351                 tape->failed_pc = NULL;
2352         }
2353         return pc->callback(drive);
2354 }
2355
2356 static ide_startstop_t idetape_rw_callback (ide_drive_t *drive)
2357 {
2358         idetape_tape_t *tape = drive->driver_data;
2359         struct request *rq = HWGROUP(drive)->rq;
2360         int blocks = tape->pc->actually_transferred / tape->tape_block_size;
2361
2362         tape->avg_size += blocks * tape->tape_block_size;
2363         tape->insert_size += blocks * tape->tape_block_size;
2364         if (tape->insert_size > 1024 * 1024)
2365                 tape->measure_insert_time = 1;
2366         if (tape->measure_insert_time) {
2367                 tape->measure_insert_time = 0;
2368                 tape->insert_time = jiffies;
2369                 tape->insert_size = 0;
2370         }
2371         if (time_after(jiffies, tape->insert_time))
2372                 tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
2373         if (jiffies - tape->avg_time >= HZ) {
2374                 tape->avg_speed = tape->avg_size * HZ / (jiffies - tape->avg_time) / 1024;
2375                 tape->avg_size = 0;
2376                 tape->avg_time = jiffies;
2377         }
2378
2379 #if IDETAPE_DEBUG_LOG   
2380         if (tape->debug_level >= 4)
2381                 printk(KERN_INFO "ide-tape: Reached idetape_rw_callback\n");
2382 #endif /* IDETAPE_DEBUG_LOG */
2383
2384         tape->first_frame_position += blocks;
2385         rq->current_nr_sectors -= blocks;
2386
2387         if (!tape->pc->error)
2388                 idetape_end_request(drive, 1, 0);
2389         else
2390                 idetape_end_request(drive, tape->pc->error, 0);
2391         return ide_stopped;
2392 }
2393
2394 static void idetape_create_read_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
2395 {
2396         idetape_init_pc(pc);
2397         pc->c[0] = IDETAPE_READ_CMD;
2398         put_unaligned(htonl(length), (unsigned int *) &pc->c[1]);
2399         pc->c[1] = 1;
2400         pc->callback = &idetape_rw_callback;
2401         pc->bh = bh;
2402         atomic_set(&bh->b_count, 0);
2403         pc->buffer = NULL;
2404         pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
2405         if (pc->request_transfer == tape->stage_size)
2406                 set_bit(PC_DMA_RECOMMENDED, &pc->flags);
2407 }
2408
2409 static void idetape_create_read_buffer_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
2410 {
2411         int size = 32768;
2412         struct idetape_bh *p = bh;
2413
2414         idetape_init_pc(pc);
2415         pc->c[0] = IDETAPE_READ_BUFFER_CMD;
2416         pc->c[1] = IDETAPE_RETRIEVE_FAULTY_BLOCK;
2417         pc->c[7] = size >> 8;
2418         pc->c[8] = size & 0xff;
2419         pc->callback = &idetape_pc_callback;
2420         pc->bh = bh;
2421         atomic_set(&bh->b_count, 0);
2422         pc->buffer = NULL;
2423         while (p) {
2424                 atomic_set(&p->b_count, 0);
2425                 p = p->b_reqnext;
2426         }
2427         pc->request_transfer = pc->buffer_size = size;
2428 }
2429
2430 static void idetape_create_write_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
2431 {
2432         idetape_init_pc(pc);
2433         pc->c[0] = IDETAPE_WRITE_CMD;
2434         put_unaligned(htonl(length), (unsigned int *) &pc->c[1]);
2435         pc->c[1] = 1;
2436         pc->callback = &idetape_rw_callback;
2437         set_bit(PC_WRITING, &pc->flags);
2438         pc->bh = bh;
2439         pc->b_data = bh->b_data;
2440         pc->b_count = atomic_read(&bh->b_count);
2441         pc->buffer = NULL;
2442         pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
2443         if (pc->request_transfer == tape->stage_size)
2444                 set_bit(PC_DMA_RECOMMENDED, &pc->flags);
2445 }
2446
2447 /*
2448  * idetape_do_request is our request handling function. 
2449  */
2450 static ide_startstop_t idetape_do_request(ide_drive_t *drive,
2451                                           struct request *rq, sector_t block)
2452 {
2453         idetape_tape_t *tape = drive->driver_data;
2454         idetape_pc_t *pc = NULL;
2455         struct request *postponed_rq = tape->postponed_rq;
2456         atapi_status_t status;
2457
2458 #if IDETAPE_DEBUG_LOG
2459 #if 0
2460         if (tape->debug_level >= 5)
2461                 printk(KERN_INFO "ide-tape: rq_status: %d, "
2462                         "dev: %s, cmd: %ld, errors: %d\n", rq->rq_status,
2463                          rq->rq_disk->disk_name, rq->cmd[0], rq->errors);
2464 #endif
2465         if (tape->debug_level >= 2)
2466                 printk(KERN_INFO "ide-tape: sector: %ld, "
2467                         "nr_sectors: %ld, current_nr_sectors: %d\n",
2468                         rq->sector, rq->nr_sectors, rq->current_nr_sectors);
2469 #endif /* IDETAPE_DEBUG_LOG */
2470
2471         if ((rq->flags & REQ_SPECIAL) == 0) {
2472                 /*
2473                  * We do not support buffer cache originated requests.
2474                  */
2475                 printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
2476                         "request queue (%ld)\n", drive->name, rq->flags);
2477                 ide_end_request(drive, 0, 0);
2478                 return ide_stopped;
2479         }
2480
2481         /*
2482          *      Retry a failed packet command
2483          */
2484         if (tape->failed_pc != NULL &&
2485             tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
2486                 return idetape_issue_packet_command(drive, tape->failed_pc);
2487         }
2488 #if IDETAPE_DEBUG_BUGS
2489         if (postponed_rq != NULL)
2490                 if (rq != postponed_rq) {
2491                         printk(KERN_ERR "ide-tape: ide-tape.c bug - "
2492                                         "Two DSC requests were queued\n");
2493                         idetape_end_request(drive, 0, 0);
2494                         return ide_stopped;
2495                 }
2496 #endif /* IDETAPE_DEBUG_BUGS */
2497
2498         tape->postponed_rq = NULL;
2499
2500         /*
2501          * If the tape is still busy, postpone our request and service
2502          * the other device meanwhile.
2503          */
2504         status.all = HWIF(drive)->INB(IDE_STATUS_REG);
2505
2506         if (!drive->dsc_overlap && !(rq->cmd[0] & REQ_IDETAPE_PC2))
2507                 set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
2508
2509         if (tape->tape_still_time > 100 && tape->tape_still_time < 200)
2510                 tape->measure_insert_time = 1;
2511         if (time_after(jiffies, tape->insert_time))
2512                 tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
2513         calculate_speeds(drive);
2514         if (!test_and_clear_bit(IDETAPE_IGNORE_DSC, &tape->flags) &&
2515             !status.b.dsc) {
2516                 if (postponed_rq == NULL) {
2517                         tape->dsc_polling_start = jiffies;
2518                         tape->dsc_polling_frequency = tape->best_dsc_rw_frequency;
2519                         tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
2520                 } else if ((signed long) (jiffies - tape->dsc_timeout) > 0) {
2521                         printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
2522                                 tape->name);
2523                         if (rq->cmd[0] & REQ_IDETAPE_PC2) {
2524                                 idetape_media_access_finished(drive);
2525                                 return ide_stopped;
2526                         } else {
2527                                 return ide_do_reset(drive);
2528                         }
2529                 } else if (jiffies - tape->dsc_polling_start > IDETAPE_DSC_MA_THRESHOLD)
2530                         tape->dsc_polling_frequency = IDETAPE_DSC_MA_SLOW;
2531                 idetape_postpone_request(drive);
2532                 return ide_stopped;
2533         }
2534         if (rq->cmd[0] & REQ_IDETAPE_READ) {
2535                 tape->buffer_head++;
2536 #if USE_IOTRACE
2537                 IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
2538 #endif
2539                 tape->postpone_cnt = 0;
2540                 pc = idetape_next_pc_storage(drive);
2541                 idetape_create_read_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2542                 goto out;
2543         }
2544         if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
2545                 tape->buffer_head++;
2546 #if USE_IOTRACE
2547                 IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
2548 #endif
2549                 tape->postpone_cnt = 0;
2550                 pc = idetape_next_pc_storage(drive);
2551                 idetape_create_write_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2552                 goto out;
2553         }
2554         if (rq->cmd[0] & REQ_IDETAPE_READ_BUFFER) {
2555                 tape->postpone_cnt = 0;
2556                 pc = idetape_next_pc_storage(drive);
2557                 idetape_create_read_buffer_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2558                 goto out;
2559         }
2560         if (rq->cmd[0] & REQ_IDETAPE_PC1) {
2561                 pc = (idetape_pc_t *) rq->buffer;
2562                 rq->cmd[0] &= ~(REQ_IDETAPE_PC1);
2563                 rq->cmd[0] |= REQ_IDETAPE_PC2;
2564                 goto out;
2565         }
2566         if (rq->cmd[0] & REQ_IDETAPE_PC2) {
2567                 idetape_media_access_finished(drive);
2568                 return ide_stopped;
2569         }
2570         BUG();
2571 out:
2572         return idetape_issue_packet_command(drive, pc);
2573 }
2574
2575 /*
2576  *      Pipeline related functions
2577  */
2578 static inline int idetape_pipeline_active (idetape_tape_t *tape)
2579 {
2580         int rc1, rc2;
2581
2582         rc1 = test_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
2583         rc2 = (tape->active_data_request != NULL);
2584         return rc1;
2585 }
2586
2587 /*
2588  *      idetape_kmalloc_stage uses __get_free_page to allocate a pipeline
2589  *      stage, along with all the necessary small buffers which together make
2590  *      a buffer of size tape->stage_size (or a bit more). We attempt to
2591  *      combine sequential pages as much as possible.
2592  *
2593  *      Returns a pointer to the new allocated stage, or NULL if we
2594  *      can't (or don't want to) allocate a stage.
2595  *
2596  *      Pipeline stages are optional and are used to increase performance.
2597  *      If we can't allocate them, we'll manage without them.
2598  */
2599 static idetape_stage_t *__idetape_kmalloc_stage (idetape_tape_t *tape, int full, int clear)
2600 {
2601         idetape_stage_t *stage;
2602         struct idetape_bh *prev_bh, *bh;
2603         int pages = tape->pages_per_stage;
2604         char *b_data = NULL;
2605
2606         if ((stage = (idetape_stage_t *) kmalloc (sizeof (idetape_stage_t),GFP_KERNEL)) == NULL)
2607                 return NULL;
2608         stage->next = NULL;
2609
2610         bh = stage->bh = (struct idetape_bh *)kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
2611         if (bh == NULL)
2612                 goto abort;
2613         bh->b_reqnext = NULL;
2614         if ((bh->b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2615                 goto abort;
2616         if (clear)
2617                 memset(bh->b_data, 0, PAGE_SIZE);
2618         bh->b_size = PAGE_SIZE;
2619         atomic_set(&bh->b_count, full ? bh->b_size : 0);
2620
2621         while (--pages) {
2622                 if ((b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2623                         goto abort;
2624                 if (clear)
2625                         memset(b_data, 0, PAGE_SIZE);
2626                 if (bh->b_data == b_data + PAGE_SIZE) {
2627                         bh->b_size += PAGE_SIZE;
2628                         bh->b_data -= PAGE_SIZE;
2629                         if (full)
2630                                 atomic_add(PAGE_SIZE, &bh->b_count);
2631                         continue;
2632                 }
2633                 if (b_data == bh->b_data + bh->b_size) {
2634                         bh->b_size += PAGE_SIZE;
2635                         if (full)
2636                                 atomic_add(PAGE_SIZE, &bh->b_count);
2637                         continue;
2638                 }
2639                 prev_bh = bh;
2640                 if ((bh = (struct idetape_bh *)kmalloc(sizeof(struct idetape_bh), GFP_KERNEL)) == NULL) {
2641                         free_page((unsigned long) b_data);
2642                         goto abort;
2643                 }
2644                 bh->b_reqnext = NULL;
2645                 bh->b_data = b_data;
2646                 bh->b_size = PAGE_SIZE;
2647                 atomic_set(&bh->b_count, full ? bh->b_size : 0);
2648                 prev_bh->b_reqnext = bh;
2649         }
2650         bh->b_size -= tape->excess_bh_size;
2651         if (full)
2652                 atomic_sub(tape->excess_bh_size, &bh->b_count);
2653         return stage;
2654 abort:
2655         __idetape_kfree_stage(stage);
2656         return NULL;
2657 }
2658
2659 static idetape_stage_t *idetape_kmalloc_stage (idetape_tape_t *tape)
2660 {
2661         idetape_stage_t *cache_stage = tape->cache_stage;
2662
2663 #if IDETAPE_DEBUG_LOG
2664         if (tape->debug_level >= 4)
2665                 printk(KERN_INFO "ide-tape: Reached idetape_kmalloc_stage\n");
2666 #endif /* IDETAPE_DEBUG_LOG */
2667
2668         if (tape->nr_stages >= tape->max_stages)
2669                 return NULL;
2670         if (cache_stage != NULL) {
2671                 tape->cache_stage = NULL;
2672                 return cache_stage;
2673         }
2674         return __idetape_kmalloc_stage(tape, 0, 0);
2675 }
2676
2677 static void idetape_copy_stage_from_user (idetape_tape_t *tape, idetape_stage_t *stage, const char *buf, int n)
2678 {
2679         struct idetape_bh *bh = tape->bh;
2680         int count;
2681
2682         while (n) {
2683 #if IDETAPE_DEBUG_BUGS
2684                 if (bh == NULL) {
2685                         printk(KERN_ERR "ide-tape: bh == NULL in "
2686                                 "idetape_copy_stage_from_user\n");
2687                         return;
2688                 }
2689 #endif /* IDETAPE_DEBUG_BUGS */
2690                 count = min((unsigned int)(bh->b_size - atomic_read(&bh->b_count)), (unsigned int)n);
2691                 copy_from_user(bh->b_data + atomic_read(&bh->b_count), buf, count);
2692                 n -= count;
2693                 atomic_add(count, &bh->b_count);
2694                 buf += count;
2695                 if (atomic_read(&bh->b_count) == bh->b_size) {
2696                         bh = bh->b_reqnext;
2697                         if (bh)
2698                                 atomic_set(&bh->b_count, 0);
2699                 }
2700         }
2701         tape->bh = bh;
2702 }
2703
2704 static void idetape_copy_stage_to_user (idetape_tape_t *tape, char *buf, idetape_stage_t *stage, int n)
2705 {
2706         struct idetape_bh *bh = tape->bh;
2707         int count;
2708
2709         while (n) {
2710 #if IDETAPE_DEBUG_BUGS
2711                 if (bh == NULL) {
2712                         printk(KERN_ERR "ide-tape: bh == NULL in "
2713                                 "idetape_copy_stage_to_user\n");
2714                         return;
2715                 }
2716 #endif /* IDETAPE_DEBUG_BUGS */
2717                 count = min(tape->b_count, n);
2718                 copy_to_user(buf, tape->b_data, count);
2719                 n -= count;
2720                 tape->b_data += count;
2721                 tape->b_count -= count;
2722                 buf += count;
2723                 if (!tape->b_count) {
2724                         tape->bh = bh = bh->b_reqnext;
2725                         if (bh) {
2726                                 tape->b_data = bh->b_data;
2727                                 tape->b_count = atomic_read(&bh->b_count);
2728                         }
2729                 }
2730         }
2731 }
2732
2733 static void idetape_init_merge_stage (idetape_tape_t *tape)
2734 {
2735         struct idetape_bh *bh = tape->merge_stage->bh;
2736         
2737         tape->bh = bh;
2738         if (tape->chrdev_direction == idetape_direction_write)
2739                 atomic_set(&bh->b_count, 0);
2740         else {
2741                 tape->b_data = bh->b_data;
2742                 tape->b_count = atomic_read(&bh->b_count);
2743         }
2744 }
2745
2746 static void idetape_switch_buffers (idetape_tape_t *tape, idetape_stage_t *stage)
2747 {
2748         struct idetape_bh *tmp;
2749
2750         tmp = stage->bh;
2751         stage->bh = tape->merge_stage->bh;
2752         tape->merge_stage->bh = tmp;
2753         idetape_init_merge_stage(tape);
2754 }
2755
2756 /*
2757  *      idetape_add_stage_tail adds a new stage at the end of the pipeline.
2758  */
2759 static void idetape_add_stage_tail (ide_drive_t *drive,idetape_stage_t *stage)
2760 {
2761         idetape_tape_t *tape = drive->driver_data;
2762         unsigned long flags;
2763         
2764 #if IDETAPE_DEBUG_LOG
2765         if (tape->debug_level >= 4)
2766                 printk (KERN_INFO "ide-tape: Reached idetape_add_stage_tail\n");
2767 #endif /* IDETAPE_DEBUG_LOG */
2768         spin_lock_irqsave(&tape->spinlock, flags);
2769         stage->next = NULL;
2770         if (tape->last_stage != NULL)
2771                 tape->last_stage->next=stage;
2772         else
2773                 tape->first_stage = tape->next_stage=stage;
2774         tape->last_stage = stage;
2775         if (tape->next_stage == NULL)
2776                 tape->next_stage = tape->last_stage;
2777         tape->nr_stages++;
2778         tape->nr_pending_stages++;
2779         spin_unlock_irqrestore(&tape->spinlock, flags);
2780 }
2781
2782 /*
2783  *      idetape_wait_for_request installs a completion in a pending request
2784  *      and sleeps until it is serviced.
2785  *
2786  *      The caller should ensure that the request will not be serviced
2787  *      before we install the completion (usually by disabling interrupts).
2788  */
2789 static void idetape_wait_for_request (ide_drive_t *drive, struct request *rq)
2790 {
2791         DECLARE_COMPLETION(wait);
2792         idetape_tape_t *tape = drive->driver_data;
2793
2794 #if IDETAPE_DEBUG_BUGS
2795         if (rq == NULL || (rq->flags & REQ_SPECIAL) == 0) {
2796                 printk (KERN_ERR "ide-tape: bug: Trying to sleep on non-valid request\n");
2797                 return;
2798         }
2799 #endif /* IDETAPE_DEBUG_BUGS */
2800         rq->waiting = &wait;
2801         spin_unlock_irq(&tape->spinlock);
2802         wait_for_completion(&wait);
2803         /* The stage and its struct request have been deallocated */
2804         spin_lock_irq(&tape->spinlock);
2805 }
2806
2807 static ide_startstop_t idetape_read_position_callback (ide_drive_t *drive)
2808 {
2809         idetape_tape_t *tape = drive->driver_data;
2810         idetape_read_position_result_t *result;
2811         
2812 #if IDETAPE_DEBUG_LOG
2813         if (tape->debug_level >= 4)
2814                 printk(KERN_INFO "ide-tape: Reached idetape_read_position_callback\n");
2815 #endif /* IDETAPE_DEBUG_LOG */
2816
2817         if (!tape->pc->error) {
2818                 result = (idetape_read_position_result_t *) tape->pc->buffer;
2819 #if IDETAPE_DEBUG_LOG
2820                 if (tape->debug_level >= 2)
2821                         printk(KERN_INFO "ide-tape: BOP - %s\n",result->bop ? "Yes":"No");
2822                 if (tape->debug_level >= 2)
2823                         printk(KERN_INFO "ide-tape: EOP - %s\n",result->eop ? "Yes":"No");
2824 #endif /* IDETAPE_DEBUG_LOG */
2825                 if (result->bpu) {
2826                         printk(KERN_INFO "ide-tape: Block location is unknown to the tape\n");
2827                         clear_bit(IDETAPE_ADDRESS_VALID, &tape->flags);
2828                         idetape_end_request(drive, 0, 0);
2829                 } else {
2830 #if IDETAPE_DEBUG_LOG
2831                         if (tape->debug_level >= 2)
2832                                 printk(KERN_INFO "ide-tape: Block Location - %u\n", ntohl(result->first_block));
2833 #endif /* IDETAPE_DEBUG_LOG */
2834                         tape->partition = result->partition;
2835                         tape->first_frame_position = ntohl(result->first_block);
2836                         tape->last_frame_position = ntohl(result->last_block);
2837                         tape->blocks_in_buffer = result->blocks_in_buffer[2];
2838                         set_bit(IDETAPE_ADDRESS_VALID, &tape->flags);
2839                         idetape_end_request(drive, 1, 0);
2840                 }
2841         } else {
2842                 idetape_end_request(drive, 0, 0);
2843         }
2844         return ide_stopped;
2845 }
2846
2847 /*
2848  *      idetape_create_write_filemark_cmd will:
2849  *
2850  *              1.      Write a filemark if write_filemark=1.
2851  *              2.      Flush the device buffers without writing a filemark
2852  *                      if write_filemark=0.
2853  *
2854  */
2855 static void idetape_create_write_filemark_cmd (ide_drive_t *drive, idetape_pc_t *pc,int write_filemark)
2856 {
2857         idetape_init_pc(pc);
2858         pc->c[0] = IDETAPE_WRITE_FILEMARK_CMD;
2859         pc->c[4] = write_filemark;
2860         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2861         pc->callback = &idetape_pc_callback;
2862 }
2863
2864 static void idetape_create_test_unit_ready_cmd(idetape_pc_t *pc)
2865 {
2866         idetape_init_pc(pc);
2867         pc->c[0] = IDETAPE_TEST_UNIT_READY_CMD;
2868         pc->callback = &idetape_pc_callback;
2869 }
2870
2871 /*
2872  *      idetape_queue_pc_tail is based on the following functions:
2873  *
2874  *      ide_do_drive_cmd from ide.c
2875  *      cdrom_queue_request and cdrom_queue_packet_command from ide-cd.c
2876  *
2877  *      We add a special packet command request to the tail of the request
2878  *      queue, and wait for it to be serviced.
2879  *
2880  *      This is not to be called from within the request handling part
2881  *      of the driver ! We allocate here data in the stack, and it is valid
2882  *      until the request is finished. This is not the case for the bottom
2883  *      part of the driver, where we are always leaving the functions to wait
2884  *      for an interrupt or a timer event.
2885  *
2886  *      From the bottom part of the driver, we should allocate safe memory
2887  *      using idetape_next_pc_storage and idetape_next_rq_storage, and add
2888  *      the request to the request list without waiting for it to be serviced !
2889  *      In that case, we usually use idetape_queue_pc_head.
2890  */
2891 static int __idetape_queue_pc_tail (ide_drive_t *drive, idetape_pc_t *pc)
2892 {
2893         struct request rq;
2894
2895         idetape_init_rq(&rq, REQ_IDETAPE_PC1);
2896         rq.buffer = (char *) pc;
2897         return ide_do_drive_cmd(drive, &rq, ide_wait);
2898 }
2899
2900 static void idetape_create_load_unload_cmd (ide_drive_t *drive, idetape_pc_t *pc,int cmd)
2901 {
2902         idetape_init_pc(pc);
2903         pc->c[0] = IDETAPE_LOAD_UNLOAD_CMD;
2904         pc->c[4] = cmd;
2905         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2906         pc->callback = &idetape_pc_callback;
2907 }
2908
2909 static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
2910 {
2911         idetape_tape_t *tape = drive->driver_data;
2912         idetape_pc_t pc;
2913         int load_attempted = 0;
2914
2915         /*
2916          * Wait for the tape to become ready
2917          */
2918         set_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags);
2919         timeout += jiffies;
2920         while (time_before(jiffies, timeout)) {
2921                 idetape_create_test_unit_ready_cmd(&pc);
2922                 if (!__idetape_queue_pc_tail(drive, &pc))
2923                         return 0;
2924                 if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
2925                     || (tape->asc == 0x3A)) {   /* no media */
2926                         if (load_attempted)
2927                                 return -ENOMEDIUM;
2928                         idetape_create_load_unload_cmd(drive, &pc, IDETAPE_LU_LOAD_MASK);
2929                         __idetape_queue_pc_tail(drive, &pc);
2930                         load_attempted = 1;
2931                 /* not about to be ready */
2932                 } else if (!(tape->sense_key == 2 && tape->asc == 4 &&
2933                              (tape->ascq == 1 || tape->ascq == 8)))
2934                         return -EIO;
2935                 current->state = TASK_INTERRUPTIBLE;
2936                 schedule_timeout(HZ / 10);
2937         }
2938         return -EIO;
2939 }
2940
2941 static int idetape_queue_pc_tail (ide_drive_t *drive,idetape_pc_t *pc)
2942 {
2943         return __idetape_queue_pc_tail(drive, pc);
2944 }
2945
2946 static int idetape_flush_tape_buffers (ide_drive_t *drive)
2947 {
2948         idetape_pc_t pc;
2949         int rc;
2950
2951         idetape_create_write_filemark_cmd(drive, &pc, 0);
2952         if ((rc = idetape_queue_pc_tail(drive, &pc)))
2953                 return rc;
2954         idetape_wait_ready(drive, 60 * 5 * HZ);
2955         return 0;
2956 }
2957
2958 static void idetape_create_read_position_cmd (idetape_pc_t *pc)
2959 {
2960         idetape_init_pc(pc);
2961         pc->c[0] = IDETAPE_READ_POSITION_CMD;
2962         pc->request_transfer = 20;
2963         pc->callback = &idetape_read_position_callback;
2964 }
2965
2966 static int idetape_read_position (ide_drive_t *drive)
2967 {
2968         idetape_tape_t *tape = drive->driver_data;
2969         idetape_pc_t pc;
2970         int position;
2971
2972 #if IDETAPE_DEBUG_LOG
2973         if (tape->debug_level >= 4)
2974                 printk(KERN_INFO "ide-tape: Reached idetape_read_position\n");
2975 #endif /* IDETAPE_DEBUG_LOG */
2976
2977         idetape_create_read_position_cmd(&pc);
2978         if (idetape_queue_pc_tail(drive, &pc))
2979                 return -1;
2980         position = tape->first_frame_position;
2981         return position;
2982 }
2983
2984 static void idetape_create_locate_cmd (ide_drive_t *drive, idetape_pc_t *pc, unsigned int block, u8 partition, int skip)
2985 {
2986         idetape_init_pc(pc);
2987         pc->c[0] = IDETAPE_LOCATE_CMD;
2988         pc->c[1] = 2;
2989         put_unaligned(htonl(block), (unsigned int *) &pc->c[3]);
2990         pc->c[8] = partition;
2991         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2992         pc->callback = &idetape_pc_callback;
2993 }
2994
2995 static int idetape_create_prevent_cmd (ide_drive_t *drive, idetape_pc_t *pc, int prevent)
2996 {
2997         idetape_tape_t *tape = drive->driver_data;
2998
2999         if (!tape->capabilities.lock)
3000                 return 0;
3001
3002         idetape_init_pc(pc);
3003         pc->c[0] = IDETAPE_PREVENT_CMD;
3004         pc->c[4] = prevent;
3005         pc->callback = &idetape_pc_callback;
3006         return 1;
3007 }
3008
3009 static int __idetape_discard_read_pipeline (ide_drive_t *drive)
3010 {
3011         idetape_tape_t *tape = drive->driver_data;
3012         unsigned long flags;
3013         int cnt;
3014
3015         if (tape->chrdev_direction != idetape_direction_read)
3016                 return 0;
3017
3018         /* Remove merge stage. */
3019         cnt = tape->merge_stage_size / tape->tape_block_size;
3020         if (test_and_clear_bit(IDETAPE_FILEMARK, &tape->flags))
3021                 ++cnt;          /* Filemarks count as 1 sector */
3022         tape->merge_stage_size = 0;
3023         if (tape->merge_stage != NULL) {
3024                 __idetape_kfree_stage(tape->merge_stage);
3025                 tape->merge_stage = NULL;
3026         }
3027
3028         /* Clear pipeline flags. */
3029         clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
3030         tape->chrdev_direction = idetape_direction_none;
3031
3032         /* Remove pipeline stages. */
3033         if (tape->first_stage == NULL)
3034                 return 0;
3035
3036         spin_lock_irqsave(&tape->spinlock, flags);
3037         tape->next_stage = NULL;
3038         if (idetape_pipeline_active(tape))
3039                 idetape_wait_for_request(drive, tape->active_data_request);
3040         spin_unlock_irqrestore(&tape->spinlock, flags);
3041
3042         while (tape->first_stage != NULL) {
3043                 struct request *rq_ptr = &tape->first_stage->rq;
3044
3045                 cnt += rq_ptr->nr_sectors - rq_ptr->current_nr_sectors; 
3046                 if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
3047                         ++cnt;
3048                 idetape_remove_stage_head(drive);
3049         }
3050         tape->nr_pending_stages = 0;
3051         tape->max_stages = tape->min_pipeline;
3052         return cnt;
3053 }
3054
3055 /*
3056  *      idetape_position_tape positions the tape to the requested block
3057  *      using the LOCATE packet command. A READ POSITION command is then
3058  *      issued to check where we are positioned.
3059  *
3060  *      Like all higher level operations, we queue the commands at the tail
3061  *      of the request queue and wait for their completion.
3062  *      
3063  */
3064 static int idetape_position_tape (ide_drive_t *drive, unsigned int block, u8 partition, int skip)
3065 {
3066         idetape_tape_t *tape = drive->driver_data;
3067         int retval;
3068         idetape_pc_t pc;
3069
3070         if (tape->chrdev_direction == idetape_direction_read)
3071                 __idetape_discard_read_pipeline(drive);
3072         idetape_wait_ready(drive, 60 * 5 * HZ);
3073         idetape_create_locate_cmd(drive, &pc, block, partition, skip);
3074         retval = idetape_queue_pc_tail(drive, &pc);
3075         if (retval)
3076                 return (retval);
3077
3078         idetape_create_read_position_cmd(&pc);
3079         return (idetape_queue_pc_tail(drive, &pc));
3080 }
3081
3082 static void idetape_discard_read_pipeline (ide_drive_t *drive, int restore_position)
3083 {
3084         idetape_tape_t *tape = drive->driver_data;
3085         int cnt;
3086         int seek, position;
3087
3088         cnt = __idetape_discard_read_pipeline(drive);
3089         if (restore_position) {
3090                 position = idetape_read_position(drive);
3091                 seek = position > cnt ? position - cnt : 0;
3092                 if (idetape_position_tape(drive, seek, 0, 0)) {
3093                         printk(KERN_INFO "ide-tape: %s: position_tape failed in discard_pipeline()\n", tape->name);
3094                         return;
3095                 }
3096         }
3097 }
3098
3099 /*
3100  * idetape_queue_rw_tail generates a read/write request for the block
3101  * device interface and wait for it to be serviced.
3102  */
3103 static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int blocks, struct idetape_bh *bh)
3104 {
3105         idetape_tape_t *tape = drive->driver_data;
3106         struct request rq;
3107
3108 #if IDETAPE_DEBUG_LOG
3109         if (tape->debug_level >= 2)
3110                 printk(KERN_INFO "ide-tape: idetape_queue_rw_tail: cmd=%d\n",cmd);
3111 #endif /* IDETAPE_DEBUG_LOG */
3112 #if IDETAPE_DEBUG_BUGS
3113         if (idetape_pipeline_active(tape)) {
3114                 printk(KERN_ERR "ide-tape: bug: the pipeline is active in idetape_queue_rw_tail\n");
3115                 return (0);
3116         }
3117 #endif /* IDETAPE_DEBUG_BUGS */ 
3118
3119         idetape_init_rq(&rq, cmd);
3120         rq.special = (void *)bh;
3121         rq.sector = tape->first_frame_position;
3122         rq.nr_sectors = rq.current_nr_sectors = blocks;
3123         (void) ide_do_drive_cmd(drive, &rq, ide_wait);
3124
3125         if ((cmd & (REQ_IDETAPE_READ | REQ_IDETAPE_WRITE)) == 0)
3126                 return 0;
3127
3128         if (tape->merge_stage)
3129                 idetape_init_merge_stage(tape);
3130         if (rq.errors == IDETAPE_ERROR_GENERAL)
3131                 return -EIO;
3132         return (tape->tape_block_size * (blocks-rq.current_nr_sectors));
3133 }
3134
3135 /*
3136  *      idetape_insert_pipeline_into_queue is used to start servicing the
3137  *      pipeline stages, starting from tape->next_stage.
3138  */
3139 static void idetape_insert_pipeline_into_queue (ide_drive_t *drive)
3140 {
3141         idetape_tape_t *tape = drive->driver_data;
3142
3143         if (tape->next_stage == NULL)
3144                 return;
3145         if (!idetape_pipeline_active(tape)) {
3146                 set_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
3147                 idetape_active_next_stage(drive);
3148                 (void) ide_do_drive_cmd(drive, tape->active_data_request, ide_end);
3149         }
3150 }
3151
3152 static void idetape_create_inquiry_cmd (idetape_pc_t *pc)
3153 {
3154         idetape_init_pc(pc);
3155         pc->c[0] = IDETAPE_INQUIRY_CMD;
3156         pc->c[4] = pc->request_transfer = 254;
3157         pc->callback = &idetape_pc_callback;
3158 }
3159
3160 static void idetape_create_rewind_cmd (ide_drive_t *drive, idetape_pc_t *pc)
3161 {
3162         idetape_init_pc(pc);
3163         pc->c[0] = IDETAPE_REWIND_CMD;
3164         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
3165         pc->callback = &idetape_pc_callback;
3166 }
3167
3168 #if 0
3169 static void idetape_create_mode_select_cmd (idetape_pc_t *pc, int length)
3170 {
3171         idetape_init_pc(pc);
3172         set_bit(PC_WRITING, &pc->flags);
3173         pc->c[0] = IDETAPE_MODE_SELECT_CMD;
3174         pc->c[1] = 0x10;
3175         put_unaligned(htons(length), (unsigned short *) &pc->c[3]);
3176         pc->request_transfer = 255;
3177         pc->callback = &idetape_pc_callback;
3178 }
3179 #endif
3180
3181 static void idetape_create_erase_cmd (idetape_pc_t *pc)
3182 {
3183         idetape_init_pc(pc);
3184         pc->c[0] = IDETAPE_ERASE_CMD;
3185         pc->c[1] = 1;
3186         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
3187         pc->callback = &idetape_pc_callback;
3188 }
3189
3190 static void idetape_create_space_cmd (idetape_pc_t *pc,int count, u8 cmd)
3191 {
3192         idetape_init_pc(pc);
3193         pc->c[0] = IDETAPE_SPACE_CMD;
3194         put_unaligned(htonl(count), (unsigned int *) &pc->c[1]);
3195         pc->c[1] = cmd;
3196         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
3197         pc->callback = &idetape_pc_callback;
3198 }
3199
3200 static void idetape_wait_first_stage (ide_drive_t *drive)
3201 {
3202         idetape_tape_t *tape = drive->driver_data;
3203         unsigned long flags;
3204
3205         if (tape->first_stage == NULL)
3206                 return;
3207         spin_lock_irqsave(&tape->spinlock, flags);
3208         if (tape->active_stage == tape->first_stage)
3209                 idetape_wait_for_request(drive, tape->active_data_request);
3210         spin_unlock_irqrestore(&tape->spinlock, flags);
3211 }
3212
3213 /*
3214  *      idetape_add_chrdev_write_request tries to add a character device
3215  *      originated write request to our pipeline. In case we don't succeed,
3216  *      we revert to non-pipelined operation mode for this request.
3217  *
3218  *      1.      Try to allocate a new pipeline stage.
3219  *      2.      If we can't, wait for more and more requests to be serviced
3220  *              and try again each time.
3221  *      3.      If we still can't allocate a stage, fallback to
3222  *              non-pipelined operation mode for this request.
3223  */
3224 static int idetape_add_chrdev_write_request (ide_drive_t *drive, int blocks)
3225 {
3226         idetape_tape_t *tape = drive->driver_data;
3227         idetape_stage_t *new_stage;
3228         unsigned long flags;
3229         struct request *rq;
3230
3231 #if IDETAPE_DEBUG_LOG
3232         if (tape->debug_level >= 3)
3233                 printk(KERN_INFO "ide-tape: Reached idetape_add_chrdev_write_request\n");
3234 #endif /* IDETAPE_DEBUG_LOG */
3235
3236         /*
3237          *      Attempt to allocate a new stage.
3238          *      Pay special attention to possible race conditions.
3239          */
3240         while ((new_stage = idetape_kmalloc_stage(tape)) == NULL) {
3241                 spin_lock_irqsave(&tape->spinlock, flags);
3242                 if (idetape_pipeline_active(tape)) {
3243                         idetape_wait_for_request(drive, tape->active_data_request);
3244                         spin_unlock_irqrestore(&tape->spinlock, flags);
3245                 } else {
3246                         spin_unlock_irqrestore(&tape->spinlock, flags);
3247                         idetape_insert_pipeline_into_queue(drive);
3248                         if (idetape_pipeline_active(tape))
3249                                 continue;
3250                         /*
3251                          *      Linux is short on memory. Fallback to
3252                          *      non-pipelined operation mode for this request.
3253                          */
3254                         return idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks, tape->merge_stage->bh);
3255                 }
3256         }
3257         rq = &new_stage->rq;
3258         idetape_init_rq(rq, REQ_IDETAPE_WRITE);
3259         /* Doesn't actually matter - We always assume sequential access */
3260         rq->sector = tape->first_frame_position;
3261         rq->nr_sectors = rq->current_nr_sectors = blocks;
3262
3263         idetape_switch_buffers(tape, new_stage);
3264         idetape_add_stage_tail(drive, new_stage);
3265         tape->pipeline_head++;
3266 #if USE_IOTRACE
3267         IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
3268 #endif
3269         calculate_speeds(drive);
3270
3271         /*
3272          *      Estimate whether the tape has stopped writing by checking
3273          *      if our write pipeline is currently empty. If we are not
3274          *      writing anymore, wait for the pipeline to be full enough
3275          *      (90%) before starting to service requests, so that we will
3276          *      be able to keep up with the higher speeds of the tape.
3277          */
3278         if (!idetape_pipeline_active(tape)) {
3279                 if (tape->nr_stages >= tape->max_stages * 9 / 10 ||
3280                     tape->nr_stages >= tape->max_stages - tape->uncontrolled_pipeline_head_speed * 3 * 1024 / tape->tape_block_size) {
3281                         tape->measure_insert_time = 1;
3282                         tape->insert_time = jiffies;
3283                         tape->insert_size = 0;
3284                         tape->insert_speed = 0;
3285                         idetape_insert_pipeline_into_queue(drive);
3286                 }
3287         }
3288         if (test_and_clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags))
3289                 /* Return a deferred error */
3290                 return -EIO;
3291         return blocks;
3292 }
3293
3294 /*
3295  *      idetape_wait_for_pipeline will wait until all pending pipeline
3296  *      requests are serviced. Typically called on device close.
3297  */
3298 static void idetape_wait_for_pipeline (ide_drive_t *drive)
3299 {
3300         idetape_tape_t *tape = drive->driver_data;
3301         unsigned long flags;
3302
3303         while (tape->next_stage || idetape_pipeline_active(tape)) {
3304                 idetape_insert_pipeline_into_queue(drive);
3305                 spin_lock_irqsave(&tape->spinlock, flags);
3306                 if (idetape_pipeline_active(tape))
3307                         idetape_wait_for_request(drive, tape->active_data_request);
3308                 spin_unlock_irqrestore(&tape->spinlock, flags);
3309         }
3310 }
3311
3312 static void idetape_empty_write_pipeline (ide_drive_t *drive)
3313 {
3314         idetape_tape_t *tape = drive->driver_data;
3315         int blocks, min;
3316         struct idetape_bh *bh;
3317         
3318 #if IDETAPE_DEBUG_BUGS
3319         if (tape->chrdev_direction != idetape_direction_write) {
3320                 printk(KERN_ERR "ide-tape: bug: Trying to empty write pipeline, but we are not writing.\n");
3321                 return;
3322         }
3323         if (tape->merge_stage_size > tape->stage_size) {
3324                 printk(KERN_ERR "ide-tape: bug: merge_buffer too big\n");
3325                 tape->merge_stage_size = tape->stage_size;
3326         }
3327 #endif /* IDETAPE_DEBUG_BUGS */
3328         if (tape->merge_stage_size) {
3329                 blocks = tape->merge_stage_size / tape->tape_block_size;
3330                 if (tape->merge_stage_size % tape->tape_block_size) {
3331                         unsigned int i;
3332
3333                         blocks++;
3334                         i = tape->tape_block_size - tape->merge_stage_size % tape->tape_block_size;
3335                         bh = tape->bh->b_reqnext;
3336                         while (bh) {
3337                                 atomic_set(&bh->b_count, 0);
3338                                 bh = bh->b_reqnext;
3339                         }
3340                         bh = tape->bh;
3341                         while (i) {
3342                                 if (bh == NULL) {
3343
3344                                         printk(KERN_INFO "ide-tape: bug, bh NULL\n");
3345                                         break;
3346                                 }
3347                                 min = min(i, (unsigned int)(bh->b_size - atomic_read(&bh->b_count)));
3348                                 memset(bh->b_data + atomic_read(&bh->b_count), 0, min);
3349                                 atomic_add(min, &bh->b_count);
3350                                 i -= min;
3351                                 bh = bh->b_reqnext;
3352                         }
3353                 }
3354                 (void) idetape_add_chrdev_write_request(drive, blocks);
3355                 tape->merge_stage_size = 0;
3356         }
3357         idetape_wait_for_pipeline(drive);
3358         if (tape->merge_stage != NULL) {
3359                 __idetape_kfree_stage(tape->merge_stage);
3360                 tape->merge_stage = NULL;
3361         }
3362         clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
3363         tape->chrdev_direction = idetape_direction_none;
3364
3365         /*
3366          *      On the next backup, perform the feedback loop again.
3367          *      (I don't want to keep sense information between backups,
3368          *       as some systems are constantly on, and the system load
3369          *       can be totally different on the next backup).
3370          */
3371         tape->max_stages = tape->min_pipeline;
3372 #if IDETAPE_DEBUG_BUGS
3373         if (tape->first_stage != NULL ||
3374             tape->next_stage != NULL ||
3375             tape->last_stage != NULL ||
3376             tape->nr_stages != 0) {
3377                 printk(KERN_ERR "ide-tape: ide-tape pipeline bug, "
3378                         "first_stage %p, next_stage %p, "
3379                         "last_stage %p, nr_stages %d\n",
3380                         tape->first_stage, tape->next_stage,
3381                         tape->last_stage, tape->nr_stages);
3382         }
3383 #endif /* IDETAPE_DEBUG_BUGS */
3384 }
3385
3386 static void idetape_restart_speed_control (ide_drive_t *drive)
3387 {
3388         idetape_tape_t *tape = drive->driver_data;
3389
3390         tape->restart_speed_control_req = 0;
3391         tape->pipeline_head = 0;
3392         tape->controlled_last_pipeline_head = tape->uncontrolled_last_pipeline_head = 0;
3393         tape->controlled_previous_pipeline_head = tape->uncontrolled_previous_pipeline_head = 0;
3394         tape->pipeline_head_speed = tape->controlled_pipeline_head_speed = 5000;
3395         tape->uncontrolled_pipeline_head_speed = 0;
3396         tape->controlled_pipeline_head_time = tape->uncontrolled_pipeline_head_time = jiffies;
3397         tape->controlled_previous_head_time = tape->uncontrolled_previous_head_time = jiffies;
3398 }
3399
3400 static int idetape_initiate_read (ide_drive_t *drive, int max_stages)
3401 {
3402         idetape_tape_t *tape = drive->driver_data;
3403         idetape_stage_t *new_stage;
3404         struct request rq;
3405         int bytes_read;
3406         int blocks = tape->capabilities.ctl;
3407
3408         /* Initialize read operation */
3409         if (tape->chrdev_direction != idetape_direction_read) {
3410                 if (tape->chrdev_direction == idetape_direction_write) {
3411                         idetape_empty_write_pipeline(drive);
3412                         idetape_flush_tape_buffers(drive);
3413                 }
3414 #if IDETAPE_DEBUG_BUGS
3415                 if (tape->merge_stage || tape->merge_stage_size) {
3416                         printk (KERN_ERR "ide-tape: merge_stage_size should be 0 now\n");
3417                         tape->merge_stage_size = 0;
3418                 }
3419 #endif /* IDETAPE_DEBUG_BUGS */
3420                 if ((tape->merge_stage = __idetape_kmalloc_stage(tape, 0, 0)) == NULL)
3421                         return -ENOMEM;
3422                 tape->chrdev_direction = idetape_direction_read;
3423
3424                 /*
3425                  *      Issue a read 0 command to ensure that DSC handshake
3426                  *      is switched from completion mode to buffer available
3427                  *      mode.
3428                  *      No point in issuing this if DSC overlap isn't supported,
3429                  *      some drives (Seagate STT3401A) will return an error.
3430                  */
3431                 if (drive->dsc_overlap) {
3432                         bytes_read = idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, 0, tape->merge_stage->bh);
3433                         if (bytes_read < 0) {
3434                                 __idetape_kfree_stage(tape->merge_stage);
3435                                 tape->merge_stage = NULL;
3436                                 tape->chrdev_direction = idetape_direction_none;
3437                                 return bytes_read;
3438                         }
3439                 }
3440         }
3441         if (tape->restart_speed_control_req)
3442                 idetape_restart_speed_control(drive);
3443         idetape_init_rq(&rq, REQ_IDETAPE_READ);
3444         rq.sector = tape->first_frame_position;
3445         rq.nr_sectors = rq.current_nr_sectors = blocks;
3446         if (!test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags) &&
3447             tape->nr_stages < max_stages) {
3448                 new_stage = idetape_kmalloc_stage(tape);
3449                 while (new_stage != NULL) {
3450                         new_stage->rq = rq;
3451                         idetape_add_stage_tail(drive, new_stage);
3452                         if (tape->nr_stages >= max_stages)
3453                                 break;
3454                         new_stage = idetape_kmalloc_stage(tape);
3455                 }
3456         }
3457         if (!idetape_pipeline_active(tape)) {
3458                 if (tape->nr_pending_stages >= 3 * max_stages / 4) {
3459                         tape->measure_insert_time = 1;
3460                         tape->insert_time = jiffies;
3461                         tape->insert_size = 0;
3462                         tape->insert_speed = 0;
3463                         idetape_insert_pipeline_into_queue(drive);
3464                 }
3465         }
3466         return 0;
3467 }
3468
3469 /*
3470  *      idetape_add_chrdev_read_request is called from idetape_chrdev_read
3471  *      to service a character device read request and add read-ahead
3472  *      requests to our pipeline.
3473  */
3474 static int idetape_add_chrdev_read_request (ide_drive_t *drive,int blocks)
3475 {
3476         idetape_tape_t *tape = drive->driver_data;
3477         unsigned long flags;
3478         struct request *rq_ptr;
3479         int bytes_read;
3480
3481 #if IDETAPE_DEBUG_LOG
3482         if (tape->debug_level >= 4)
3483                 printk(KERN_INFO "ide-tape: Reached idetape_add_chrdev_read_request, %d blocks\n", blocks);
3484 #endif /* IDETAPE_DEBUG_LOG */
3485
3486         /*
3487          * If we are at a filemark, return a read length of 0
3488          */
3489         if (test_bit(IDETAPE_FILEMARK, &tape->flags))
3490                 return 0;
3491
3492         /*
3493          * Wait for the next block to be available at the head
3494          * of the pipeline
3495          */
3496         idetape_initiate_read(drive, tape->max_stages);
3497         if (tape->first_stage == NULL) {
3498                 if (test_bit(IDETAPE_PIPELINE_ERROR, &tape->flags))
3499                         return 0;
3500                 return idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, blocks, tape->merge_stage->bh);
3501         }
3502         idetape_wait_first_stage(drive);
3503         rq_ptr = &tape->first_stage->rq;
3504         bytes_read = tape->tape_block_size * (rq_ptr->nr_sectors - rq_ptr->current_nr_sectors);
3505         rq_ptr->nr_sectors = rq_ptr->current_nr_sectors = 0;
3506
3507
3508         if (rq_ptr->errors == IDETAPE_ERROR_EOD)
3509                 return 0;
3510         else {
3511                 idetape_switch_buffers(tape, tape->first_stage);
3512                 if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
3513                         set_bit(IDETAPE_FILEMARK, &tape->flags);
3514                 spin_lock_irqsave(&tape->spinlock, flags);
3515                 idetape_remove_stage_head(drive);
3516                 spin_unlock_irqrestore(&tape->spinlock, flags);
3517                 tape->pipeline_head++;
3518 #if USE_IOTRACE
3519                 IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
3520 #endif
3521                 calculate_speeds(drive);
3522         }
3523 #if IDETAPE_DEBUG_BUGS
3524         if (bytes_read > blocks * tape->tape_block_size) {
3525                 printk(KERN_ERR "ide-tape: bug: trying to return more bytes than requested\n");
3526                 bytes_read = blocks * tape->tape_block_size;
3527         }
3528 #endif /* IDETAPE_DEBUG_BUGS */
3529         return (bytes_read);
3530 }
3531
3532 static void idetape_pad_zeros (ide_drive_t *drive, int bcount)
3533 {
3534         idetape_tape_t *tape = drive->driver_data;
3535         struct idetape_bh *bh;
3536         int blocks;
3537         
3538         while (bcount) {
3539                 unsigned int count;
3540
3541                 bh = tape->merge_stage->bh;
3542                 count = min(tape->stage_size, bcount);
3543                 bcount -= count;
3544                 blocks = count / tape->tape_block_size;
3545                 while (count) {
3546                         atomic_set(&bh->b_count, min(count, (unsigned int)bh->b_size));
3547                         memset(bh->b_data, 0, atomic_read(&bh->b_count));
3548                         count -= atomic_read(&bh->b_count);
3549                         bh = bh->b_reqnext;
3550                 }
3551                 idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks, tape->merge_stage->bh);
3552         }
3553 }
3554
3555 static int idetape_pipeline_size (ide_drive_t *drive)
3556 {
3557         idetape_tape_t *tape = drive->driver_data;
3558         idetape_stage_t *stage;
3559         struct request *rq;
3560         int size = 0;
3561
3562         idetape_wait_for_pipeline(drive);
3563         stage = tape->first_stage;
3564         while (stage != NULL) {
3565                 rq = &stage->rq;
3566                 size += tape->tape_block_size * (rq->nr_sectors-rq->current_nr_sectors);
3567                 if (rq->errors == IDETAPE_ERROR_FILEMARK)
3568                         size += tape->tape_block_size;
3569                 stage = stage->next;
3570         }
3571         size += tape->merge_stage_size;
3572         return size;
3573 }
3574
3575 /*
3576  *      Rewinds the tape to the Beginning Of the current Partition (BOP).
3577  *
3578  *      We currently support only one partition.
3579  */ 
3580 static int idetape_rewind_tape (ide_drive_t *drive)
3581 {
3582         int retval;
3583         idetape_pc_t pc;
3584 #if IDETAPE_DEBUG_LOG
3585         idetape_tape_t *tape = drive->driver_data;
3586         if (tape->debug_level >= 2)
3587                 printk(KERN_INFO "ide-tape: Reached idetape_rewind_tape\n");
3588 #endif /* IDETAPE_DEBUG_LOG */  
3589         
3590         idetape_create_rewind_cmd(drive, &pc);
3591         retval = idetape_queue_pc_tail(drive, &pc);
3592         if (retval)
3593                 return retval;
3594
3595         idetape_create_read_position_cmd(&pc);
3596         retval = idetape_queue_pc_tail(drive, &pc);
3597         if (retval)
3598                 return retval;
3599         return 0;
3600 }
3601
3602 /*
3603  *      Our special ide-tape ioctl's.
3604  *
3605  *      Currently there aren't any ioctl's.
3606  *      mtio.h compatible commands should be issued to the character device
3607  *      interface.
3608  */
3609 static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd, unsigned long arg)
3610 {
3611         idetape_tape_t *tape = drive->driver_data;
3612         idetape_config_t config;
3613
3614 #if IDETAPE_DEBUG_LOG   
3615         if (tape->debug_level >= 4)
3616                 printk(KERN_INFO "ide-tape: Reached idetape_blkdev_ioctl\n");
3617 #endif /* IDETAPE_DEBUG_LOG */
3618         switch (cmd) {
3619                 case 0x0340:
3620                         if (copy_from_user ((char *) &config, (char *) arg, sizeof (idetape_config_t)))
3621                                 return -EFAULT;
3622                         tape->best_dsc_rw_frequency = config.dsc_rw_frequency;
3623                         tape->max_stages = config.nr_stages;
3624                         break;
3625                 case 0x0350:
3626                         config.dsc_rw_frequency = (int) tape->best_dsc_rw_frequency;
3627                         config.nr_stages = tape->max_stages; 
3628                         if (copy_to_user((char *) arg, (char *) &config, sizeof (idetape_config_t)))
3629                                 return -EFAULT;
3630                         break;
3631                 default:
3632                         return -EIO;
3633         }
3634         return 0;
3635 }
3636
3637 /*
3638  *      idetape_pre_reset is called before an ATAPI/ATA software reset.
3639  */
3640 static void idetape_pre_reset (ide_drive_t *drive)
3641 {
3642         idetape_tape_t *tape = drive->driver_data;
3643         if (tape != NULL)
3644                 set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
3645 }
3646
3647 /*
3648  *      idetape_space_over_filemarks is now a bit more complicated than just
3649  *      passing the command to the tape since we may have crossed some
3650  *      filemarks during our pipelined read-ahead mode.
3651  *
3652  *      As a minor side effect, the pipeline enables us to support MTFSFM when
3653  *      the filemark is in our internal pipeline even if the tape doesn't
3654  *      support spacing over filemarks in the reverse direction.
3655  */
3656 static int idetape_space_over_filemarks (ide_drive_t *drive,short mt_op,int mt_count)
3657 {
3658         idetape_tape_t *tape = drive->driver_data;
3659         idetape_pc_t pc;
3660         unsigned long flags;
3661         int retval,count=0;
3662
3663         if (mt_count == 0)
3664                 return 0;
3665         if (MTBSF == mt_op || MTBSFM == mt_op) {
3666                 if (!tape->capabilities.sprev)
3667                         return -EIO;
3668                 mt_count = - mt_count;
3669         }
3670
3671         if (tape->chrdev_direction == idetape_direction_read) {
3672                 /*
3673                  *      We have a read-ahead buffer. Scan it for crossed
3674                  *      filemarks.
3675                  */
3676                 tape->merge_stage_size = 0;
3677                 if (test_and_clear_bit(IDETAPE_FILEMARK, &tape->flags))
3678                         ++count;
3679                 while (tape->first_stage != NULL) {
3680                         if (count == mt_count) {
3681                                 if (mt_op == MTFSFM)
3682                                         set_bit(IDETAPE_FILEMARK, &tape->flags);
3683                                 return 0;
3684                         }
3685                         spin_lock_irqsave(&tape->spinlock, flags);
3686                         if (tape->first_stage == tape->active_stage) {
3687                                 /*
3688                                  *      We have reached the active stage in the read pipeline.
3689                                  *      There is no point in allowing the drive to continue
3690                                  *      reading any farther, so we stop the pipeline.
3691                                  *
3692                                  *      This section should be moved to a separate subroutine,
3693                                  *      because a similar function is performed in
3694                                  *      __idetape_discard_read_pipeline(), for example.
3695                                  */
3696                                 tape->next_stage = NULL;
3697                                 spin_unlock_irqrestore(&tape->spinlock, flags);
3698                                 idetape_wait_first_stage(drive);
3699                                 tape->next_stage = tape->first_stage->next;
3700                         } else
3701                                 spin_unlock_irqrestore(&tape->spinlock, flags);
3702                         if (tape->first_stage->rq.errors == IDETAPE_ERROR_FILEMARK)
3703                                 ++count;
3704                         idetape_remove_stage_head(drive);
3705                 }
3706                 idetape_discard_read_pipeline(drive, 0);
3707         }
3708
3709         /*
3710          *      The filemark was not found in our internal pipeline.
3711          *      Now we can issue the space command.
3712          */
3713         switch (mt_op) {
3714                 case MTFSF:
3715                 case MTBSF:
3716                         idetape_create_space_cmd(&pc,mt_count-count,IDETAPE_SPACE_OVER_FILEMARK);
3717                         return (idetape_queue_pc_tail(drive, &pc));
3718                 case MTFSFM:
3719                 case MTBSFM:
3720                         if (!tape->capabilities.sprev)
3721                                 return (-EIO);
3722                         retval = idetape_space_over_filemarks(drive, MTFSF, mt_count-count);
3723                         if (retval) return (retval);
3724                         count = (MTBSFM == mt_op ? 1 : -1);
3725                         return (idetape_space_over_filemarks(drive, MTFSF, count));
3726                 default:
3727                         printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",mt_op);
3728                         return (-EIO);
3729         }
3730 }
3731
3732
3733 /*
3734  *      Our character device read / write functions.
3735  *
3736  *      The tape is optimized to maximize throughput when it is transferring
3737  *      an integral number of the "continuous transfer limit", which is
3738  *      a parameter of the specific tape (26 KB on my particular tape).
3739  *      (32 kB for Onstream)
3740  *
3741  *      As of version 1.3 of the driver, the character device provides an
3742  *      abstract continuous view of the media - any mix of block sizes (even 1
3743  *      byte) on the same backup/restore procedure is supported. The driver
3744  *      will internally convert the requests to the recommended transfer unit,
3745  *      so that an unmatch between the user's block size to the recommended
3746  *      size will only result in a (slightly) increased driver overhead, but
3747  *      will no longer hit performance.
3748  *      This is not applicable to Onstream.
3749  */
3750 static ssize_t idetape_chrdev_read (struct file *file, char *buf,
3751                                     size_t count, loff_t *ppos)
3752 {
3753         ide_drive_t *drive = file->private_data;
3754         idetape_tape_t *tape = drive->driver_data;
3755         ssize_t bytes_read,temp, actually_read = 0, rc;
3756
3757         if (ppos != &file->f_pos) {
3758                 /* "A request was outside the capabilities of the device." */
3759                 return -ENXIO;
3760         }
3761 #if IDETAPE_DEBUG_LOG
3762         if (tape->debug_level >= 3)
3763                 printk(KERN_INFO "ide-tape: Reached idetape_chrdev_read, count %Zd\n", count);
3764 #endif /* IDETAPE_DEBUG_LOG */
3765
3766         if (tape->chrdev_direction != idetape_direction_read) {
3767                 if (test_bit(IDETAPE_DETECT_BS, &tape->flags))
3768                         if (count > tape->tape_block_size &&
3769                             (count % tape->tape_block_size) == 0)
3770                                 tape->user_bs_factor = count / tape->tape_block_size;
3771         }
3772         if ((rc = idetape_initiate_read(drive, tape->max_stages)) < 0)
3773                 return rc;
3774         if (count == 0)
3775                 return (0);
3776         if (tape->merge_stage_size) {
3777                 actually_read = min((unsigned int)(tape->merge_stage_size), (unsigned int)count);
3778                 idetape_copy_stage_to_user(tape, buf, tape->merge_stage, actually_read);
3779                 buf += actually_read;
3780                 tape->merge_stage_size -= actually_read;
3781                 count -= actually_read;
3782         }
3783         while (count >= tape->stage_size) {
3784                 bytes_read = idetape_add_chrdev_read_request(drive, tape->capabilities.ctl);
3785                 if (bytes_read <= 0)
3786                         goto finish;
3787                 idetape_copy_stage_to_user(tape, buf, tape->merge_stage, bytes_read);
3788                 buf += bytes_read;
3789                 count -= bytes_read;
3790                 actually_read += bytes_read;
3791         }
3792         if (count) {
3793                 bytes_read = idetape_add_chrdev_read_request(drive, tape->capabilities.ctl);
3794                 if (bytes_read <= 0)
3795                         goto finish;
3796                 temp = min((unsigned long)count, (unsigned long)bytes_read);
3797                 idetape_copy_stage_to_user(tape, buf, tape->merge_stage, temp);
3798                 actually_read += temp;
3799                 tape->merge_stage_size = bytes_read-temp;
3800         }
3801 finish:
3802         if (!actually_read && test_bit(IDETAPE_FILEMARK, &tape->flags)) {
3803 #if IDETAPE_DEBUG_LOG
3804                 if (tape->debug_level >= 2)
3805                         printk(KERN_INFO "ide-tape: %s: spacing over filemark\n", tape->name);
3806 #endif
3807                 idetape_space_over_filemarks(drive, MTFSF, 1);
3808                 return 0;
3809         }
3810         return actually_read;
3811 }
3812
3813 static ssize_t idetape_chrdev_write (struct file *file, const char *buf,
3814                                      size_t count, loff_t *ppos)
3815 {
3816         ide_drive_t *drive = file->private_data;
3817         idetape_tape_t *tape = drive->driver_data;
3818         ssize_t retval, actually_written = 0;
3819
3820         if (ppos != &file->f_pos) {
3821                 /* "A request was outside the capabilities of the device." */
3822                 return -ENXIO;
3823         }
3824
3825         /* The drive is write protected. */
3826         if (tape->write_prot)
3827                 return -EACCES;
3828
3829 #if IDETAPE_DEBUG_LOG
3830         if (tape->debug_level >= 3)
3831                 printk(KERN_INFO "ide-tape: Reached idetape_chrdev_write, "
3832                         "count %Zd\n", count);
3833 #endif /* IDETAPE_DEBUG_LOG */
3834
3835         /* Initialize write operation */
3836         if (tape->chrdev_direction != idetape_direction_write) {
3837                 if (tape->chrdev_direction == idetape_direction_read)
3838                         idetape_discard_read_pipeline(drive, 1);
3839 #if IDETAPE_DEBUG_BUGS
3840                 if (tape->merge_stage || tape->merge_stage_size) {
3841                         printk(KERN_ERR "ide-tape: merge_stage_size "
3842                                 "should be 0 now\n");
3843                         tape->merge_stage_size = 0;
3844                 }
3845 #endif /* IDETAPE_DEBUG_BUGS */
3846                 if ((tape->merge_stage = __idetape_kmalloc_stage(tape, 0, 0)) == NULL)
3847                         return -ENOMEM;
3848                 tape->chrdev_direction = idetape_direction_write;
3849                 idetape_init_merge_stage(tape);
3850
3851                 /*
3852                  *      Issue a write 0 command to ensure that DSC handshake
3853                  *      is switched from completion mode to buffer available
3854                  *      mode.
3855                  *      No point in issuing this if DSC overlap isn't supported,
3856                  *      some drives (Seagate STT3401A) will return an error.
3857                  */
3858                 if (drive->dsc_overlap) {
3859                         retval = idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, 0, tape->merge_stage->bh);
3860                         if (retval < 0) {
3861                                 __idetape_kfree_stage(tape->merge_stage);
3862                                 tape->merge_stage = NULL;
3863                                 tape->chrdev_direction = idetape_direction_none;
3864                                 return retval;
3865                         }
3866                 }
3867         }
3868         if (count == 0)
3869                 return (0);
3870         if (tape->restart_speed_control_req)
3871                 idetape_restart_speed_control(drive);
3872         if (tape->merge_stage_size) {
3873 #if IDETAPE_DEBUG_BUGS
3874                 if (tape->merge_stage_size >= tape->stage_size) {
3875                         printk(KERN_ERR "ide-tape: bug: merge buffer too big\n");
3876                         tape->merge_stage_size = 0;
3877                 }
3878 #endif /* IDETAPE_DEBUG_BUGS */
3879                 actually_written = min((unsigned int)(tape->stage_size - tape->merge_stage_size), (unsigned int)count);
3880                 idetape_copy_stage_from_user(tape, tape->merge_stage, buf, actually_written);
3881                 buf += actually_written;
3882                 tape->merge_stage_size += actually_written;
3883                 count -= actually_written;
3884
3885                 if (tape->merge_stage_size == tape->stage_size) {
3886                         tape->merge_stage_size = 0;
3887                         retval = idetape_add_chrdev_write_request(drive, tape->capabilities.ctl);
3888                         if (retval <= 0)
3889                                 return (retval);
3890                 }
3891         }
3892         while (count >= tape->stage_size) {
3893                 idetape_copy_stage_from_user(tape, tape->merge_stage, buf, tape->stage_size);
3894                 buf += tape->stage_size;
3895                 count -= tape->stage_size;
3896                 retval = idetape_add_chrdev_write_request(drive, tape->capabilities.ctl);
3897                 actually_written += tape->stage_size;
3898                 if (retval <= 0)
3899                         return (retval);
3900         }
3901         if (count) {
3902                 actually_written += count;
3903                 idetape_copy_stage_from_user(tape, tape->merge_stage, buf, count);
3904                 tape->merge_stage_size += count;
3905         }
3906         return (actually_written);
3907 }
3908
3909 static int idetape_write_filemark (ide_drive_t *drive)
3910 {
3911         idetape_pc_t pc;
3912
3913         /* Write a filemark */
3914         idetape_create_write_filemark_cmd(drive, &pc, 1);
3915         if (idetape_queue_pc_tail(drive, &pc)) {
3916                 printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
3917                 return -EIO;
3918         }
3919         return 0;
3920 }
3921
3922 /*
3923  *      idetape_mtioctop is called from idetape_chrdev_ioctl when
3924  *      the general mtio MTIOCTOP ioctl is requested.
3925  *
3926  *      We currently support the following mtio.h operations:
3927  *
3928  *      MTFSF   -       Space over mt_count filemarks in the positive direction.
3929  *                      The tape is positioned after the last spaced filemark.
3930  *
3931  *      MTFSFM  -       Same as MTFSF, but the tape is positioned before the
3932  *                      last filemark.
3933  *
3934  *      MTBSF   -       Steps background over mt_count filemarks, tape is
3935  *                      positioned before the last filemark.
3936  *
3937  *      MTBSFM  -       Like MTBSF, only tape is positioned after the last filemark.
3938  *
3939  *      Note:
3940  *
3941  *              MTBSF and MTBSFM are not supported when the tape doesn't
3942  *              support spacing over filemarks in the reverse direction.
3943  *              In this case, MTFSFM is also usually not supported (it is
3944  *              supported in the rare case in which we crossed the filemark
3945  *              during our read-ahead pipelined operation mode).
3946  *              
3947  *      MTWEOF  -       Writes mt_count filemarks. Tape is positioned after
3948  *                      the last written filemark.
3949  *
3950  *      MTREW   -       Rewinds tape.
3951  *
3952  *      MTLOAD  -       Loads the tape.
3953  *
3954  *      MTOFFL  -       Puts the tape drive "Offline": Rewinds the tape and
3955  *      MTUNLOAD        prevents further access until the media is replaced.
3956  *
3957  *      MTNOP   -       Flushes tape buffers.
3958  *
3959  *      MTRETEN -       Retension media. This typically consists of one end
3960  *                      to end pass on the media.
3961  *
3962  *      MTEOM   -       Moves to the end of recorded data.
3963  *
3964  *      MTERASE -       Erases tape.
3965  *
3966  *      MTSETBLK -      Sets the user block size to mt_count bytes. If
3967  *                      mt_count is 0, we will attempt to autodetect
3968  *                      the block size.
3969  *
3970  *      MTSEEK  -       Positions the tape in a specific block number, where
3971  *                      each block is assumed to contain which user_block_size
3972  *                      bytes.
3973  *
3974  *      MTSETPART -     Switches to another tape partition.
3975  *
3976  *      MTLOCK -        Locks the tape door.
3977  *
3978  *      MTUNLOCK -      Unlocks the tape door.
3979  *
3980  *      The following commands are currently not supported:
3981  *
3982  *      MTFSS, MTBSS, MTWSM, MTSETDENSITY,
3983  *      MTSETDRVBUFFER, MT_ST_BOOLEANS, MT_ST_WRITE_THRESHOLD.
3984  */
3985 static int idetape_mtioctop (ide_drive_t *drive,short mt_op,int mt_count)
3986 {
3987         idetape_tape_t *tape = drive->driver_data;
3988         idetape_pc_t pc;
3989         int i,retval;
3990
3991 #if IDETAPE_DEBUG_LOG
3992         if (tape->debug_level >= 1)
3993                 printk(KERN_INFO "ide-tape: Handling MTIOCTOP ioctl: "
3994                         "mt_op=%d, mt_count=%d\n", mt_op, mt_count);
3995 #endif /* IDETAPE_DEBUG_LOG */
3996         /*
3997          *      Commands which need our pipelined read-ahead stages.
3998          */
3999         switch (mt_op) {
4000                 case MTFSF:
4001                 case MTFSFM:
4002                 case MTBSF:
4003                 case MTBSFM:
4004                         if (!mt_count)
4005                                 return (0);
4006                         return (idetape_space_over_filemarks(drive,mt_op,mt_count));
4007                 default:
4008                         break;
4009         }
4010         switch (mt_op) {
4011                 case MTWEOF:
4012                         if (tape->write_prot)
4013                                 return -EACCES;
4014                         idetape_discard_read_pipeline(drive, 1);
4015                         for (i = 0; i < mt_count; i++) {
4016                                 retval = idetape_write_filemark(drive);
4017                                 if (retval)
4018                                         return retval;
4019                         }
4020                         return (0);
4021                 case MTREW:
4022                         idetape_discard_read_pipeline(drive, 0);
4023                         if (idetape_rewind_tape(drive))
4024                                 return -EIO;
4025                         return 0;
4026                 case MTLOAD:
4027                         idetape_discard_read_pipeline(drive, 0);
4028                         idetape_create_load_unload_cmd(drive, &pc, IDETAPE_LU_LOAD_MASK);
4029                         return (idetape_queue_pc_tail(drive, &pc));
4030                 case MTUNLOAD:
4031                 case MTOFFL:
4032                         /*
4033                          * If door is locked, attempt to unlock before
4034                          * attempting to eject.
4035                          */
4036                         if (tape->door_locked) {
4037                                 if (idetape_create_prevent_cmd(drive, &pc, 0))
4038                                         if (!idetape_queue_pc_tail(drive, &pc))
4039                                                 tape->door_locked = DOOR_UNLOCKED;
4040                         }
4041                         idetape_discard_read_pipeline(drive, 0);
4042                         idetape_create_load_unload_cmd(drive, &pc,!IDETAPE_LU_LOAD_MASK);
4043                         retval = idetape_queue_pc_tail(drive, &pc);
4044                         if (!retval)
4045                                 clear_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags);
4046                         return retval;
4047                 case MTNOP:
4048                         idetape_discard_read_pipeline(drive, 0);
4049                         return (idetape_flush_tape_buffers(drive));
4050                 case MTRETEN:
4051                         idetape_discard_read_pipeline(drive, 0);
4052                         idetape_create_load_unload_cmd(drive, &pc,IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
4053                         return (idetape_queue_pc_tail(drive, &pc));
4054                 case MTEOM:
4055                         idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
4056                         return (idetape_queue_pc_tail(drive, &pc));
4057                 case MTERASE:
4058                         (void) idetape_rewind_tape(drive);
4059                         idetape_create_erase_cmd(&pc);
4060                         return (idetape_queue_pc_tail(drive, &pc));
4061                 case MTSETBLK:
4062                         if (mt_count) {
4063                                 if (mt_count < tape->tape_block_size || mt_count % tape->tape_block_size)
4064                                         return -EIO;
4065                                 tape->user_bs_factor = mt_count / tape->tape_block_size;
4066                                 clear_bit(IDETAPE_DETECT_BS, &tape->flags);
4067                         } else
4068                                 set_bit(IDETAPE_DETECT_BS, &tape->flags);
4069                         return 0;
4070                 case MTSEEK:
4071                         idetape_discard_read_pipeline(drive, 0);
4072                         return idetape_position_tape(drive, mt_count * tape->user_bs_factor, tape->partition, 0);
4073                 case MTSETPART:
4074                         idetape_discard_read_pipeline(drive, 0);
4075                         return (idetape_position_tape(drive, 0, mt_count, 0));
4076                 case MTFSR:
4077                 case MTBSR:
4078                 case MTLOCK:
4079                         if (!idetape_create_prevent_cmd(drive, &pc, 1))
4080                                 return 0;
4081                         retval = idetape_queue_pc_tail(drive, &pc);
4082                         if (retval) return retval;
4083                         tape->door_locked = DOOR_EXPLICITLY_LOCKED;
4084                         return 0;
4085                 case MTUNLOCK:
4086                         if (!idetape_create_prevent_cmd(drive, &pc, 0))
4087                                 return 0;
4088                         retval = idetape_queue_pc_tail(drive, &pc);
4089                         if (retval) return retval;
4090                         tape->door_locked = DOOR_UNLOCKED;
4091                         return 0;
4092                 default:
4093                         printk(KERN_ERR "ide-tape: MTIO operation %d not "
4094                                 "supported\n", mt_op);
4095                         return (-EIO);
4096         }
4097 }
4098
4099 /*
4100  *      Our character device ioctls.
4101  *
4102  *      General mtio.h magnetic io commands are supported here, and not in
4103  *      the corresponding block interface.
4104  *
4105  *      The following ioctls are supported:
4106  *
4107  *      MTIOCTOP -      Refer to idetape_mtioctop for detailed description.
4108  *
4109  *      MTIOCGET -      The mt_dsreg field in the returned mtget structure
4110  *                      will be set to (user block size in bytes <<
4111  *                      MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK.
4112  *
4113  *                      The mt_blkno is set to the current user block number.
4114  *                      The other mtget fields are not supported.
4115  *
4116  *      MTIOCPOS -      The current tape "block position" is returned. We
4117  *                      assume that each block contains user_block_size
4118  *                      bytes.
4119  *
4120  *      Our own ide-tape ioctls are supported on both interfaces.
4121  */
4122 static int idetape_chrdev_ioctl (struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
4123 {
4124         ide_drive_t *drive = file->private_data;
4125         idetape_tape_t *tape = drive->driver_data;
4126         struct mtop mtop;
4127         struct mtget mtget;
4128         struct mtpos mtpos;
4129         int block_offset = 0, position = tape->first_frame_position;
4130
4131 #if IDETAPE_DEBUG_LOG
4132         if (tape->debug_level >= 3)
4133                 printk(KERN_INFO "ide-tape: Reached idetape_chrdev_ioctl, "
4134                         "cmd=%u\n", cmd);
4135 #endif /* IDETAPE_DEBUG_LOG */
4136
4137         tape->restart_speed_control_req = 1;
4138         if (tape->chrdev_direction == idetape_direction_write) {
4139                 idetape_empty_write_pipeline(drive);
4140                 idetape_flush_tape_buffers(drive);
4141         }
4142         if (cmd == MTIOCGET || cmd == MTIOCPOS) {
4143                 block_offset = idetape_pipeline_size(drive) / (tape->tape_block_size * tape->user_bs_factor);
4144                 if ((position = idetape_read_position(drive)) < 0)
4145                         return -EIO;
4146         }
4147         switch (cmd) {
4148                 case MTIOCTOP:
4149                         if (copy_from_user((char *) &mtop, (char *) arg, sizeof (struct mtop)))
4150                                 return -EFAULT;
4151                         return (idetape_mtioctop(drive,mtop.mt_op,mtop.mt_count));
4152                 case MTIOCGET:
4153                         memset(&mtget, 0, sizeof (struct mtget));
4154                         mtget.mt_type = MT_ISSCSI2;
4155                         mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
4156                         mtget.mt_dsreg = ((tape->tape_block_size * tape->user_bs_factor) << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
4157                         if (tape->drv_write_prot) {
4158                                 mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
4159                         }
4160                         if (copy_to_user((char *) arg,(char *) &mtget, sizeof(struct mtget)))
4161                                 return -EFAULT;
4162                         return 0;
4163                 case MTIOCPOS:
4164                         mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
4165                         if (copy_to_user((char *) arg,(char *) &mtpos, sizeof(struct mtpos)))
4166                                 return -EFAULT;
4167                         return 0;
4168                 default:
4169                         if (tape->chrdev_direction == idetape_direction_read)
4170                                 idetape_discard_read_pipeline(drive, 1);
4171                         return idetape_blkdev_ioctl(drive, cmd, arg);
4172         }
4173 }
4174
4175 static void idetape_get_blocksize_from_block_descriptor(ide_drive_t *drive);
4176
4177 /*
4178  *      Our character device open function.
4179  */
4180 static int idetape_chrdev_open (struct inode *inode, struct file *filp)
4181 {
4182         unsigned int minor = iminor(inode), i = minor & ~0xc0;
4183         ide_drive_t *drive;
4184         idetape_tape_t *tape;
4185         idetape_pc_t pc;
4186         int retval;
4187
4188 #if IDETAPE_DEBUG_LOG
4189         printk(KERN_INFO "ide-tape: Reached idetape_chrdev_open\n");
4190 #endif /* IDETAPE_DEBUG_LOG */
4191         
4192         if (i >= MAX_HWIFS * MAX_DRIVES)
4193                 return -ENXIO;
4194         drive = idetape_chrdevs[i].drive;
4195         tape = drive->driver_data;
4196         filp->private_data = drive;
4197
4198         if (test_and_set_bit(IDETAPE_BUSY, &tape->flags))
4199                 return -EBUSY;
4200         retval = idetape_wait_ready(drive, 60 * HZ);
4201         if (retval) {
4202                 clear_bit(IDETAPE_BUSY, &tape->flags);
4203                 printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
4204                 return retval;
4205         }
4206
4207         idetape_read_position(drive);
4208         if (!test_bit(IDETAPE_ADDRESS_VALID, &tape->flags))
4209                 (void)idetape_rewind_tape(drive);
4210
4211         if (tape->chrdev_direction != idetape_direction_read)
4212                 clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
4213
4214         /* Read block size and write protect status from drive. */
4215         idetape_get_blocksize_from_block_descriptor(drive);
4216
4217         /* Set write protect flag if device is opened as read-only. */
4218         if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
4219                 tape->write_prot = 1;
4220         else
4221                 tape->write_prot = tape->drv_write_prot;
4222
4223         /* Make sure drive isn't write protected if user wants to write. */
4224         if (tape->write_prot) {
4225                 if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
4226                     (filp->f_flags & O_ACCMODE) == O_RDWR) {
4227                         clear_bit(IDETAPE_BUSY, &tape->flags);
4228                         return -EROFS;
4229                 }
4230         }
4231
4232         /*
4233          * Lock the tape drive door so user can't eject.
4234          */
4235         if (tape->chrdev_direction == idetape_direction_none) {
4236                 if (idetape_create_prevent_cmd(drive, &pc, 1)) {
4237                         if (!idetape_queue_pc_tail(drive, &pc)) {
4238                                 if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
4239                                         tape->door_locked = DOOR_LOCKED;
4240                         }
4241                 }
4242         }
4243         idetape_restart_speed_control(drive);
4244         tape->restart_speed_control_req = 0;
4245         return 0;
4246 }
4247
4248 static void idetape_write_release (ide_drive_t *drive, unsigned int minor)
4249 {
4250         idetape_tape_t *tape = drive->driver_data;
4251
4252         idetape_empty_write_pipeline(drive);
4253         tape->merge_stage = __idetape_kmalloc_stage(tape, 1, 0);
4254         if (tape->merge_stage != NULL) {
4255                 idetape_pad_zeros(drive, tape->tape_block_size * (tape->user_bs_factor - 1));
4256                 __idetape_kfree_stage(tape->merge_stage);
4257                 tape->merge_stage = NULL;
4258         }
4259         idetape_write_filemark(drive);
4260         idetape_flush_tape_buffers(drive);
4261         idetape_flush_tape_buffers(drive);
4262 }
4263
4264 /*
4265  *      Our character device release function.
4266  */
4267 static int idetape_chrdev_release (struct inode *inode, struct file *filp)
4268 {
4269         ide_drive_t *drive = filp->private_data;
4270         idetape_tape_t *tape;
4271         idetape_pc_t pc;
4272         unsigned int minor = iminor(inode);
4273
4274         lock_kernel();
4275         tape = drive->driver_data;
4276 #if IDETAPE_DEBUG_LOG
4277         if (tape->debug_level >= 3)
4278                 printk(KERN_INFO "ide-tape: Reached idetape_chrdev_release\n");
4279 #endif /* IDETAPE_DEBUG_LOG */
4280
4281         if (tape->chrdev_direction == idetape_direction_write)
4282                 idetape_write_release(drive, minor);
4283         if (tape->chrdev_direction == idetape_direction_read) {
4284                 if (minor < 128)
4285                         idetape_discard_read_pipeline(drive, 1);
4286                 else
4287                         idetape_wait_for_pipeline(drive);
4288         }
4289         if (tape->cache_stage != NULL) {
4290                 __idetape_kfree_stage(tape->cache_stage);
4291                 tape->cache_stage = NULL;
4292         }
4293         if (minor < 128 && test_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags))
4294                 (void) idetape_rewind_tape(drive);
4295         if (tape->chrdev_direction == idetape_direction_none) {
4296                 if (tape->door_locked == DOOR_LOCKED) {
4297                         if (idetape_create_prevent_cmd(drive, &pc, 0)) {
4298                                 if (!idetape_queue_pc_tail(drive, &pc))
4299                                         tape->door_locked = DOOR_UNLOCKED;
4300                         }
4301                 }
4302         }
4303         clear_bit(IDETAPE_BUSY, &tape->flags);
4304         unlock_kernel();
4305         return 0;
4306 }
4307
4308 /*
4309  *      idetape_identify_device is called to check the contents of the
4310  *      ATAPI IDENTIFY command results. We return:
4311  *
4312  *      1       If the tape can be supported by us, based on the information
4313  *              we have so far.
4314  *
4315  *      0       If this tape driver is not currently supported by us.
4316  */
4317 static int idetape_identify_device (ide_drive_t *drive)
4318 {
4319         struct idetape_id_gcw gcw;
4320         struct hd_driveid *id = drive->id;
4321 #if IDETAPE_DEBUG_INFO
4322         unsigned short mask,i;
4323 #endif /* IDETAPE_DEBUG_INFO */
4324
4325         if (drive->id_read == 0)
4326                 return 1;
4327
4328         *((unsigned short *) &gcw) = id->config;
4329
4330 #if IDETAPE_DEBUG_INFO
4331         printk(KERN_INFO "ide-tape: Dumping ATAPI Identify Device tape parameters\n");
4332         printk(KERN_INFO "ide-tape: Protocol Type: ");
4333         switch (gcw.protocol) {
4334                 case 0: case 1: printk("ATA\n");break;
4335                 case 2: printk("ATAPI\n");break;
4336                 case 3: printk("Reserved (Unknown to ide-tape)\n");break;
4337         }
4338         printk(KERN_INFO "ide-tape: Device Type: %x - ",gcw.device_type);       
4339         switch (gcw.device_type) {
4340                 case 0: printk("Direct-access Device\n");break;
4341                 case 1: printk("Streaming Tape Device\n");break;
4342                 case 2: case 3: case 4: printk("Reserved\n");break;
4343                 case 5: printk("CD-ROM Device\n");break;
4344                 case 6: printk("Reserved\n");
4345                 case 7: printk("Optical memory Device\n");break;
4346                 case 0x1f: printk("Unknown or no Device type\n");break;
4347                 default: printk("Reserved\n");
4348         }
4349         printk(KERN_INFO "ide-tape: Removable: %s",gcw.removable ? "Yes\n":"No\n");     
4350         printk(KERN_INFO "ide-tape: Command Packet DRQ Type: ");
4351         switch (gcw.drq_type) {
4352                 case 0: printk("Microprocessor DRQ\n");break;
4353                 case 1: printk("Interrupt DRQ\n");break;
4354                 case 2: printk("Accelerated DRQ\n");break;
4355                 case 3: printk("Reserved\n");break;
4356         }
4357         printk(KERN_INFO "ide-tape: Command Packet Size: ");
4358         switch (gcw.packet_size) {
4359                 case 0: printk("12 bytes\n");break;
4360                 case 1: printk("16 bytes\n");break;
4361                 default: printk("Reserved\n");break;
4362         }
4363         printk(KERN_INFO "ide-tape: Model: %.40s\n",id->model);
4364         printk(KERN_INFO "ide-tape: Firmware Revision: %.8s\n",id->fw_rev);
4365         printk(KERN_INFO "ide-tape: Serial Number: %.20s\n",id->serial_no);
4366         printk(KERN_INFO "ide-tape: Write buffer size: %d bytes\n",id->buf_size*512);
4367         printk(KERN_INFO "ide-tape: DMA: %s",id->capability & 0x01 ? "Yes\n":"No\n");
4368         printk(KERN_INFO "ide-tape: LBA: %s",id->capability & 0x02 ? "Yes\n":"No\n");
4369         printk(KERN_INFO "ide-tape: IORDY can be disabled: %s",id->capability & 0x04 ? "Yes\n":"No\n");
4370         printk(KERN_INFO "ide-tape: IORDY supported: %s",id->capability & 0x08 ? "Yes\n":"Unknown\n");
4371         printk(KERN_INFO "ide-tape: ATAPI overlap supported: %s",id->capability & 0x20 ? "Yes\n":"No\n");
4372         printk(KERN_INFO "ide-tape: PIO Cycle Timing Category: %d\n",id->tPIO);
4373         printk(KERN_INFO "ide-tape: DMA Cycle Timing Category: %d\n",id->tDMA);
4374         printk(KERN_INFO "ide-tape: Single Word DMA supported modes: ");
4375         for (i=0,mask=1;i<8;i++,mask=mask << 1) {
4376                 if (id->dma_1word & mask)
4377                         printk("%d ",i);
4378                 if (id->dma_1word & (mask << 8))
4379                         printk("(active) ");
4380         }
4381         printk("\n");
4382         printk(KERN_INFO "ide-tape: Multi Word DMA supported modes: ");
4383         for (i=0,mask=1;i<8;i++,mask=mask << 1) {
4384                 if (id->dma_mword & mask)
4385                         printk("%d ",i);
4386                 if (id->dma_mword & (mask << 8))
4387                         printk("(active) ");
4388         }
4389         printk("\n");
4390         if (id->field_valid & 0x0002) {
4391                 printk(KERN_INFO "ide-tape: Enhanced PIO Modes: %s\n",
4392                         id->eide_pio_modes & 1 ? "Mode 3":"None");
4393                 printk(KERN_INFO "ide-tape: Minimum Multi-word DMA cycle per word: ");
4394                 if (id->eide_dma_min == 0)
4395                         printk("Not supported\n");
4396                 else
4397                         printk("%d ns\n",id->eide_dma_min);
4398
4399                 printk(KERN_INFO "ide-tape: Manufacturer\'s Recommended Multi-word cycle: ");
4400                 if (id->eide_dma_time == 0)
4401                         printk("Not supported\n");
4402                 else
4403                         printk("%d ns\n",id->eide_dma_time);
4404
4405                 printk(KERN_INFO "ide-tape: Minimum PIO cycle without IORDY: ");
4406                 if (id->eide_pio == 0)
4407                         printk("Not supported\n");
4408                 else
4409                         printk("%d ns\n",id->eide_pio);
4410
4411                 printk(KERN_INFO "ide-tape: Minimum PIO cycle with IORDY: ");
4412                 if (id->eide_pio_iordy == 0)
4413                         printk("Not supported\n");
4414                 else
4415                         printk("%d ns\n",id->eide_pio_iordy);
4416                 
4417         } else
4418                 printk(KERN_INFO "ide-tape: According to the device, fields 64-70 are not valid.\n");
4419 #endif /* IDETAPE_DEBUG_INFO */
4420
4421         /* Check that we can support this device */
4422
4423         if (gcw.protocol !=2 )
4424                 printk(KERN_ERR "ide-tape: Protocol is not ATAPI\n");
4425         else if (gcw.device_type != 1)
4426                 printk(KERN_ERR "ide-tape: Device type is not set to tape\n");
4427         else if (!gcw.removable)
4428                 printk(KERN_ERR "ide-tape: The removable flag is not set\n");
4429         else if (gcw.packet_size != 0) {
4430                 printk(KERN_ERR "ide-tape: Packet size is not 12 bytes long\n");
4431                 if (gcw.packet_size == 1)
4432                         printk(KERN_ERR "ide-tape: Sorry, padding to 16 bytes is still not supported\n");
4433         } else
4434                 return 1;
4435         return 0;
4436 }
4437
4438 /*
4439  * Use INQUIRY to get the firmware revision
4440  */
4441 static void idetape_get_inquiry_results (ide_drive_t *drive)
4442 {
4443         char *r;
4444         idetape_tape_t *tape = drive->driver_data;
4445         idetape_pc_t pc;
4446         idetape_inquiry_result_t *inquiry;
4447         
4448         idetape_create_inquiry_cmd(&pc);
4449         if (idetape_queue_pc_tail(drive, &pc)) {
4450                 printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n", tape->name);
4451                 return;
4452         }
4453         inquiry = (idetape_inquiry_result_t *) pc.buffer;
4454         memcpy(tape->vendor_id, inquiry->vendor_id, 8);
4455         memcpy(tape->product_id, inquiry->product_id, 16);
4456         memcpy(tape->firmware_revision, inquiry->revision_level, 4);
4457         ide_fixstring(tape->vendor_id, 10, 0);
4458         ide_fixstring(tape->product_id, 18, 0);
4459         ide_fixstring(tape->firmware_revision, 6, 0);
4460         r = tape->firmware_revision;
4461         if (*(r + 1) == '.')
4462                 tape->firmware_revision_num = (*r - '0') * 100 + (*(r + 2) - '0') * 10 + *(r + 3) - '0';
4463         printk(KERN_INFO "ide-tape: %s <-> %s: %s %s rev %s\n", drive->name, tape->name, tape->vendor_id, tape->product_id, tape->firmware_revision);
4464 }
4465
4466 /*
4467  *      idetape_get_mode_sense_results asks the tape about its various
4468  *      parameters. In particular, we will adjust our data transfer buffer
4469  *      size to the recommended value as returned by the tape.
4470  */
4471 static void idetape_get_mode_sense_results (ide_drive_t *drive)
4472 {
4473         idetape_tape_t *tape = drive->driver_data;
4474         idetape_pc_t pc;
4475         idetape_mode_parameter_header_t *header;
4476         idetape_capabilities_page_t *capabilities;
4477         
4478         idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
4479         if (idetape_queue_pc_tail(drive, &pc)) {
4480                 printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming some default values\n");
4481                 tape->tape_block_size = 512;
4482                 tape->capabilities.ctl = 52;
4483                 tape->capabilities.speed = 450;
4484                 tape->capabilities.buffer_size = 6 * 52;
4485                 return;
4486         }
4487         header = (idetape_mode_parameter_header_t *) pc.buffer;
4488         capabilities = (idetape_capabilities_page_t *) (pc.buffer + sizeof(idetape_mode_parameter_header_t) + header->bdl);
4489
4490         capabilities->max_speed = ntohs(capabilities->max_speed);
4491         capabilities->ctl = ntohs(capabilities->ctl);
4492         capabilities->speed = ntohs(capabilities->speed);
4493         capabilities->buffer_size = ntohs(capabilities->buffer_size);
4494
4495         if (!capabilities->speed) {
4496                 printk(KERN_INFO "ide-tape: %s: overriding capabilities->speed (assuming 650KB/sec)\n", drive->name);
4497                 capabilities->speed = 650;
4498         }
4499         if (!capabilities->max_speed) {
4500                 printk(KERN_INFO "ide-tape: %s: overriding capabilities->max_speed (assuming 650KB/sec)\n", drive->name);
4501                 capabilities->max_speed = 650;
4502         }
4503
4504         tape->capabilities = *capabilities;             /* Save us a copy */
4505         if (capabilities->blk512)
4506                 tape->tape_block_size = 512;
4507         else if (capabilities->blk1024)
4508                 tape->tape_block_size = 1024;
4509
4510 #if IDETAPE_DEBUG_INFO
4511         printk(KERN_INFO "ide-tape: Dumping the results of the MODE SENSE packet command\n");
4512         printk(KERN_INFO "ide-tape: Mode Parameter Header:\n");
4513         printk(KERN_INFO "ide-tape: Mode Data Length - %d\n",header->mode_data_length);
4514         printk(KERN_INFO "ide-tape: Medium Type - %d\n",header->medium_type);
4515         printk(KERN_INFO "ide-tape: Device Specific Parameter - %d\n",header->dsp);
4516         printk(KERN_INFO "ide-tape: Block Descriptor Length - %d\n",header->bdl);
4517         
4518         printk(KERN_INFO "ide-tape: Capabilities and Mechanical Status Page:\n");
4519         printk(KERN_INFO "ide-tape: Page code - %d\n",capabilities->page_code);
4520         printk(KERN_INFO "ide-tape: Page length - %d\n",capabilities->page_length);
4521         printk(KERN_INFO "ide-tape: Read only - %s\n",capabilities->ro ? "Yes":"No");
4522         printk(KERN_INFO "ide-tape: Supports reverse space - %s\n",capabilities->sprev ? "Yes":"No");
4523         printk(KERN_INFO "ide-tape: Supports erase initiated formatting - %s\n",capabilities->efmt ? "Yes":"No");
4524         printk(KERN_INFO "ide-tape: Supports QFA two Partition format - %s\n",capabilities->qfa ? "Yes":"No");
4525         printk(KERN_INFO "ide-tape: Supports locking the medium - %s\n",capabilities->lock ? "Yes":"No");
4526         printk(KERN_INFO "ide-tape: The volume is currently locked - %s\n",capabilities->locked ? "Yes":"No");
4527         printk(KERN_INFO "ide-tape: The device defaults in the prevent state - %s\n",capabilities->prevent ? "Yes":"No");
4528         printk(KERN_INFO "ide-tape: Supports ejecting the medium - %s\n",capabilities->eject ? "Yes":"No");
4529         printk(KERN_INFO "ide-tape: Supports error correction - %s\n",capabilities->ecc ? "Yes":"No");
4530         printk(KERN_INFO "ide-tape: Supports data compression - %s\n",capabilities->cmprs ? "Yes":"No");
4531         printk(KERN_INFO "ide-tape: Supports 512 bytes block size - %s\n",capabilities->blk512 ? "Yes":"No");
4532         printk(KERN_INFO "ide-tape: Supports 1024 bytes block size - %s\n",capabilities->blk1024 ? "Yes":"No");
4533         printk(KERN_INFO "ide-tape: Supports 32768 bytes block size / Restricted byte count for PIO transfers - %s\n",capabilities->blk32768 ? "Yes":"No");
4534         printk(KERN_INFO "ide-tape: Maximum supported speed in KBps - %d\n",capabilities->max_speed);
4535         printk(KERN_INFO "ide-tape: Continuous transfer limits in blocks - %d\n",capabilities->ctl);
4536         printk(KERN_INFO "ide-tape: Current speed in KBps - %d\n",capabilities->speed); 
4537         printk(KERN_INFO "ide-tape: Buffer size - %d\n",capabilities->buffer_size*512);
4538 #endif /* IDETAPE_DEBUG_INFO */
4539 }
4540
4541 /*
4542  *      ide_get_blocksize_from_block_descriptor does a mode sense page 0 with block descriptor
4543  *      and if it succeeds sets the tape block size with the reported value
4544  */
4545 static void idetape_get_blocksize_from_block_descriptor(ide_drive_t *drive)
4546 {
4547
4548         idetape_tape_t *tape = drive->driver_data;
4549         idetape_pc_t pc;
4550         idetape_mode_parameter_header_t *header;
4551         idetape_parameter_block_descriptor_t *block_descrp;
4552         
4553         idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
4554         if (idetape_queue_pc_tail(drive, &pc)) {
4555                 printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
4556                 if (tape->tape_block_size == 0) {
4557                         printk(KERN_WARNING "ide-tape: Cannot deal with zero block size, assume 32k\n");
4558                         tape->tape_block_size =  32768;
4559                 }
4560                 return;
4561         }
4562         header = (idetape_mode_parameter_header_t *) pc.buffer;
4563         block_descrp = (idetape_parameter_block_descriptor_t *) (pc.buffer + sizeof(idetape_mode_parameter_header_t));
4564         tape->tape_block_size =( block_descrp->length[0]<<16) + (block_descrp->length[1]<<8) + block_descrp->length[2];
4565         tape->drv_write_prot = (header->dsp & 0x80) >> 7;
4566
4567 #if IDETAPE_DEBUG_INFO
4568         printk(KERN_INFO "ide-tape: Adjusted block size - %d\n", tape->tape_block_size);
4569 #endif /* IDETAPE_DEBUG_INFO */
4570 }
4571 static void idetape_add_settings (ide_drive_t *drive)
4572 {
4573         idetape_tape_t *tape = drive->driver_data;
4574
4575 /*
4576  *                      drive   setting name    read/write      ioctl   ioctl           data type       min                     max                     mul_factor                      div_factor                      data pointer                            set function
4577  */
4578         ide_add_setting(drive,  "buffer",       SETTING_READ,   -1,     -1,             TYPE_SHORT,     0,                      0xffff,                 1,                              2,                              &tape->capabilities.buffer_size,        NULL);
4579         ide_add_setting(drive,  "pipeline_min", SETTING_RW,     -1,     -1,             TYPE_INT,       1,                      0xffff,                 tape->stage_size / 1024,        1,                              &tape->min_pipeline,                    NULL);
4580         ide_add_setting(drive,  "pipeline",     SETTING_RW,     -1,     -1,             TYPE_INT,       1,                      0xffff,                 tape->stage_size / 1024,        1,                              &tape->max_stages,                      NULL);
4581         ide_add_setting(drive,  "pipeline_max", SETTING_RW,     -1,     -1,             TYPE_INT,       1,                      0xffff,                 tape->stage_size / 1024,        1,                              &tape->max_pipeline,                    NULL);
4582         ide_add_setting(drive,  "pipeline_used",SETTING_READ,   -1,     -1,             TYPE_INT,       0,                      0xffff,                 tape->stage_size / 1024,        1,                              &tape->nr_stages,                       NULL);
4583         ide_add_setting(drive,  "pipeline_pending",SETTING_READ,-1,     -1,             TYPE_INT,       0,                      0xffff,                 tape->stage_size / 1024,        1,                              &tape->nr_pending_stages,               NULL);
4584         ide_add_setting(drive,  "speed",        SETTING_READ,   -1,     -1,             TYPE_SHORT,     0,                      0xffff,                 1,                              1,                              &tape->capabilities.speed,              NULL);
4585         ide_add_setting(drive,  "stage",        SETTING_READ,   -1,     -1,             TYPE_INT,       0,                      0xffff,                 1,                              1024,                           &tape->stage_size,                      NULL);
4586         ide_add_setting(drive,  "tdsc",         SETTING_RW,     -1,     -1,             TYPE_INT,       IDETAPE_DSC_RW_MIN,     IDETAPE_DSC_RW_MAX,     1000,                           HZ,                             &tape->best_dsc_rw_frequency,           NULL);
4587         ide_add_setting(drive,  "dsc_overlap",  SETTING_RW,     -1,     -1,             TYPE_BYTE,      0,                      1,                      1,                              1,                              &drive->dsc_overlap,                    NULL);
4588         ide_add_setting(drive,  "pipeline_head_speed_c",SETTING_READ,   -1,     -1,     TYPE_INT,       0,                      0xffff,                 1,                              1,                              &tape->controlled_pipeline_head_speed,  NULL);
4589         ide_add_setting(drive,  "pipeline_head_speed_u",SETTING_READ,   -1,     -1,     TYPE_INT,       0,                      0xffff,                 1,                              1,                              &tape->uncontrolled_pipeline_head_speed,        NULL);
4590         ide_add_setting(drive,  "avg_speed",    SETTING_READ,   -1,     -1,             TYPE_INT,       0,                      0xffff,                 1,                              1,                              &tape->avg_speed,               NULL);
4591         ide_add_setting(drive,  "debug_level",SETTING_RW,       -1,     -1,             TYPE_INT,       0,                      0xffff,                 1,                              1,                              &tape->debug_level,             NULL);
4592 }
4593
4594 /*
4595  *      ide_setup is called to:
4596  *
4597  *              1.      Initialize our various state variables.
4598  *              2.      Ask the tape for its capabilities.
4599  *              3.      Allocate a buffer which will be used for data
4600  *                      transfer. The buffer size is chosen based on
4601  *                      the recommendation which we received in step (2).
4602  *
4603  *      Note that at this point ide.c already assigned us an irq, so that
4604  *      we can queue requests here and wait for their completion.
4605  */
4606 static void idetape_setup (ide_drive_t *drive, idetape_tape_t *tape, int minor)
4607 {
4608         unsigned long t1, tmid, tn, t;
4609         int speed;
4610         struct idetape_id_gcw gcw;
4611         int stage_size;
4612         struct sysinfo si;
4613
4614         memset(tape, 0, sizeof (idetape_tape_t));
4615         spin_lock_init(&tape->spinlock);
4616         drive->driver_data = tape;
4617         /* An ATAPI device ignores DRDY */
4618         drive->ready_stat = 0;
4619         drive->dsc_overlap = 1;
4620 #ifdef CONFIG_BLK_DEV_IDEPCI
4621         if (HWIF(drive)->pci_dev != NULL) {
4622                 /*
4623                  * These two ide-pci host adapters appear to need DSC overlap disabled.
4624                  * This probably needs further analysis.
4625                  */
4626                 if ((HWIF(drive)->pci_dev->device == PCI_DEVICE_ID_ARTOP_ATP850UF) ||
4627                     (HWIF(drive)->pci_dev->device == PCI_DEVICE_ID_TTI_HPT343)) {
4628                         printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n", tape->name);
4629                         drive->dsc_overlap = 0;
4630                 }
4631         }
4632 #endif /* CONFIG_BLK_DEV_IDEPCI */
4633         /* Seagate Travan drives do not support DSC overlap. */
4634         if (strstr(drive->id->model, "Seagate STT3401"))
4635                 drive->dsc_overlap = 0;
4636         tape->drive = drive;
4637         tape->minor = minor;
4638         tape->name[0] = 'h';
4639         tape->name[1] = 't';
4640         tape->name[2] = '0' + minor;
4641         tape->chrdev_direction = idetape_direction_none;
4642         tape->pc = tape->pc_stack;
4643         tape->max_insert_speed = 10000;
4644         tape->speed_control = 1;
4645         *((unsigned short *) &gcw) = drive->id->config;
4646         if (gcw.drq_type == 1)
4647                 set_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags);
4648
4649         tape->min_pipeline = tape->max_pipeline = tape->max_stages = 10;
4650         
4651         idetape_get_inquiry_results(drive);
4652         idetape_get_mode_sense_results(drive);
4653         idetape_get_blocksize_from_block_descriptor(drive);
4654         tape->user_bs_factor = 1;
4655         tape->stage_size = tape->capabilities.ctl * tape->tape_block_size;
4656         while (tape->stage_size > 0xffff) {
4657                 printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
4658                 tape->capabilities.ctl /= 2;
4659                 tape->stage_size = tape->capabilities.ctl * tape->tape_block_size;
4660         }
4661         stage_size = tape->stage_size;
4662         tape->pages_per_stage = stage_size / PAGE_SIZE;
4663         if (stage_size % PAGE_SIZE) {
4664                 tape->pages_per_stage++;
4665                 tape->excess_bh_size = PAGE_SIZE - stage_size % PAGE_SIZE;
4666         }
4667
4668         /*
4669          *      Select the "best" DSC read/write polling frequency
4670          *      and pipeline size.
4671          */
4672         speed = max(tape->capabilities.speed, tape->capabilities.max_speed);
4673
4674         tape->max_stages = speed * 1000 * 10 / tape->stage_size;
4675
4676         /*
4677          *      Limit memory use for pipeline to 10% of physical memory
4678          */
4679         si_meminfo(&si);
4680         if (tape->max_stages * tape->stage_size > si.totalram * si.mem_unit / 10)
4681                 tape->max_stages = si.totalram * si.mem_unit / (10 * tape->stage_size);
4682         tape->max_stages   = min(tape->max_stages, IDETAPE_MAX_PIPELINE_STAGES);
4683         tape->min_pipeline = min(tape->max_stages, IDETAPE_MIN_PIPELINE_STAGES);
4684         tape->max_pipeline = min(tape->max_stages * 2, IDETAPE_MAX_PIPELINE_STAGES);
4685         if (tape->max_stages == 0)
4686                 tape->max_stages = tape->min_pipeline = tape->max_pipeline = 1;
4687
4688         t1 = (tape->stage_size * HZ) / (speed * 1000);
4689         tmid = (tape->capabilities.buffer_size * 32 * HZ) / (speed * 125);
4690         tn = (IDETAPE_FIFO_THRESHOLD * tape->stage_size * HZ) / (speed * 1000);
4691
4692         if (tape->max_stages)
4693                 t = tn;
4694         else
4695                 t = t1;
4696
4697         /*
4698          *      Ensure that the number we got makes sense; limit
4699          *      it within IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
4700          */
4701         tape->best_dsc_rw_frequency = max_t(unsigned long, min_t(unsigned long, t, IDETAPE_DSC_RW_MAX), IDETAPE_DSC_RW_MIN);
4702         printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
4703                 "%dkB pipeline, %lums tDSC%s\n",
4704                 drive->name, tape->name, tape->capabilities.speed,
4705                 (tape->capabilities.buffer_size * 512) / tape->stage_size,
4706                 tape->stage_size / 1024,
4707                 tape->max_stages * tape->stage_size / 1024,
4708                 tape->best_dsc_rw_frequency * 1000 / HZ,
4709                 drive->using_dma ? ", DMA":"");
4710
4711         idetape_add_settings(drive);
4712 }
4713
4714 static int idetape_cleanup (ide_drive_t *drive)
4715 {
4716         idetape_tape_t *tape = drive->driver_data;
4717         int minor = tape->minor;
4718         unsigned long flags;
4719
4720         spin_lock_irqsave(&ide_lock, flags);
4721         if (test_bit(IDETAPE_BUSY, &tape->flags) || drive->usage ||
4722             tape->first_stage != NULL || tape->merge_stage_size) {
4723                 spin_unlock_irqrestore(&ide_lock, flags);
4724                 return 1;
4725         }
4726         idetape_chrdevs[minor].drive = NULL;
4727         spin_unlock_irqrestore(&ide_lock, flags);
4728         DRIVER(drive)->busy = 0;
4729         (void) ide_unregister_subdriver(drive);
4730         drive->driver_data = NULL;
4731         devfs_remove("%s/mt", drive->devfs_name);
4732         devfs_remove("%s/mtn", drive->devfs_name);
4733         devfs_unregister_tape(drive->disk->number);
4734         kfree (tape);
4735         drive->disk->fops = ide_fops;
4736         return 0;
4737 }
4738
4739 #ifdef CONFIG_PROC_FS
4740
4741 static int proc_idetape_read_name
4742         (char *page, char **start, off_t off, int count, int *eof, void *data)
4743 {
4744         ide_drive_t     *drive = (ide_drive_t *) data;
4745         idetape_tape_t  *tape = drive->driver_data;
4746         char            *out = page;
4747         int             len;
4748
4749         len = sprintf(out, "%s\n", tape->name);
4750         PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
4751 }
4752
4753 static ide_proc_entry_t idetape_proc[] = {
4754         { "name",       S_IFREG|S_IRUGO,        proc_idetape_read_name, NULL },
4755         { NULL, 0, NULL, NULL }
4756 };
4757
4758 #else
4759
4760 #define idetape_proc    NULL
4761
4762 #endif
4763
4764 static int idetape_attach(ide_drive_t *drive);
4765
4766 /*
4767  *      IDE subdriver functions, registered with ide.c
4768  */
4769 static ide_driver_t idetape_driver = {
4770         .owner                  = THIS_MODULE,
4771         .name                   = "ide-tape",
4772         .version                = IDETAPE_VERSION,
4773         .media                  = ide_tape,
4774         .busy                   = 1,
4775         .supports_dsc_overlap   = 1,
4776         .cleanup                = idetape_cleanup,
4777         .do_request             = idetape_do_request,
4778         .end_request            = idetape_end_request,
4779         .pre_reset              = idetape_pre_reset,
4780         .proc                   = idetape_proc,
4781         .attach                 = idetape_attach,
4782         .drives                 = LIST_HEAD_INIT(idetape_driver.drives),
4783 };
4784
4785 /*
4786  *      Our character device supporting functions, passed to register_chrdev.
4787  */
4788 static struct file_operations idetape_fops = {
4789         .owner          = THIS_MODULE,
4790         .read           = idetape_chrdev_read,
4791         .write          = idetape_chrdev_write,
4792         .ioctl          = idetape_chrdev_ioctl,
4793         .open           = idetape_chrdev_open,
4794         .release        = idetape_chrdev_release,
4795 };
4796
4797 static int idetape_open(struct inode *inode, struct file *filp)
4798 {
4799         ide_drive_t *drive = inode->i_bdev->bd_disk->private_data;
4800         drive->usage++;
4801         return 0;
4802 }
4803
4804 static int idetape_release(struct inode *inode, struct file *filp)
4805 {
4806         ide_drive_t *drive = inode->i_bdev->bd_disk->private_data;
4807         drive->usage--;
4808         return 0;
4809 }
4810
4811 static int idetape_ioctl(struct inode *inode, struct file *file,
4812                         unsigned int cmd, unsigned long arg)
4813 {
4814         struct block_device *bdev = inode->i_bdev;
4815         ide_drive_t *drive = bdev->bd_disk->private_data;
4816         int err = generic_ide_ioctl(bdev, cmd, arg);
4817         if (err == -EINVAL)
4818                 err = idetape_blkdev_ioctl(drive, cmd, arg);
4819         return err;
4820 }
4821
4822 static struct block_device_operations idetape_block_ops = {
4823         .owner          = THIS_MODULE,
4824         .open           = idetape_open,
4825         .release        = idetape_release,
4826         .ioctl          = idetape_ioctl,
4827 };
4828
4829 static int idetape_attach (ide_drive_t *drive)
4830 {
4831         idetape_tape_t *tape;
4832         int minor;
4833
4834         if (!strstr("ide-tape", drive->driver_req))
4835                 goto failed;
4836         if (!drive->present)
4837                 goto failed;
4838         if (drive->media != ide_tape)
4839                 goto failed;
4840         if (!idetape_identify_device (drive)) {
4841                 printk(KERN_ERR "ide-tape: %s: not supported by this version of ide-tape\n", drive->name);
4842                 goto failed;
4843         }
4844         if (drive->scsi) {
4845                 printk("ide-tape: passing drive %s to ide-scsi emulation.\n", drive->name);
4846                 goto failed;
4847         }
4848         if (strstr(drive->id->model, "OnStream DI-")) {
4849                 printk(KERN_WARNING "ide-tape: Use drive %s with ide-scsi emulation and osst.\n", drive->name);
4850                 printk(KERN_WARNING "ide-tape: OnStream support will be removed soon from ide-tape!\n");
4851         }
4852         tape = (idetape_tape_t *) kmalloc (sizeof (idetape_tape_t), GFP_KERNEL);
4853         if (tape == NULL) {
4854                 printk(KERN_ERR "ide-tape: %s: Can't allocate a tape structure\n", drive->name);
4855                 goto failed;
4856         }
4857         if (ide_register_subdriver(drive, &idetape_driver)) {
4858                 printk(KERN_ERR "ide-tape: %s: Failed to register the driver with ide.c\n", drive->name);
4859                 kfree(tape);
4860                 goto failed;
4861         }
4862         for (minor = 0; idetape_chrdevs[minor].drive != NULL; minor++)
4863                 ;
4864         idetape_setup(drive, tape, minor);
4865         idetape_chrdevs[minor].drive = drive;
4866
4867         devfs_mk_cdev(MKDEV(HWIF(drive)->major, minor),
4868                         S_IFCHR | S_IRUGO | S_IWUGO,
4869                         "%s/mt", drive->devfs_name);
4870         devfs_mk_cdev(MKDEV(HWIF(drive)->major, minor + 128),
4871                         S_IFCHR | S_IRUGO | S_IWUGO,
4872                         "%s/mtn", drive->devfs_name);
4873
4874         drive->disk->number = devfs_register_tape(drive->devfs_name);
4875         drive->disk->fops = &idetape_block_ops;
4876         return 0;
4877 failed:
4878         return 1;
4879 }
4880
4881 MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
4882 MODULE_LICENSE("GPL");
4883
4884 static void __exit idetape_exit (void)
4885 {
4886         ide_unregister_driver(&idetape_driver);
4887         unregister_chrdev(IDETAPE_MAJOR, "ht");
4888 }
4889
4890 /*
4891  *      idetape_init will register the driver for each tape.
4892  */
4893 static int idetape_init (void)
4894 {
4895         if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
4896                 printk(KERN_ERR "ide-tape: Failed to register character device interface\n");
4897                 return -EBUSY;
4898         }
4899         ide_register_driver(&idetape_driver);
4900         return 0;
4901 }
4902
4903 module_init(idetape_init);
4904 module_exit(idetape_exit);
4905 MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);