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