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