Merge git://git.kernel.org/pub/scm/linux/kernel/git/bunk/trivial
[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/module.h>
428 #include <linux/types.h>
429 #include <linux/string.h>
430 #include <linux/kernel.h>
431 #include <linux/delay.h>
432 #include <linux/timer.h>
433 #include <linux/mm.h>
434 #include <linux/interrupt.h>
435 #include <linux/jiffies.h>
436 #include <linux/major.h>
437 #include <linux/errno.h>
438 #include <linux/genhd.h>
439 #include <linux/slab.h>
440 #include <linux/pci.h>
441 #include <linux/ide.h>
442 #include <linux/smp_lock.h>
443 #include <linux/completion.h>
444 #include <linux/bitops.h>
445 #include <linux/mutex.h>
446
447 #include <asm/byteorder.h>
448 #include <asm/irq.h>
449 #include <asm/uaccess.h>
450 #include <asm/io.h>
451 #include <asm/unaligned.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 system
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 #define IO_IDETAPE_FIFO 500
625 #endif
626
627 /*
628  *      Read/Write error simulation
629  */
630 #define SIMULATE_ERRORS                 0
631
632 /*
633  *      For general magnetic tape device compatibility.
634  */
635 typedef enum {
636         idetape_direction_none,
637         idetape_direction_read,
638         idetape_direction_write
639 } idetape_chrdev_direction_t;
640
641 struct idetape_bh {
642         u32 b_size;
643         atomic_t b_count;
644         struct idetape_bh *b_reqnext;
645         char *b_data;
646 };
647
648 /*
649  *      Our view of a packet command.
650  */
651 typedef struct idetape_packet_command_s {
652         u8 c[12];                               /* Actual packet bytes */
653         int retries;                            /* On each retry, we increment retries */
654         int error;                              /* Error code */
655         int request_transfer;                   /* Bytes to transfer */
656         int actually_transferred;               /* Bytes actually transferred */
657         int buffer_size;                        /* Size of our data buffer */
658         struct idetape_bh *bh;
659         char *b_data;
660         int b_count;
661         u8 *buffer;                             /* Data buffer */
662         u8 *current_position;                   /* Pointer into the above buffer */
663         ide_startstop_t (*callback) (ide_drive_t *);    /* Called when this packet command is completed */
664         u8 pc_buffer[IDETAPE_PC_BUFFER_SIZE];   /* Temporary buffer */
665         unsigned long flags;                    /* Status/Action bit flags: long for set_bit */
666 } idetape_pc_t;
667
668 /*
669  *      Packet command flag bits.
670  */
671 /* Set when an error is considered normal - We won't retry */
672 #define PC_ABORT                        0
673 /* 1 When polling for DSC on a media access command */
674 #define PC_WAIT_FOR_DSC                 1
675 /* 1 when we prefer to use DMA if possible */
676 #define PC_DMA_RECOMMENDED              2
677 /* 1 while DMA in progress */
678 #define PC_DMA_IN_PROGRESS              3
679 /* 1 when encountered problem during DMA */
680 #define PC_DMA_ERROR                    4
681 /* Data direction */
682 #define PC_WRITING                      5
683
684 /*
685  *      Capabilities and Mechanical Status Page
686  */
687 typedef struct {
688         unsigned        page_code       :6;     /* Page code - Should be 0x2a */
689         __u8            reserved0_6     :1;
690         __u8            ps              :1;     /* parameters saveable */
691         __u8            page_length;            /* Page Length - Should be 0x12 */
692         __u8            reserved2, reserved3;
693         unsigned        ro              :1;     /* Read Only Mode */
694         unsigned        reserved4_1234  :4;
695         unsigned        sprev           :1;     /* Supports SPACE in the reverse direction */
696         unsigned        reserved4_67    :2;
697         unsigned        reserved5_012   :3;
698         unsigned        efmt            :1;     /* Supports ERASE command initiated formatting */
699         unsigned        reserved5_4     :1;
700         unsigned        qfa             :1;     /* Supports the QFA two partition formats */
701         unsigned        reserved5_67    :2;
702         unsigned        lock            :1;     /* Supports locking the volume */
703         unsigned        locked          :1;     /* The volume is locked */
704         unsigned        prevent         :1;     /* The device defaults in the prevent state after power up */   
705         unsigned        eject           :1;     /* The device can eject the volume */
706         __u8            disconnect      :1;     /* The device can break request > ctl */        
707         __u8            reserved6_5     :1;
708         unsigned        ecc             :1;     /* Supports error correction */
709         unsigned        cmprs           :1;     /* Supports data compression */
710         unsigned        reserved7_0     :1;
711         unsigned        blk512          :1;     /* Supports 512 bytes block size */
712         unsigned        blk1024         :1;     /* Supports 1024 bytes block size */
713         unsigned        reserved7_3_6   :4;
714         unsigned        blk32768        :1;     /* slowb - the device restricts the byte count for PIO */
715                                                 /* transfers for slow buffer memory ??? */
716                                                 /* Also 32768 block size in some cases */
717         __u16           max_speed;              /* Maximum speed supported in KBps */
718         __u8            reserved10, reserved11;
719         __u16           ctl;                    /* Continuous Transfer Limit in blocks */
720         __u16           speed;                  /* Current Speed, in KBps */
721         __u16           buffer_size;            /* Buffer Size, in 512 bytes */
722         __u8            reserved18, reserved19;
723 } idetape_capabilities_page_t;
724
725 /*
726  *      Block Size Page
727  */
728 typedef struct {
729         unsigned        page_code       :6;     /* Page code - Should be 0x30 */
730         unsigned        reserved1_6     :1;
731         unsigned        ps              :1;
732         __u8            page_length;            /* Page Length - Should be 2 */
733         __u8            reserved2;
734         unsigned        play32          :1;
735         unsigned        play32_5        :1;
736         unsigned        reserved2_23    :2;
737         unsigned        record32        :1;
738         unsigned        record32_5      :1;
739         unsigned        reserved2_6     :1;
740         unsigned        one             :1;
741 } idetape_block_size_page_t;
742
743 /*
744  *      A pipeline stage.
745  */
746 typedef struct idetape_stage_s {
747         struct request rq;                      /* The corresponding request */
748         struct idetape_bh *bh;                  /* The data buffers */
749         struct idetape_stage_s *next;           /* Pointer to the next stage */
750 } idetape_stage_t;
751
752 /*
753  *      REQUEST SENSE packet command result - Data Format.
754  */
755 typedef struct {
756         unsigned        error_code      :7;     /* Current of deferred errors */
757         unsigned        valid           :1;     /* The information field conforms to QIC-157C */
758         __u8            reserved1       :8;     /* Segment Number - Reserved */
759         unsigned        sense_key       :4;     /* Sense Key */
760         unsigned        reserved2_4     :1;     /* Reserved */
761         unsigned        ili             :1;     /* Incorrect Length Indicator */
762         unsigned        eom             :1;     /* End Of Medium */
763         unsigned        filemark        :1;     /* Filemark */
764         __u32           information __attribute__ ((packed));
765         __u8            asl;                    /* Additional sense length (n-7) */
766         __u32           command_specific;       /* Additional command specific information */
767         __u8            asc;                    /* Additional Sense Code */
768         __u8            ascq;                   /* Additional Sense Code Qualifier */
769         __u8            replaceable_unit_code;  /* Field Replaceable Unit Code */
770         unsigned        sk_specific1    :7;     /* Sense Key Specific */
771         unsigned        sksv            :1;     /* Sense Key Specific information is valid */
772         __u8            sk_specific2;           /* Sense Key Specific */
773         __u8            sk_specific3;           /* Sense Key Specific */
774         __u8            pad[2];                 /* Padding to 20 bytes */
775 } idetape_request_sense_result_t;
776
777
778 /*
779  *      Most of our global data which we need to save even as we leave the
780  *      driver due to an interrupt or a timer event is stored in a variable
781  *      of type idetape_tape_t, defined below.
782  */
783 typedef struct ide_tape_obj {
784         ide_drive_t     *drive;
785         ide_driver_t    *driver;
786         struct gendisk  *disk;
787         struct kref     kref;
788
789         /*
790          *      Since a typical character device operation requires more
791          *      than one packet command, we provide here enough memory
792          *      for the maximum of interconnected packet commands.
793          *      The packet commands are stored in the circular array pc_stack.
794          *      pc_stack_index points to the last used entry, and warps around
795          *      to the start when we get to the last array entry.
796          *
797          *      pc points to the current processed packet command.
798          *
799          *      failed_pc points to the last failed packet command, or contains
800          *      NULL if we do not need to retry any packet command. This is
801          *      required since an additional packet command is needed before the
802          *      retry, to get detailed information on what went wrong.
803          */
804         /* Current packet command */
805         idetape_pc_t *pc;
806         /* Last failed packet command */
807         idetape_pc_t *failed_pc;
808         /* Packet command stack */
809         idetape_pc_t pc_stack[IDETAPE_PC_STACK];
810         /* Next free packet command storage space */
811         int pc_stack_index;
812         struct request rq_stack[IDETAPE_PC_STACK];
813         /* We implement a circular array */
814         int rq_stack_index;
815
816         /*
817          *      DSC polling variables.
818          *
819          *      While polling for DSC we use postponed_rq to postpone the
820          *      current request so that ide.c will be able to service
821          *      pending requests on the other device. Note that at most
822          *      we will have only one DSC (usually data transfer) request
823          *      in the device request queue. Additional requests can be
824          *      queued in our internal pipeline, but they will be visible
825          *      to ide.c only one at a time.
826          */
827         struct request *postponed_rq;
828         /* The time in which we started polling for DSC */
829         unsigned long dsc_polling_start;
830         /* Timer used to poll for dsc */
831         struct timer_list dsc_timer;
832         /* Read/Write dsc polling frequency */
833         unsigned long best_dsc_rw_frequency;
834         /* The current polling frequency */
835         unsigned long dsc_polling_frequency;
836         /* Maximum waiting time */
837         unsigned long dsc_timeout;
838
839         /*
840          *      Read position information
841          */
842         u8 partition;
843         /* Current block */
844         unsigned int first_frame_position;
845         unsigned int last_frame_position;
846         unsigned int blocks_in_buffer;
847
848         /*
849          *      Last error information
850          */
851         u8 sense_key, asc, ascq;
852
853         /*
854          *      Character device operation
855          */
856         unsigned int minor;
857         /* device name */
858         char name[4];
859         /* Current character device data transfer direction */
860         idetape_chrdev_direction_t chrdev_direction;
861
862         /*
863          *      Device information
864          */
865         /* Usually 512 or 1024 bytes */
866         unsigned short tape_block_size;
867         int user_bs_factor;
868         /* Copy of the tape's Capabilities and Mechanical Page */
869         idetape_capabilities_page_t capabilities;
870
871         /*
872          *      Active data transfer request parameters.
873          *
874          *      At most, there is only one ide-tape originated data transfer
875          *      request in the device request queue. This allows ide.c to
876          *      easily service requests from the other device when we
877          *      postpone our active request. In the pipelined operation
878          *      mode, we use our internal pipeline structure to hold
879          *      more data requests.
880          *
881          *      The data buffer size is chosen based on the tape's
882          *      recommendation.
883          */
884         /* Pointer to the request which is waiting in the device request queue */
885         struct request *active_data_request;
886         /* Data buffer size (chosen based on the tape's recommendation */
887         int stage_size;
888         idetape_stage_t *merge_stage;
889         int merge_stage_size;
890         struct idetape_bh *bh;
891         char *b_data;
892         int b_count;
893         
894         /*
895          *      Pipeline parameters.
896          *
897          *      To accomplish non-pipelined mode, we simply set the following
898          *      variables to zero (or NULL, where appropriate).
899          */
900         /* Number of currently used stages */
901         int nr_stages;
902         /* Number of pending stages */
903         int nr_pending_stages;
904         /* We will not allocate more than this number of stages */
905         int max_stages, min_pipeline, max_pipeline;
906         /* The first stage which will be removed from the pipeline */
907         idetape_stage_t *first_stage;
908         /* The currently active stage */
909         idetape_stage_t *active_stage;
910         /* Will be serviced after the currently active request */
911         idetape_stage_t *next_stage;
912         /* New requests will be added to the pipeline here */
913         idetape_stage_t *last_stage;
914         /* Optional free stage which we can use */
915         idetape_stage_t *cache_stage;
916         int pages_per_stage;
917         /* Wasted space in each stage */
918         int excess_bh_size;
919
920         /* Status/Action flags: long for set_bit */
921         unsigned long flags;
922         /* protects the ide-tape queue */
923         spinlock_t spinlock;
924
925         /*
926          * Measures average tape speed
927          */
928         unsigned long avg_time;
929         int avg_size;
930         int avg_speed;
931
932         /* last sense information */
933         idetape_request_sense_result_t sense;
934
935         char vendor_id[10];
936         char product_id[18];
937         char firmware_revision[6];
938         int firmware_revision_num;
939
940         /* the door is currently locked */
941         int door_locked;
942         /* the tape hardware is write protected */
943         char drv_write_prot;
944         /* the tape is write protected (hardware or opened as read-only) */
945         char write_prot;
946
947         /*
948          * Limit the number of times a request can
949          * be postponed, to avoid an infinite postpone
950          * deadlock.
951          */
952         /* request postpone count limit */
953         int postpone_cnt;
954
955         /*
956          * Measures number of frames:
957          *
958          * 1. written/read to/from the driver pipeline (pipeline_head).
959          * 2. written/read to/from the tape buffers (idetape_bh).
960          * 3. written/read by the tape to/from the media (tape_head).
961          */
962         int pipeline_head;
963         int buffer_head;
964         int tape_head;
965         int last_tape_head;
966
967         /*
968          * Speed control at the tape buffers input/output
969          */
970         unsigned long insert_time;
971         int insert_size;
972         int insert_speed;
973         int max_insert_speed;
974         int measure_insert_time;
975
976         /*
977          * Measure tape still time, in milliseconds
978          */
979         unsigned long tape_still_time_begin;
980         int tape_still_time;
981
982         /*
983          * Speed regulation negative feedback loop
984          */
985         int speed_control;
986         int pipeline_head_speed;
987         int controlled_pipeline_head_speed;
988         int uncontrolled_pipeline_head_speed;
989         int controlled_last_pipeline_head;
990         int uncontrolled_last_pipeline_head;
991         unsigned long uncontrolled_pipeline_head_time;
992         unsigned long controlled_pipeline_head_time;
993         int controlled_previous_pipeline_head;
994         int uncontrolled_previous_pipeline_head;
995         unsigned long controlled_previous_head_time;
996         unsigned long uncontrolled_previous_head_time;
997         int restart_speed_control_req;
998
999         /*
1000          * Debug_level determines amount of debugging output;
1001          * can be changed using /proc/ide/hdx/settings
1002          * 0 : almost no debugging output
1003          * 1 : 0+output errors only
1004          * 2 : 1+output all sensekey/asc
1005          * 3 : 2+follow all chrdev related procedures
1006          * 4 : 3+follow all procedures
1007          * 5 : 4+include pc_stack rq_stack info
1008          * 6 : 5+USE_COUNT updates
1009          */
1010          int debug_level; 
1011 } idetape_tape_t;
1012
1013 static DEFINE_MUTEX(idetape_ref_mutex);
1014
1015 static struct class *idetape_sysfs_class;
1016
1017 #define to_ide_tape(obj) container_of(obj, struct ide_tape_obj, kref)
1018
1019 #define ide_tape_g(disk) \
1020         container_of((disk)->private_data, struct ide_tape_obj, driver)
1021
1022 static struct ide_tape_obj *ide_tape_get(struct gendisk *disk)
1023 {
1024         struct ide_tape_obj *tape = NULL;
1025
1026         mutex_lock(&idetape_ref_mutex);
1027         tape = ide_tape_g(disk);
1028         if (tape)
1029                 kref_get(&tape->kref);
1030         mutex_unlock(&idetape_ref_mutex);
1031         return tape;
1032 }
1033
1034 static void ide_tape_release(struct kref *);
1035
1036 static void ide_tape_put(struct ide_tape_obj *tape)
1037 {
1038         mutex_lock(&idetape_ref_mutex);
1039         kref_put(&tape->kref, ide_tape_release);
1040         mutex_unlock(&idetape_ref_mutex);
1041 }
1042
1043 /*
1044  *      Tape door status
1045  */
1046 #define DOOR_UNLOCKED                   0
1047 #define DOOR_LOCKED                     1
1048 #define DOOR_EXPLICITLY_LOCKED          2
1049
1050 /*
1051  *      Tape flag bits values.
1052  */
1053 #define IDETAPE_IGNORE_DSC              0
1054 #define IDETAPE_ADDRESS_VALID           1       /* 0 When the tape position is unknown */
1055 #define IDETAPE_BUSY                    2       /* Device already opened */
1056 #define IDETAPE_PIPELINE_ERROR          3       /* Error detected in a pipeline stage */
1057 #define IDETAPE_DETECT_BS               4       /* Attempt to auto-detect the current user block size */
1058 #define IDETAPE_FILEMARK                5       /* Currently on a filemark */
1059 #define IDETAPE_DRQ_INTERRUPT           6       /* DRQ interrupt device */
1060 #define IDETAPE_READ_ERROR              7
1061 #define IDETAPE_PIPELINE_ACTIVE         8       /* pipeline active */
1062 /* 0 = no tape is loaded, so we don't rewind after ejecting */
1063 #define IDETAPE_MEDIUM_PRESENT          9
1064
1065 /*
1066  *      Supported ATAPI tape drives packet commands
1067  */
1068 #define IDETAPE_TEST_UNIT_READY_CMD     0x00
1069 #define IDETAPE_REWIND_CMD              0x01
1070 #define IDETAPE_REQUEST_SENSE_CMD       0x03
1071 #define IDETAPE_READ_CMD                0x08
1072 #define IDETAPE_WRITE_CMD               0x0a
1073 #define IDETAPE_WRITE_FILEMARK_CMD      0x10
1074 #define IDETAPE_SPACE_CMD               0x11
1075 #define IDETAPE_INQUIRY_CMD             0x12
1076 #define IDETAPE_ERASE_CMD               0x19
1077 #define IDETAPE_MODE_SENSE_CMD          0x1a
1078 #define IDETAPE_MODE_SELECT_CMD         0x15
1079 #define IDETAPE_LOAD_UNLOAD_CMD         0x1b
1080 #define IDETAPE_PREVENT_CMD             0x1e
1081 #define IDETAPE_LOCATE_CMD              0x2b
1082 #define IDETAPE_READ_POSITION_CMD       0x34
1083 #define IDETAPE_READ_BUFFER_CMD         0x3c
1084 #define IDETAPE_SET_SPEED_CMD           0xbb
1085
1086 /*
1087  *      Some defines for the READ BUFFER command
1088  */
1089 #define IDETAPE_RETRIEVE_FAULTY_BLOCK   6
1090
1091 /*
1092  *      Some defines for the SPACE command
1093  */
1094 #define IDETAPE_SPACE_OVER_FILEMARK     1
1095 #define IDETAPE_SPACE_TO_EOD            3
1096
1097 /*
1098  *      Some defines for the LOAD UNLOAD command
1099  */
1100 #define IDETAPE_LU_LOAD_MASK            1
1101 #define IDETAPE_LU_RETENSION_MASK       2
1102 #define IDETAPE_LU_EOT_MASK             4
1103
1104 /*
1105  *      Special requests for our block device strategy routine.
1106  *
1107  *      In order to service a character device command, we add special
1108  *      requests to the tail of our block device request queue and wait
1109  *      for their completion.
1110  */
1111
1112 enum {
1113         REQ_IDETAPE_PC1         = (1 << 0), /* packet command (first stage) */
1114         REQ_IDETAPE_PC2         = (1 << 1), /* packet command (second stage) */
1115         REQ_IDETAPE_READ        = (1 << 2),
1116         REQ_IDETAPE_WRITE       = (1 << 3),
1117         REQ_IDETAPE_READ_BUFFER = (1 << 4),
1118 };
1119
1120 /*
1121  *      Error codes which are returned in rq->errors to the higher part
1122  *      of the driver.
1123  */
1124 #define IDETAPE_ERROR_GENERAL           101
1125 #define IDETAPE_ERROR_FILEMARK          102
1126 #define IDETAPE_ERROR_EOD               103
1127
1128 /*
1129  *      The following is used to format the general configuration word of
1130  *      the ATAPI IDENTIFY DEVICE command.
1131  */
1132 struct idetape_id_gcw { 
1133         unsigned packet_size            :2;     /* Packet Size */
1134         unsigned reserved234            :3;     /* Reserved */
1135         unsigned drq_type               :2;     /* Command packet DRQ type */
1136         unsigned removable              :1;     /* Removable media */
1137         unsigned device_type            :5;     /* Device type */
1138         unsigned reserved13             :1;     /* Reserved */
1139         unsigned protocol               :2;     /* Protocol type */
1140 };
1141
1142 /*
1143  *      INQUIRY packet command - Data Format (From Table 6-8 of QIC-157C)
1144  */
1145 typedef struct {
1146         unsigned        device_type     :5;     /* Peripheral Device Type */
1147         unsigned        reserved0_765   :3;     /* Peripheral Qualifier - Reserved */
1148         unsigned        reserved1_6t0   :7;     /* Reserved */
1149         unsigned        rmb             :1;     /* Removable Medium Bit */
1150         unsigned        ansi_version    :3;     /* ANSI Version */
1151         unsigned        ecma_version    :3;     /* ECMA Version */
1152         unsigned        iso_version     :2;     /* ISO Version */
1153         unsigned        response_format :4;     /* Response Data Format */
1154         unsigned        reserved3_45    :2;     /* Reserved */
1155         unsigned        reserved3_6     :1;     /* TrmIOP - Reserved */
1156         unsigned        reserved3_7     :1;     /* AENC - Reserved */
1157         __u8            additional_length;      /* Additional Length (total_length-4) */
1158         __u8            rsv5, rsv6, rsv7;       /* Reserved */
1159         __u8            vendor_id[8];           /* Vendor Identification */
1160         __u8            product_id[16];         /* Product Identification */
1161         __u8            revision_level[4];      /* Revision Level */
1162         __u8            vendor_specific[20];    /* Vendor Specific - Optional */
1163         __u8            reserved56t95[40];      /* Reserved - Optional */
1164                                                 /* Additional information may be returned */
1165 } idetape_inquiry_result_t;
1166
1167 /*
1168  *      READ POSITION packet command - Data Format (From Table 6-57)
1169  */
1170 typedef struct {
1171         unsigned        reserved0_10    :2;     /* Reserved */
1172         unsigned        bpu             :1;     /* Block Position Unknown */    
1173         unsigned        reserved0_543   :3;     /* Reserved */
1174         unsigned        eop             :1;     /* End Of Partition */
1175         unsigned        bop             :1;     /* Beginning Of Partition */
1176         u8              partition;              /* Partition Number */
1177         u8              reserved2, reserved3;   /* Reserved */
1178         u32             first_block;            /* First Block Location */
1179         u32             last_block;             /* Last Block Location (Optional) */
1180         u8              reserved12;             /* Reserved */
1181         u8              blocks_in_buffer[3];    /* Blocks In Buffer - (Optional) */
1182         u32             bytes_in_buffer;        /* Bytes In Buffer (Optional) */
1183 } idetape_read_position_result_t;
1184
1185 /*
1186  *      Follows structures which are related to the SELECT SENSE / MODE SENSE
1187  *      packet commands. Those packet commands are still not supported
1188  *      by ide-tape.
1189  */
1190 #define IDETAPE_BLOCK_DESCRIPTOR        0
1191 #define IDETAPE_CAPABILITIES_PAGE       0x2a
1192 #define IDETAPE_PARAMTR_PAGE            0x2b   /* Onstream DI-x0 only */
1193 #define IDETAPE_BLOCK_SIZE_PAGE         0x30
1194 #define IDETAPE_BUFFER_FILLING_PAGE     0x33
1195
1196 /*
1197  *      Mode Parameter Header for the MODE SENSE packet command
1198  */
1199 typedef struct {
1200         __u8    mode_data_length;       /* Length of the following data transfer */
1201         __u8    medium_type;            /* Medium Type */
1202         __u8    dsp;                    /* Device Specific Parameter */
1203         __u8    bdl;                    /* Block Descriptor Length */
1204 #if 0
1205         /* data transfer page */
1206         __u8    page_code       :6;
1207         __u8    reserved0_6     :1;
1208         __u8    ps              :1;     /* parameters saveable */
1209         __u8    page_length;            /* page Length == 0x02 */
1210         __u8    reserved2;
1211         __u8    read32k         :1;     /* 32k blk size (data only) */
1212         __u8    read32k5        :1;     /* 32.5k blk size (data&AUX) */
1213         __u8    reserved3_23    :2;
1214         __u8    write32k        :1;     /* 32k blk size (data only) */
1215         __u8    write32k5       :1;     /* 32.5k blk size (data&AUX) */
1216         __u8    reserved3_6     :1;
1217         __u8    streaming       :1;     /* streaming mode enable */
1218 #endif
1219 } idetape_mode_parameter_header_t;
1220
1221 /*
1222  *      Mode Parameter Block Descriptor the MODE SENSE packet command
1223  *
1224  *      Support for block descriptors is optional.
1225  */
1226 typedef struct {
1227         __u8            density_code;           /* Medium density code */
1228         __u8            blocks[3];              /* Number of blocks */
1229         __u8            reserved4;              /* Reserved */
1230         __u8            length[3];              /* Block Length */
1231 } idetape_parameter_block_descriptor_t;
1232
1233 /*
1234  *      The Data Compression Page, as returned by the MODE SENSE packet command.
1235  */
1236 typedef struct {
1237         unsigned        page_code       :6;     /* Page Code - Should be 0xf */
1238         unsigned        reserved0       :1;     /* Reserved */
1239         unsigned        ps              :1;
1240         __u8            page_length;            /* Page Length - Should be 14 */
1241         unsigned        reserved2       :6;     /* Reserved */
1242         unsigned        dcc             :1;     /* Data Compression Capable */
1243         unsigned        dce             :1;     /* Data Compression Enable */
1244         unsigned        reserved3       :5;     /* Reserved */
1245         unsigned        red             :2;     /* Report Exception on Decompression */
1246         unsigned        dde             :1;     /* Data Decompression Enable */
1247         __u32           ca;                     /* Compression Algorithm */
1248         __u32           da;                     /* Decompression Algorithm */
1249         __u8            reserved[4];            /* Reserved */
1250 } idetape_data_compression_page_t;
1251
1252 /*
1253  *      The Medium Partition Page, as returned by the MODE SENSE packet command.
1254  */
1255 typedef struct {
1256         unsigned        page_code       :6;     /* Page Code - Should be 0x11 */
1257         unsigned        reserved1_6     :1;     /* Reserved */
1258         unsigned        ps              :1;
1259         __u8            page_length;            /* Page Length - Should be 6 */
1260         __u8            map;                    /* Maximum Additional Partitions - Should be 0 */
1261         __u8            apd;                    /* Additional Partitions Defined - Should be 0 */
1262         unsigned        reserved4_012   :3;     /* Reserved */
1263         unsigned        psum            :2;     /* Should be 0 */
1264         unsigned        idp             :1;     /* Should be 0 */
1265         unsigned        sdp             :1;     /* Should be 0 */
1266         unsigned        fdp             :1;     /* Fixed Data Partitions */
1267         __u8            mfr;                    /* Medium Format Recognition */
1268         __u8            reserved[2];            /* Reserved */
1269 } idetape_medium_partition_page_t;
1270
1271 /*
1272  *      Run time configurable parameters.
1273  */
1274 typedef struct {
1275         int     dsc_rw_frequency;
1276         int     dsc_media_access_frequency;
1277         int     nr_stages;
1278 } idetape_config_t;
1279
1280 /*
1281  *      The variables below are used for the character device interface.
1282  *      Additional state variables are defined in our ide_drive_t structure.
1283  */
1284 static struct ide_tape_obj * idetape_devs[MAX_HWIFS * MAX_DRIVES];
1285
1286 #define ide_tape_f(file) ((file)->private_data)
1287
1288 static struct ide_tape_obj *ide_tape_chrdev_get(unsigned int i)
1289 {
1290         struct ide_tape_obj *tape = NULL;
1291
1292         mutex_lock(&idetape_ref_mutex);
1293         tape = idetape_devs[i];
1294         if (tape)
1295                 kref_get(&tape->kref);
1296         mutex_unlock(&idetape_ref_mutex);
1297         return tape;
1298 }
1299
1300 /*
1301  *      Function declarations
1302  *
1303  */
1304 static int idetape_chrdev_release (struct inode *inode, struct file *filp);
1305 static void idetape_write_release (ide_drive_t *drive, unsigned int minor);
1306
1307 /*
1308  * Too bad. The drive wants to send us data which we are not ready to accept.
1309  * Just throw it away.
1310  */
1311 static void idetape_discard_data (ide_drive_t *drive, unsigned int bcount)
1312 {
1313         while (bcount--)
1314                 (void) HWIF(drive)->INB(IDE_DATA_REG);
1315 }
1316
1317 static void idetape_input_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
1318 {
1319         struct idetape_bh *bh = pc->bh;
1320         int count;
1321
1322         while (bcount) {
1323 #if IDETAPE_DEBUG_BUGS
1324                 if (bh == NULL) {
1325                         printk(KERN_ERR "ide-tape: bh == NULL in "
1326                                 "idetape_input_buffers\n");
1327                         idetape_discard_data(drive, bcount);
1328                         return;
1329                 }
1330 #endif /* IDETAPE_DEBUG_BUGS */
1331                 count = min((unsigned int)(bh->b_size - atomic_read(&bh->b_count)), bcount);
1332                 HWIF(drive)->atapi_input_bytes(drive, bh->b_data + atomic_read(&bh->b_count), count);
1333                 bcount -= count;
1334                 atomic_add(count, &bh->b_count);
1335                 if (atomic_read(&bh->b_count) == bh->b_size) {
1336                         bh = bh->b_reqnext;
1337                         if (bh)
1338                                 atomic_set(&bh->b_count, 0);
1339                 }
1340         }
1341         pc->bh = bh;
1342 }
1343
1344 static void idetape_output_buffers (ide_drive_t *drive, idetape_pc_t *pc, unsigned int bcount)
1345 {
1346         struct idetape_bh *bh = pc->bh;
1347         int count;
1348
1349         while (bcount) {
1350 #if IDETAPE_DEBUG_BUGS
1351                 if (bh == NULL) {
1352                         printk(KERN_ERR "ide-tape: bh == NULL in "
1353                                 "idetape_output_buffers\n");
1354                         return;
1355                 }
1356 #endif /* IDETAPE_DEBUG_BUGS */
1357                 count = min((unsigned int)pc->b_count, (unsigned int)bcount);
1358                 HWIF(drive)->atapi_output_bytes(drive, pc->b_data, count);
1359                 bcount -= count;
1360                 pc->b_data += count;
1361                 pc->b_count -= count;
1362                 if (!pc->b_count) {
1363                         pc->bh = bh = bh->b_reqnext;
1364                         if (bh) {
1365                                 pc->b_data = bh->b_data;
1366                                 pc->b_count = atomic_read(&bh->b_count);
1367                         }
1368                 }
1369         }
1370 }
1371
1372 static void idetape_update_buffers (idetape_pc_t *pc)
1373 {
1374         struct idetape_bh *bh = pc->bh;
1375         int count;
1376         unsigned int bcount = pc->actually_transferred;
1377
1378         if (test_bit(PC_WRITING, &pc->flags))
1379                 return;
1380         while (bcount) {
1381 #if IDETAPE_DEBUG_BUGS
1382                 if (bh == NULL) {
1383                         printk(KERN_ERR "ide-tape: bh == NULL in "
1384                                 "idetape_update_buffers\n");
1385                         return;
1386                 }
1387 #endif /* IDETAPE_DEBUG_BUGS */
1388                 count = min((unsigned int)bh->b_size, (unsigned int)bcount);
1389                 atomic_set(&bh->b_count, count);
1390                 if (atomic_read(&bh->b_count) == bh->b_size)
1391                         bh = bh->b_reqnext;
1392                 bcount -= count;
1393         }
1394         pc->bh = bh;
1395 }
1396
1397 /*
1398  *      idetape_next_pc_storage returns a pointer to a place in which we can
1399  *      safely store a packet command, even though we intend to leave the
1400  *      driver. A storage space for a maximum of IDETAPE_PC_STACK packet
1401  *      commands is allocated at initialization time.
1402  */
1403 static idetape_pc_t *idetape_next_pc_storage (ide_drive_t *drive)
1404 {
1405         idetape_tape_t *tape = drive->driver_data;
1406
1407 #if IDETAPE_DEBUG_LOG
1408         if (tape->debug_level >= 5)
1409                 printk(KERN_INFO "ide-tape: pc_stack_index=%d\n",
1410                         tape->pc_stack_index);
1411 #endif /* IDETAPE_DEBUG_LOG */
1412         if (tape->pc_stack_index == IDETAPE_PC_STACK)
1413                 tape->pc_stack_index=0;
1414         return (&tape->pc_stack[tape->pc_stack_index++]);
1415 }
1416
1417 /*
1418  *      idetape_next_rq_storage is used along with idetape_next_pc_storage.
1419  *      Since we queue packet commands in the request queue, we need to
1420  *      allocate a request, along with the allocation of a packet command.
1421  */
1422  
1423 /**************************************************************
1424  *                                                            *
1425  *  This should get fixed to use kmalloc(.., GFP_ATOMIC)      *
1426  *  followed later on by kfree().   -ml                       *
1427  *                                                            *
1428  **************************************************************/
1429  
1430 static struct request *idetape_next_rq_storage (ide_drive_t *drive)
1431 {
1432         idetape_tape_t *tape = drive->driver_data;
1433
1434 #if IDETAPE_DEBUG_LOG
1435         if (tape->debug_level >= 5)
1436                 printk(KERN_INFO "ide-tape: rq_stack_index=%d\n",
1437                         tape->rq_stack_index);
1438 #endif /* IDETAPE_DEBUG_LOG */
1439         if (tape->rq_stack_index == IDETAPE_PC_STACK)
1440                 tape->rq_stack_index=0;
1441         return (&tape->rq_stack[tape->rq_stack_index++]);
1442 }
1443
1444 /*
1445  *      idetape_init_pc initializes a packet command.
1446  */
1447 static void idetape_init_pc (idetape_pc_t *pc)
1448 {
1449         memset(pc->c, 0, 12);
1450         pc->retries = 0;
1451         pc->flags = 0;
1452         pc->request_transfer = 0;
1453         pc->buffer = pc->pc_buffer;
1454         pc->buffer_size = IDETAPE_PC_BUFFER_SIZE;
1455         pc->bh = NULL;
1456         pc->b_data = NULL;
1457 }
1458
1459 /*
1460  *      idetape_analyze_error is called on each failed packet command retry
1461  *      to analyze the request sense. We currently do not utilize this
1462  *      information.
1463  */
1464 static void idetape_analyze_error (ide_drive_t *drive, idetape_request_sense_result_t *result)
1465 {
1466         idetape_tape_t *tape = drive->driver_data;
1467         idetape_pc_t *pc = tape->failed_pc;
1468
1469         tape->sense     = *result;
1470         tape->sense_key = result->sense_key;
1471         tape->asc       = result->asc;
1472         tape->ascq      = result->ascq;
1473 #if IDETAPE_DEBUG_LOG
1474         /*
1475          *      Without debugging, we only log an error if we decided to
1476          *      give up retrying.
1477          */
1478         if (tape->debug_level >= 1)
1479                 printk(KERN_INFO "ide-tape: pc = %x, sense key = %x, "
1480                         "asc = %x, ascq = %x\n",
1481                         pc->c[0], result->sense_key,
1482                         result->asc, result->ascq);
1483 #endif /* IDETAPE_DEBUG_LOG */
1484
1485         /*
1486          *      Correct pc->actually_transferred by asking the tape.
1487          */
1488         if (test_bit(PC_DMA_ERROR, &pc->flags)) {
1489                 pc->actually_transferred = pc->request_transfer - tape->tape_block_size * ntohl(get_unaligned(&result->information));
1490                 idetape_update_buffers(pc);
1491         }
1492
1493         /*
1494          * If error was the result of a zero-length read or write command,
1495          * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
1496          * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
1497          */
1498         if ((pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD)
1499             && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) { /* length==0 */
1500                 if (result->sense_key == 5) {
1501                         /* don't report an error, everything's ok */
1502                         pc->error = 0;
1503                         /* don't retry read/write */
1504                         set_bit(PC_ABORT, &pc->flags);
1505                 }
1506         }
1507         if (pc->c[0] == IDETAPE_READ_CMD && result->filemark) {
1508                 pc->error = IDETAPE_ERROR_FILEMARK;
1509                 set_bit(PC_ABORT, &pc->flags);
1510         }
1511         if (pc->c[0] == IDETAPE_WRITE_CMD) {
1512                 if (result->eom ||
1513                     (result->sense_key == 0xd && result->asc == 0x0 &&
1514                      result->ascq == 0x2)) {
1515                         pc->error = IDETAPE_ERROR_EOD;
1516                         set_bit(PC_ABORT, &pc->flags);
1517                 }
1518         }
1519         if (pc->c[0] == IDETAPE_READ_CMD || pc->c[0] == IDETAPE_WRITE_CMD) {
1520                 if (result->sense_key == 8) {
1521                         pc->error = IDETAPE_ERROR_EOD;
1522                         set_bit(PC_ABORT, &pc->flags);
1523                 }
1524                 if (!test_bit(PC_ABORT, &pc->flags) &&
1525                     pc->actually_transferred)
1526                         pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
1527         }
1528 }
1529
1530 /*
1531  * idetape_active_next_stage will declare the next stage as "active".
1532  */
1533 static void idetape_active_next_stage (ide_drive_t *drive)
1534 {
1535         idetape_tape_t *tape = drive->driver_data;
1536         idetape_stage_t *stage = tape->next_stage;
1537         struct request *rq = &stage->rq;
1538
1539 #if IDETAPE_DEBUG_LOG
1540         if (tape->debug_level >= 4)
1541                 printk(KERN_INFO "ide-tape: Reached idetape_active_next_stage\n");
1542 #endif /* IDETAPE_DEBUG_LOG */
1543 #if IDETAPE_DEBUG_BUGS
1544         if (stage == NULL) {
1545                 printk(KERN_ERR "ide-tape: bug: Trying to activate a non existing stage\n");
1546                 return;
1547         }
1548 #endif /* IDETAPE_DEBUG_BUGS */ 
1549
1550         rq->rq_disk = tape->disk;
1551         rq->buffer = NULL;
1552         rq->special = (void *)stage->bh;
1553         tape->active_data_request = rq;
1554         tape->active_stage = stage;
1555         tape->next_stage = stage->next;
1556 }
1557
1558 /*
1559  *      idetape_increase_max_pipeline_stages is a part of the feedback
1560  *      loop which tries to find the optimum number of stages. In the
1561  *      feedback loop, we are starting from a minimum maximum number of
1562  *      stages, and if we sense that the pipeline is empty, we try to
1563  *      increase it, until we reach the user compile time memory limit.
1564  */
1565 static void idetape_increase_max_pipeline_stages (ide_drive_t *drive)
1566 {
1567         idetape_tape_t *tape = drive->driver_data;
1568         int increase = (tape->max_pipeline - tape->min_pipeline) / 10;
1569         
1570 #if IDETAPE_DEBUG_LOG
1571         if (tape->debug_level >= 4)
1572                 printk (KERN_INFO "ide-tape: Reached idetape_increase_max_pipeline_stages\n");
1573 #endif /* IDETAPE_DEBUG_LOG */
1574
1575         tape->max_stages += max(increase, 1);
1576         tape->max_stages = max(tape->max_stages, tape->min_pipeline);
1577         tape->max_stages = min(tape->max_stages, tape->max_pipeline);
1578 }
1579
1580 /*
1581  *      idetape_kfree_stage calls kfree to completely free a stage, along with
1582  *      its related buffers.
1583  */
1584 static void __idetape_kfree_stage (idetape_stage_t *stage)
1585 {
1586         struct idetape_bh *prev_bh, *bh = stage->bh;
1587         int size;
1588
1589         while (bh != NULL) {
1590                 if (bh->b_data != NULL) {
1591                         size = (int) bh->b_size;
1592                         while (size > 0) {
1593                                 free_page((unsigned long) bh->b_data);
1594                                 size -= PAGE_SIZE;
1595                                 bh->b_data += PAGE_SIZE;
1596                         }
1597                 }
1598                 prev_bh = bh;
1599                 bh = bh->b_reqnext;
1600                 kfree(prev_bh);
1601         }
1602         kfree(stage);
1603 }
1604
1605 static void idetape_kfree_stage (idetape_tape_t *tape, idetape_stage_t *stage)
1606 {
1607         __idetape_kfree_stage(stage);
1608 }
1609
1610 /*
1611  *      idetape_remove_stage_head removes tape->first_stage from the pipeline.
1612  *      The caller should avoid race conditions.
1613  */
1614 static void idetape_remove_stage_head (ide_drive_t *drive)
1615 {
1616         idetape_tape_t *tape = drive->driver_data;
1617         idetape_stage_t *stage;
1618         
1619 #if IDETAPE_DEBUG_LOG
1620         if (tape->debug_level >= 4)
1621                 printk(KERN_INFO "ide-tape: Reached idetape_remove_stage_head\n");
1622 #endif /* IDETAPE_DEBUG_LOG */
1623 #if IDETAPE_DEBUG_BUGS
1624         if (tape->first_stage == NULL) {
1625                 printk(KERN_ERR "ide-tape: bug: tape->first_stage is NULL\n");
1626                 return;         
1627         }
1628         if (tape->active_stage == tape->first_stage) {
1629                 printk(KERN_ERR "ide-tape: bug: Trying to free our active pipeline stage\n");
1630                 return;
1631         }
1632 #endif /* IDETAPE_DEBUG_BUGS */
1633         stage = tape->first_stage;
1634         tape->first_stage = stage->next;
1635         idetape_kfree_stage(tape, stage);
1636         tape->nr_stages--;
1637         if (tape->first_stage == NULL) {
1638                 tape->last_stage = NULL;
1639 #if IDETAPE_DEBUG_BUGS
1640                 if (tape->next_stage != NULL)
1641                         printk(KERN_ERR "ide-tape: bug: tape->next_stage != NULL\n");
1642                 if (tape->nr_stages)
1643                         printk(KERN_ERR "ide-tape: bug: nr_stages should be 0 now\n");
1644 #endif /* IDETAPE_DEBUG_BUGS */
1645         }
1646 }
1647
1648 /*
1649  * This will free all the pipeline stages starting from new_last_stage->next
1650  * to the end of the list, and point tape->last_stage to new_last_stage.
1651  */
1652 static void idetape_abort_pipeline(ide_drive_t *drive,
1653                                    idetape_stage_t *new_last_stage)
1654 {
1655         idetape_tape_t *tape = drive->driver_data;
1656         idetape_stage_t *stage = new_last_stage->next;
1657         idetape_stage_t *nstage;
1658
1659 #if IDETAPE_DEBUG_LOG
1660         if (tape->debug_level >= 4)
1661                 printk(KERN_INFO "ide-tape: %s: idetape_abort_pipeline called\n", tape->name);
1662 #endif
1663         while (stage) {
1664                 nstage = stage->next;
1665                 idetape_kfree_stage(tape, stage);
1666                 --tape->nr_stages;
1667                 --tape->nr_pending_stages;
1668                 stage = nstage;
1669         }
1670         if (new_last_stage)
1671                 new_last_stage->next = NULL;
1672         tape->last_stage = new_last_stage;
1673         tape->next_stage = NULL;
1674 }
1675
1676 /*
1677  *      idetape_end_request is used to finish servicing a request, and to
1678  *      insert a pending pipeline request into the main device queue.
1679  */
1680 static int idetape_end_request(ide_drive_t *drive, int uptodate, int nr_sects)
1681 {
1682         struct request *rq = HWGROUP(drive)->rq;
1683         idetape_tape_t *tape = drive->driver_data;
1684         unsigned long flags;
1685         int error;
1686         int remove_stage = 0;
1687         idetape_stage_t *active_stage;
1688
1689 #if IDETAPE_DEBUG_LOG
1690         if (tape->debug_level >= 4)
1691         printk(KERN_INFO "ide-tape: Reached idetape_end_request\n");
1692 #endif /* IDETAPE_DEBUG_LOG */
1693
1694         switch (uptodate) {
1695                 case 0: error = IDETAPE_ERROR_GENERAL; break;
1696                 case 1: error = 0; break;
1697                 default: error = uptodate;
1698         }
1699         rq->errors = error;
1700         if (error)
1701                 tape->failed_pc = NULL;
1702
1703         spin_lock_irqsave(&tape->spinlock, flags);
1704
1705         /* The request was a pipelined data transfer request */
1706         if (tape->active_data_request == rq) {
1707                 active_stage = tape->active_stage;
1708                 tape->active_stage = NULL;
1709                 tape->active_data_request = NULL;
1710                 tape->nr_pending_stages--;
1711                 if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
1712                         remove_stage = 1;
1713                         if (error) {
1714                                 set_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
1715                                 if (error == IDETAPE_ERROR_EOD)
1716                                         idetape_abort_pipeline(drive, active_stage);
1717                         }
1718                 } else if (rq->cmd[0] & REQ_IDETAPE_READ) {
1719                         if (error == IDETAPE_ERROR_EOD) {
1720                                 set_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
1721                                 idetape_abort_pipeline(drive, active_stage);
1722                         }
1723                 }
1724                 if (tape->next_stage != NULL) {
1725                         idetape_active_next_stage(drive);
1726
1727                         /*
1728                          * Insert the next request into the request queue.
1729                          */
1730                         (void) ide_do_drive_cmd(drive, tape->active_data_request, ide_end);
1731                 } else if (!error) {
1732                                 idetape_increase_max_pipeline_stages(drive);
1733                 }
1734         }
1735         ide_end_drive_cmd(drive, 0, 0);
1736 //      blkdev_dequeue_request(rq);
1737 //      drive->rq = NULL;
1738 //      end_that_request_last(rq);
1739
1740         if (remove_stage)
1741                 idetape_remove_stage_head(drive);
1742         if (tape->active_data_request == NULL)
1743                 clear_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
1744         spin_unlock_irqrestore(&tape->spinlock, flags);
1745         return 0;
1746 }
1747
1748 static ide_startstop_t idetape_request_sense_callback (ide_drive_t *drive)
1749 {
1750         idetape_tape_t *tape = drive->driver_data;
1751
1752 #if IDETAPE_DEBUG_LOG
1753         if (tape->debug_level >= 4)
1754                 printk(KERN_INFO "ide-tape: Reached idetape_request_sense_callback\n");
1755 #endif /* IDETAPE_DEBUG_LOG */
1756         if (!tape->pc->error) {
1757                 idetape_analyze_error(drive, (idetape_request_sense_result_t *) tape->pc->buffer);
1758                 idetape_end_request(drive, 1, 0);
1759         } else {
1760                 printk(KERN_ERR "ide-tape: Error in REQUEST SENSE itself - Aborting request!\n");
1761                 idetape_end_request(drive, 0, 0);
1762         }
1763         return ide_stopped;
1764 }
1765
1766 static void idetape_create_request_sense_cmd (idetape_pc_t *pc)
1767 {
1768         idetape_init_pc(pc);    
1769         pc->c[0] = IDETAPE_REQUEST_SENSE_CMD;
1770         pc->c[4] = 20;
1771         pc->request_transfer = 20;
1772         pc->callback = &idetape_request_sense_callback;
1773 }
1774
1775 static void idetape_init_rq(struct request *rq, u8 cmd)
1776 {
1777         memset(rq, 0, sizeof(*rq));
1778         rq->cmd_type = REQ_TYPE_SPECIAL;
1779         rq->cmd[0] = cmd;
1780 }
1781
1782 /*
1783  *      idetape_queue_pc_head generates a new packet command request in front
1784  *      of the request queue, before the current request, so that it will be
1785  *      processed immediately, on the next pass through the driver.
1786  *
1787  *      idetape_queue_pc_head is called from the request handling part of
1788  *      the driver (the "bottom" part). Safe storage for the request should
1789  *      be allocated with idetape_next_pc_storage and idetape_next_rq_storage
1790  *      before calling idetape_queue_pc_head.
1791  *
1792  *      Memory for those requests is pre-allocated at initialization time, and
1793  *      is limited to IDETAPE_PC_STACK requests. We assume that we have enough
1794  *      space for the maximum possible number of inter-dependent packet commands.
1795  *
1796  *      The higher level of the driver - The ioctl handler and the character
1797  *      device handling functions should queue request to the lower level part
1798  *      and wait for their completion using idetape_queue_pc_tail or
1799  *      idetape_queue_rw_tail.
1800  */
1801 static void idetape_queue_pc_head (ide_drive_t *drive, idetape_pc_t *pc,struct request *rq)
1802 {
1803         struct ide_tape_obj *tape = drive->driver_data;
1804
1805         idetape_init_rq(rq, REQ_IDETAPE_PC1);
1806         rq->buffer = (char *) pc;
1807         rq->rq_disk = tape->disk;
1808         (void) ide_do_drive_cmd(drive, rq, ide_preempt);
1809 }
1810
1811 /*
1812  *      idetape_retry_pc is called when an error was detected during the
1813  *      last packet command. We queue a request sense packet command in
1814  *      the head of the request list.
1815  */
1816 static ide_startstop_t idetape_retry_pc (ide_drive_t *drive)
1817 {
1818         idetape_tape_t *tape = drive->driver_data;
1819         idetape_pc_t *pc;
1820         struct request *rq;
1821         atapi_error_t error;
1822
1823         error.all = HWIF(drive)->INB(IDE_ERROR_REG);
1824         pc = idetape_next_pc_storage(drive);
1825         rq = idetape_next_rq_storage(drive);
1826         idetape_create_request_sense_cmd(pc);
1827         set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
1828         idetape_queue_pc_head(drive, pc, rq);
1829         return ide_stopped;
1830 }
1831
1832 /*
1833  *      idetape_postpone_request postpones the current request so that
1834  *      ide.c will be able to service requests from another device on
1835  *      the same hwgroup while we are polling for DSC.
1836  */
1837 static void idetape_postpone_request (ide_drive_t *drive)
1838 {
1839         idetape_tape_t *tape = drive->driver_data;
1840
1841 #if IDETAPE_DEBUG_LOG
1842         if (tape->debug_level >= 4)
1843                 printk(KERN_INFO "ide-tape: idetape_postpone_request\n");
1844 #endif
1845         tape->postponed_rq = HWGROUP(drive)->rq;
1846         ide_stall_queue(drive, tape->dsc_polling_frequency);
1847 }
1848
1849 /*
1850  *      idetape_pc_intr is the usual interrupt handler which will be called
1851  *      during a packet command. We will transfer some of the data (as
1852  *      requested by the drive) and will re-point interrupt handler to us.
1853  *      When data transfer is finished, we will act according to the
1854  *      algorithm described before idetape_issue_packet_command.
1855  *
1856  */
1857 static ide_startstop_t idetape_pc_intr (ide_drive_t *drive)
1858 {
1859         ide_hwif_t *hwif = drive->hwif;
1860         idetape_tape_t *tape = drive->driver_data;
1861         atapi_status_t status;
1862         atapi_bcount_t bcount;
1863         atapi_ireason_t ireason;
1864         idetape_pc_t *pc = tape->pc;
1865
1866         unsigned int temp;
1867 #if SIMULATE_ERRORS
1868         static int error_sim_count = 0;
1869 #endif
1870
1871 #if IDETAPE_DEBUG_LOG
1872         if (tape->debug_level >= 4)
1873                 printk(KERN_INFO "ide-tape: Reached idetape_pc_intr "
1874                                 "interrupt handler\n");
1875 #endif /* IDETAPE_DEBUG_LOG */  
1876
1877         /* Clear the interrupt */
1878         status.all = HWIF(drive)->INB(IDE_STATUS_REG);
1879
1880         if (test_bit(PC_DMA_IN_PROGRESS, &pc->flags)) {
1881                 if (HWIF(drive)->ide_dma_end(drive) || status.b.check) {
1882                         /*
1883                          * A DMA error is sometimes expected. For example,
1884                          * if the tape is crossing a filemark during a
1885                          * READ command, it will issue an irq and position
1886                          * itself before the filemark, so that only a partial
1887                          * data transfer will occur (which causes the DMA
1888                          * error). In that case, we will later ask the tape
1889                          * how much bytes of the original request were
1890                          * actually transferred (we can't receive that
1891                          * information from the DMA engine on most chipsets).
1892                          */
1893
1894                         /*
1895                          * On the contrary, a DMA error is never expected;
1896                          * it usually indicates a hardware error or abort.
1897                          * If the tape crosses a filemark during a READ
1898                          * command, it will issue an irq and position itself
1899                          * after the filemark (not before). Only a partial
1900                          * data transfer will occur, but no DMA error.
1901                          * (AS, 19 Apr 2001)
1902                          */
1903                         set_bit(PC_DMA_ERROR, &pc->flags);
1904                 } else {
1905                         pc->actually_transferred = pc->request_transfer;
1906                         idetape_update_buffers(pc);
1907                 }
1908 #if IDETAPE_DEBUG_LOG
1909                 if (tape->debug_level >= 4)
1910                         printk(KERN_INFO "ide-tape: DMA finished\n");
1911 #endif /* IDETAPE_DEBUG_LOG */
1912         }
1913
1914         /* No more interrupts */
1915         if (!status.b.drq) {
1916 #if IDETAPE_DEBUG_LOG
1917                 if (tape->debug_level >= 2)
1918                         printk(KERN_INFO "ide-tape: Packet command completed, %d bytes transferred\n", pc->actually_transferred);
1919 #endif /* IDETAPE_DEBUG_LOG */
1920                 clear_bit(PC_DMA_IN_PROGRESS, &pc->flags);
1921
1922                 local_irq_enable();
1923
1924 #if SIMULATE_ERRORS
1925                 if ((pc->c[0] == IDETAPE_WRITE_CMD ||
1926                      pc->c[0] == IDETAPE_READ_CMD) &&
1927                     (++error_sim_count % 100) == 0) {
1928                         printk(KERN_INFO "ide-tape: %s: simulating error\n",
1929                                 tape->name);
1930                         status.b.check = 1;
1931                 }
1932 #endif
1933                 if (status.b.check && pc->c[0] == IDETAPE_REQUEST_SENSE_CMD)
1934                         status.b.check = 0;
1935                 if (status.b.check || test_bit(PC_DMA_ERROR, &pc->flags)) {     /* Error detected */
1936 #if IDETAPE_DEBUG_LOG
1937                         if (tape->debug_level >= 1)
1938                                 printk(KERN_INFO "ide-tape: %s: I/O error\n",
1939                                         tape->name);
1940 #endif /* IDETAPE_DEBUG_LOG */
1941                         if (pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
1942                                 printk(KERN_ERR "ide-tape: I/O error in request sense command\n");
1943                                 return ide_do_reset(drive);
1944                         }
1945 #if IDETAPE_DEBUG_LOG
1946                         if (tape->debug_level >= 1)
1947                                 printk(KERN_INFO "ide-tape: [cmd %x]: check condition\n", pc->c[0]);
1948 #endif
1949                         /* Retry operation */
1950                         return idetape_retry_pc(drive);
1951                 }
1952                 pc->error = 0;
1953                 if (test_bit(PC_WAIT_FOR_DSC, &pc->flags) &&
1954                     !status.b.dsc) {
1955                         /* Media access command */
1956                         tape->dsc_polling_start = jiffies;
1957                         tape->dsc_polling_frequency = IDETAPE_DSC_MA_FAST;
1958                         tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
1959                         /* Allow ide.c to handle other requests */
1960                         idetape_postpone_request(drive);
1961                         return ide_stopped;
1962                 }
1963                 if (tape->failed_pc == pc)
1964                         tape->failed_pc = NULL;
1965                 /* Command finished - Call the callback function */
1966                 return pc->callback(drive);
1967         }
1968         if (test_and_clear_bit(PC_DMA_IN_PROGRESS, &pc->flags)) {
1969                 printk(KERN_ERR "ide-tape: The tape wants to issue more "
1970                                 "interrupts in DMA mode\n");
1971                 printk(KERN_ERR "ide-tape: DMA disabled, reverting to PIO\n");
1972                 ide_dma_off(drive);
1973                 return ide_do_reset(drive);
1974         }
1975         /* Get the number of bytes to transfer on this interrupt. */
1976         bcount.b.high = hwif->INB(IDE_BCOUNTH_REG);
1977         bcount.b.low = hwif->INB(IDE_BCOUNTL_REG);
1978
1979         ireason.all = hwif->INB(IDE_IREASON_REG);
1980
1981         if (ireason.b.cod) {
1982                 printk(KERN_ERR "ide-tape: CoD != 0 in idetape_pc_intr\n");
1983                 return ide_do_reset(drive);
1984         }
1985         if (ireason.b.io == test_bit(PC_WRITING, &pc->flags)) {
1986                 /* Hopefully, we will never get here */
1987                 printk(KERN_ERR "ide-tape: We wanted to %s, ",
1988                         ireason.b.io ? "Write":"Read");
1989                 printk(KERN_ERR "ide-tape: but the tape wants us to %s !\n",
1990                         ireason.b.io ? "Read":"Write");
1991                 return ide_do_reset(drive);
1992         }
1993         if (!test_bit(PC_WRITING, &pc->flags)) {
1994                 /* Reading - Check that we have enough space */
1995                 temp = pc->actually_transferred + bcount.all;
1996                 if (temp > pc->request_transfer) {
1997                         if (temp > pc->buffer_size) {
1998                                 printk(KERN_ERR "ide-tape: The tape wants to send us more data than expected - discarding data\n");
1999                                 idetape_discard_data(drive, bcount.all);
2000                                 ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
2001                                 return ide_started;
2002                         }
2003 #if IDETAPE_DEBUG_LOG
2004                         if (tape->debug_level >= 2)
2005                                 printk(KERN_NOTICE "ide-tape: The tape wants to send us more data than expected - allowing transfer\n");
2006 #endif /* IDETAPE_DEBUG_LOG */
2007                 }
2008         }
2009         if (test_bit(PC_WRITING, &pc->flags)) {
2010                 if (pc->bh != NULL)
2011                         idetape_output_buffers(drive, pc, bcount.all);
2012                 else
2013                         /* Write the current buffer */
2014                         HWIF(drive)->atapi_output_bytes(drive, pc->current_position, bcount.all);
2015         } else {
2016                 if (pc->bh != NULL)
2017                         idetape_input_buffers(drive, pc, bcount.all);
2018                 else
2019                         /* Read the current buffer */
2020                         HWIF(drive)->atapi_input_bytes(drive, pc->current_position, bcount.all);
2021         }
2022         /* Update the current position */
2023         pc->actually_transferred += bcount.all;
2024         pc->current_position += bcount.all;
2025 #if IDETAPE_DEBUG_LOG
2026         if (tape->debug_level >= 2)
2027                 printk(KERN_INFO "ide-tape: [cmd %x] transferred %d bytes on that interrupt\n", pc->c[0], bcount.all);
2028 #endif
2029         /* And set the interrupt handler again */
2030         ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
2031         return ide_started;
2032 }
2033
2034 /*
2035  *      Packet Command Interface
2036  *
2037  *      The current Packet Command is available in tape->pc, and will not
2038  *      change until we finish handling it. Each packet command is associated
2039  *      with a callback function that will be called when the command is
2040  *      finished.
2041  *
2042  *      The handling will be done in three stages:
2043  *
2044  *      1.      idetape_issue_packet_command will send the packet command to the
2045  *              drive, and will set the interrupt handler to idetape_pc_intr.
2046  *
2047  *      2.      On each interrupt, idetape_pc_intr will be called. This step
2048  *              will be repeated until the device signals us that no more
2049  *              interrupts will be issued.
2050  *
2051  *      3.      ATAPI Tape media access commands have immediate status with a
2052  *              delayed process. In case of a successful initiation of a
2053  *              media access packet command, the DSC bit will be set when the
2054  *              actual execution of the command is finished. 
2055  *              Since the tape drive will not issue an interrupt, we have to
2056  *              poll for this event. In this case, we define the request as
2057  *              "low priority request" by setting rq_status to
2058  *              IDETAPE_RQ_POSTPONED,   set a timer to poll for DSC and exit
2059  *              the driver.
2060  *
2061  *              ide.c will then give higher priority to requests which
2062  *              originate from the other device, until will change rq_status
2063  *              to RQ_ACTIVE.
2064  *
2065  *      4.      When the packet command is finished, it will be checked for errors.
2066  *
2067  *      5.      In case an error was found, we queue a request sense packet
2068  *              command in front of the request queue and retry the operation
2069  *              up to IDETAPE_MAX_PC_RETRIES times.
2070  *
2071  *      6.      In case no error was found, or we decided to give up and not
2072  *              to retry again, the callback function will be called and then
2073  *              we will handle the next request.
2074  *
2075  */
2076 static ide_startstop_t idetape_transfer_pc(ide_drive_t *drive)
2077 {
2078         ide_hwif_t *hwif = drive->hwif;
2079         idetape_tape_t *tape = drive->driver_data;
2080         idetape_pc_t *pc = tape->pc;
2081         atapi_ireason_t ireason;
2082         int retries = 100;
2083         ide_startstop_t startstop;
2084
2085         if (ide_wait_stat(&startstop,drive,DRQ_STAT,BUSY_STAT,WAIT_READY)) {
2086                 printk(KERN_ERR "ide-tape: Strange, packet command initiated yet DRQ isn't asserted\n");
2087                 return startstop;
2088         }
2089         ireason.all = hwif->INB(IDE_IREASON_REG);
2090         while (retries-- && (!ireason.b.cod || ireason.b.io)) {
2091                 printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while issuing "
2092                                 "a packet command, retrying\n");
2093                 udelay(100);
2094                 ireason.all = hwif->INB(IDE_IREASON_REG);
2095                 if (retries == 0) {
2096                         printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while "
2097                                         "issuing a packet command, ignoring\n");
2098                         ireason.b.cod = 1;
2099                         ireason.b.io = 0;
2100                 }
2101         }
2102         if (!ireason.b.cod || ireason.b.io) {
2103                 printk(KERN_ERR "ide-tape: (IO,CoD) != (0,1) while issuing "
2104                                 "a packet command\n");
2105                 return ide_do_reset(drive);
2106         }
2107         /* Set the interrupt routine */
2108         ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
2109 #ifdef CONFIG_BLK_DEV_IDEDMA
2110         /* Begin DMA, if necessary */
2111         if (test_bit(PC_DMA_IN_PROGRESS, &pc->flags))
2112                 hwif->dma_start(drive);
2113 #endif
2114         /* Send the actual packet */
2115         HWIF(drive)->atapi_output_bytes(drive, pc->c, 12);
2116         return ide_started;
2117 }
2118
2119 static ide_startstop_t idetape_issue_packet_command (ide_drive_t *drive, idetape_pc_t *pc)
2120 {
2121         ide_hwif_t *hwif = drive->hwif;
2122         idetape_tape_t *tape = drive->driver_data;
2123         atapi_bcount_t bcount;
2124         int dma_ok = 0;
2125
2126 #if IDETAPE_DEBUG_BUGS
2127         if (tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD &&
2128             pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
2129                 printk(KERN_ERR "ide-tape: possible ide-tape.c bug - "
2130                         "Two request sense in serial were issued\n");
2131         }
2132 #endif /* IDETAPE_DEBUG_BUGS */
2133
2134         if (tape->failed_pc == NULL && pc->c[0] != IDETAPE_REQUEST_SENSE_CMD)
2135                 tape->failed_pc = pc;
2136         /* Set the current packet command */
2137         tape->pc = pc;
2138
2139         if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
2140             test_bit(PC_ABORT, &pc->flags)) {
2141                 /*
2142                  *      We will "abort" retrying a packet command in case
2143                  *      a legitimate error code was received (crossing a
2144                  *      filemark, or end of the media, for example).
2145                  */
2146                 if (!test_bit(PC_ABORT, &pc->flags)) {
2147                         if (!(pc->c[0] == IDETAPE_TEST_UNIT_READY_CMD &&
2148                               tape->sense_key == 2 && tape->asc == 4 &&
2149                              (tape->ascq == 1 || tape->ascq == 8))) {
2150                                 printk(KERN_ERR "ide-tape: %s: I/O error, "
2151                                                 "pc = %2x, key = %2x, "
2152                                                 "asc = %2x, ascq = %2x\n",
2153                                                 tape->name, pc->c[0],
2154                                                 tape->sense_key, tape->asc,
2155                                                 tape->ascq);
2156                         }
2157                         /* Giving up */
2158                         pc->error = IDETAPE_ERROR_GENERAL;
2159                 }
2160                 tape->failed_pc = NULL;
2161                 return pc->callback(drive);
2162         }
2163 #if IDETAPE_DEBUG_LOG
2164         if (tape->debug_level >= 2)
2165                 printk(KERN_INFO "ide-tape: Retry number - %d, cmd = %02X\n", pc->retries, pc->c[0]);
2166 #endif /* IDETAPE_DEBUG_LOG */
2167
2168         pc->retries++;
2169         /* We haven't transferred any data yet */
2170         pc->actually_transferred = 0;
2171         pc->current_position = pc->buffer;
2172         /* Request to transfer the entire buffer at once */
2173         bcount.all = pc->request_transfer;
2174
2175         if (test_and_clear_bit(PC_DMA_ERROR, &pc->flags)) {
2176                 printk(KERN_WARNING "ide-tape: DMA disabled, "
2177                                 "reverting to PIO\n");
2178                 ide_dma_off(drive);
2179         }
2180         if (test_bit(PC_DMA_RECOMMENDED, &pc->flags) && drive->using_dma)
2181                 dma_ok = !hwif->dma_setup(drive);
2182
2183         if (IDE_CONTROL_REG)
2184                 hwif->OUTB(drive->ctl, IDE_CONTROL_REG);
2185         hwif->OUTB(dma_ok ? 1 : 0, IDE_FEATURE_REG);    /* Use PIO/DMA */
2186         hwif->OUTB(bcount.b.high, IDE_BCOUNTH_REG);
2187         hwif->OUTB(bcount.b.low, IDE_BCOUNTL_REG);
2188         hwif->OUTB(drive->select.all, IDE_SELECT_REG);
2189         if (dma_ok)                     /* Will begin DMA later */
2190                 set_bit(PC_DMA_IN_PROGRESS, &pc->flags);
2191         if (test_bit(IDETAPE_DRQ_INTERRUPT, &tape->flags)) {
2192                 ide_set_handler(drive, &idetape_transfer_pc, IDETAPE_WAIT_CMD, NULL);
2193                 hwif->OUTB(WIN_PACKETCMD, IDE_COMMAND_REG);
2194                 return ide_started;
2195         } else {
2196                 hwif->OUTB(WIN_PACKETCMD, IDE_COMMAND_REG);
2197                 return idetape_transfer_pc(drive);
2198         }
2199 }
2200
2201 /*
2202  *      General packet command callback function.
2203  */
2204 static ide_startstop_t idetape_pc_callback (ide_drive_t *drive)
2205 {
2206         idetape_tape_t *tape = drive->driver_data;
2207         
2208 #if IDETAPE_DEBUG_LOG
2209         if (tape->debug_level >= 4)
2210                 printk(KERN_INFO "ide-tape: Reached idetape_pc_callback\n");
2211 #endif /* IDETAPE_DEBUG_LOG */
2212
2213         idetape_end_request(drive, tape->pc->error ? 0 : 1, 0);
2214         return ide_stopped;
2215 }
2216
2217 /*
2218  *      A mode sense command is used to "sense" tape parameters.
2219  */
2220 static void idetape_create_mode_sense_cmd (idetape_pc_t *pc, u8 page_code)
2221 {
2222         idetape_init_pc(pc);
2223         pc->c[0] = IDETAPE_MODE_SENSE_CMD;
2224         if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
2225                 pc->c[1] = 8;   /* DBD = 1 - Don't return block descriptors */
2226         pc->c[2] = page_code;
2227         /*
2228          * Changed pc->c[3] to 0 (255 will at best return unused info).
2229          *
2230          * For SCSI this byte is defined as subpage instead of high byte
2231          * of length and some IDE drives seem to interpret it this way
2232          * and return an error when 255 is used.
2233          */
2234         pc->c[3] = 0;
2235         pc->c[4] = 255;         /* (We will just discard data in that case) */
2236         if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
2237                 pc->request_transfer = 12;
2238         else if (page_code == IDETAPE_CAPABILITIES_PAGE)
2239                 pc->request_transfer = 24;
2240         else
2241                 pc->request_transfer = 50;
2242         pc->callback = &idetape_pc_callback;
2243 }
2244
2245 static void calculate_speeds(ide_drive_t *drive)
2246 {
2247         idetape_tape_t *tape = drive->driver_data;
2248         int full = 125, empty = 75;
2249
2250         if (time_after(jiffies, tape->controlled_pipeline_head_time + 120 * HZ)) {
2251                 tape->controlled_previous_pipeline_head = tape->controlled_last_pipeline_head;
2252                 tape->controlled_previous_head_time = tape->controlled_pipeline_head_time;
2253                 tape->controlled_last_pipeline_head = tape->pipeline_head;
2254                 tape->controlled_pipeline_head_time = jiffies;
2255         }
2256         if (time_after(jiffies, tape->controlled_pipeline_head_time + 60 * HZ))
2257                 tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_last_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_pipeline_head_time);
2258         else if (time_after(jiffies, tape->controlled_previous_head_time))
2259                 tape->controlled_pipeline_head_speed = (tape->pipeline_head - tape->controlled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->controlled_previous_head_time);
2260
2261         if (tape->nr_pending_stages < tape->max_stages /*- 1 */) {
2262                 /* -1 for read mode error recovery */
2263                 if (time_after(jiffies, tape->uncontrolled_previous_head_time + 10 * HZ)) {
2264                         tape->uncontrolled_pipeline_head_time = jiffies;
2265                         tape->uncontrolled_pipeline_head_speed = (tape->pipeline_head - tape->uncontrolled_previous_pipeline_head) * 32 * HZ / (jiffies - tape->uncontrolled_previous_head_time);
2266                 }
2267         } else {
2268                 tape->uncontrolled_previous_head_time = jiffies;
2269                 tape->uncontrolled_previous_pipeline_head = tape->pipeline_head;
2270                 if (time_after(jiffies, tape->uncontrolled_pipeline_head_time + 30 * HZ)) {
2271                         tape->uncontrolled_pipeline_head_time = jiffies;
2272                 }
2273         }
2274         tape->pipeline_head_speed = max(tape->uncontrolled_pipeline_head_speed, tape->controlled_pipeline_head_speed);
2275         if (tape->speed_control == 0) {
2276                 tape->max_insert_speed = 5000;
2277         } else if (tape->speed_control == 1) {
2278                 if (tape->nr_pending_stages >= tape->max_stages / 2)
2279                         tape->max_insert_speed = tape->pipeline_head_speed +
2280                                 (1100 - tape->pipeline_head_speed) * 2 * (tape->nr_pending_stages - tape->max_stages / 2) / tape->max_stages;
2281                 else
2282                         tape->max_insert_speed = 500 +
2283                                 (tape->pipeline_head_speed - 500) * 2 * tape->nr_pending_stages / tape->max_stages;
2284                 if (tape->nr_pending_stages >= tape->max_stages * 99 / 100)
2285                         tape->max_insert_speed = 5000;
2286         } else if (tape->speed_control == 2) {
2287                 tape->max_insert_speed = tape->pipeline_head_speed * empty / 100 +
2288                         (tape->pipeline_head_speed * full / 100 - tape->pipeline_head_speed * empty / 100) * tape->nr_pending_stages / tape->max_stages;
2289         } else
2290                 tape->max_insert_speed = tape->speed_control;
2291         tape->max_insert_speed = max(tape->max_insert_speed, 500);
2292 }
2293
2294 static ide_startstop_t idetape_media_access_finished (ide_drive_t *drive)
2295 {
2296         idetape_tape_t *tape = drive->driver_data;
2297         idetape_pc_t *pc = tape->pc;
2298         atapi_status_t status;
2299
2300         status.all = HWIF(drive)->INB(IDE_STATUS_REG);
2301         if (status.b.dsc) {
2302                 if (status.b.check) {
2303                         /* Error detected */
2304                         if (pc->c[0] != IDETAPE_TEST_UNIT_READY_CMD)
2305                                 printk(KERN_ERR "ide-tape: %s: I/O error, ",
2306                                                 tape->name);
2307                         /* Retry operation */
2308                         return idetape_retry_pc(drive);
2309                 }
2310                 pc->error = 0;
2311                 if (tape->failed_pc == pc)
2312                         tape->failed_pc = NULL;
2313         } else {
2314                 pc->error = IDETAPE_ERROR_GENERAL;
2315                 tape->failed_pc = NULL;
2316         }
2317         return pc->callback(drive);
2318 }
2319
2320 static ide_startstop_t idetape_rw_callback (ide_drive_t *drive)
2321 {
2322         idetape_tape_t *tape = drive->driver_data;
2323         struct request *rq = HWGROUP(drive)->rq;
2324         int blocks = tape->pc->actually_transferred / tape->tape_block_size;
2325
2326         tape->avg_size += blocks * tape->tape_block_size;
2327         tape->insert_size += blocks * tape->tape_block_size;
2328         if (tape->insert_size > 1024 * 1024)
2329                 tape->measure_insert_time = 1;
2330         if (tape->measure_insert_time) {
2331                 tape->measure_insert_time = 0;
2332                 tape->insert_time = jiffies;
2333                 tape->insert_size = 0;
2334         }
2335         if (time_after(jiffies, tape->insert_time))
2336                 tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
2337         if (time_after_eq(jiffies, tape->avg_time + HZ)) {
2338                 tape->avg_speed = tape->avg_size * HZ / (jiffies - tape->avg_time) / 1024;
2339                 tape->avg_size = 0;
2340                 tape->avg_time = jiffies;
2341         }
2342
2343 #if IDETAPE_DEBUG_LOG   
2344         if (tape->debug_level >= 4)
2345                 printk(KERN_INFO "ide-tape: Reached idetape_rw_callback\n");
2346 #endif /* IDETAPE_DEBUG_LOG */
2347
2348         tape->first_frame_position += blocks;
2349         rq->current_nr_sectors -= blocks;
2350
2351         if (!tape->pc->error)
2352                 idetape_end_request(drive, 1, 0);
2353         else
2354                 idetape_end_request(drive, tape->pc->error, 0);
2355         return ide_stopped;
2356 }
2357
2358 static void idetape_create_read_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
2359 {
2360         idetape_init_pc(pc);
2361         pc->c[0] = IDETAPE_READ_CMD;
2362         put_unaligned(htonl(length), (unsigned int *) &pc->c[1]);
2363         pc->c[1] = 1;
2364         pc->callback = &idetape_rw_callback;
2365         pc->bh = bh;
2366         atomic_set(&bh->b_count, 0);
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 static void idetape_create_read_buffer_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
2374 {
2375         int size = 32768;
2376         struct idetape_bh *p = bh;
2377
2378         idetape_init_pc(pc);
2379         pc->c[0] = IDETAPE_READ_BUFFER_CMD;
2380         pc->c[1] = IDETAPE_RETRIEVE_FAULTY_BLOCK;
2381         pc->c[7] = size >> 8;
2382         pc->c[8] = size & 0xff;
2383         pc->callback = &idetape_pc_callback;
2384         pc->bh = bh;
2385         atomic_set(&bh->b_count, 0);
2386         pc->buffer = NULL;
2387         while (p) {
2388                 atomic_set(&p->b_count, 0);
2389                 p = p->b_reqnext;
2390         }
2391         pc->request_transfer = pc->buffer_size = size;
2392 }
2393
2394 static void idetape_create_write_cmd(idetape_tape_t *tape, idetape_pc_t *pc, unsigned int length, struct idetape_bh *bh)
2395 {
2396         idetape_init_pc(pc);
2397         pc->c[0] = IDETAPE_WRITE_CMD;
2398         put_unaligned(htonl(length), (unsigned int *) &pc->c[1]);
2399         pc->c[1] = 1;
2400         pc->callback = &idetape_rw_callback;
2401         set_bit(PC_WRITING, &pc->flags);
2402         pc->bh = bh;
2403         pc->b_data = bh->b_data;
2404         pc->b_count = atomic_read(&bh->b_count);
2405         pc->buffer = NULL;
2406         pc->request_transfer = pc->buffer_size = length * tape->tape_block_size;
2407         if (pc->request_transfer == tape->stage_size)
2408                 set_bit(PC_DMA_RECOMMENDED, &pc->flags);
2409 }
2410
2411 /*
2412  * idetape_do_request is our request handling function. 
2413  */
2414 static ide_startstop_t idetape_do_request(ide_drive_t *drive,
2415                                           struct request *rq, sector_t block)
2416 {
2417         idetape_tape_t *tape = drive->driver_data;
2418         idetape_pc_t *pc = NULL;
2419         struct request *postponed_rq = tape->postponed_rq;
2420         atapi_status_t status;
2421
2422 #if IDETAPE_DEBUG_LOG
2423 #if 0
2424         if (tape->debug_level >= 5)
2425                 printk(KERN_INFO "ide-tape:  %d, "
2426                         "dev: %s, cmd: %ld, errors: %d\n",
2427                          rq->rq_disk->disk_name, rq->cmd[0], rq->errors);
2428 #endif
2429         if (tape->debug_level >= 2)
2430                 printk(KERN_INFO "ide-tape: sector: %ld, "
2431                         "nr_sectors: %ld, current_nr_sectors: %d\n",
2432                         rq->sector, rq->nr_sectors, rq->current_nr_sectors);
2433 #endif /* IDETAPE_DEBUG_LOG */
2434
2435         if (!blk_special_request(rq)) {
2436                 /*
2437                  * We do not support buffer cache originated requests.
2438                  */
2439                 printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
2440                         "request queue (%d)\n", drive->name, rq->cmd_type);
2441                 ide_end_request(drive, 0, 0);
2442                 return ide_stopped;
2443         }
2444
2445         /*
2446          *      Retry a failed packet command
2447          */
2448         if (tape->failed_pc != NULL &&
2449             tape->pc->c[0] == IDETAPE_REQUEST_SENSE_CMD) {
2450                 return idetape_issue_packet_command(drive, tape->failed_pc);
2451         }
2452 #if IDETAPE_DEBUG_BUGS
2453         if (postponed_rq != NULL)
2454                 if (rq != postponed_rq) {
2455                         printk(KERN_ERR "ide-tape: ide-tape.c bug - "
2456                                         "Two DSC requests were queued\n");
2457                         idetape_end_request(drive, 0, 0);
2458                         return ide_stopped;
2459                 }
2460 #endif /* IDETAPE_DEBUG_BUGS */
2461
2462         tape->postponed_rq = NULL;
2463
2464         /*
2465          * If the tape is still busy, postpone our request and service
2466          * the other device meanwhile.
2467          */
2468         status.all = HWIF(drive)->INB(IDE_STATUS_REG);
2469
2470         if (!drive->dsc_overlap && !(rq->cmd[0] & REQ_IDETAPE_PC2))
2471                 set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
2472
2473         if (drive->post_reset == 1) {
2474                 set_bit(IDETAPE_IGNORE_DSC, &tape->flags);
2475                 drive->post_reset = 0;
2476         }
2477
2478         if (tape->tape_still_time > 100 && tape->tape_still_time < 200)
2479                 tape->measure_insert_time = 1;
2480         if (time_after(jiffies, tape->insert_time))
2481                 tape->insert_speed = tape->insert_size / 1024 * HZ / (jiffies - tape->insert_time);
2482         calculate_speeds(drive);
2483         if (!test_and_clear_bit(IDETAPE_IGNORE_DSC, &tape->flags) &&
2484             !status.b.dsc) {
2485                 if (postponed_rq == NULL) {
2486                         tape->dsc_polling_start = jiffies;
2487                         tape->dsc_polling_frequency = tape->best_dsc_rw_frequency;
2488                         tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
2489                 } else if (time_after(jiffies, tape->dsc_timeout)) {
2490                         printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
2491                                 tape->name);
2492                         if (rq->cmd[0] & REQ_IDETAPE_PC2) {
2493                                 idetape_media_access_finished(drive);
2494                                 return ide_stopped;
2495                         } else {
2496                                 return ide_do_reset(drive);
2497                         }
2498                 } else if (time_after(jiffies, tape->dsc_polling_start + IDETAPE_DSC_MA_THRESHOLD))
2499                         tape->dsc_polling_frequency = IDETAPE_DSC_MA_SLOW;
2500                 idetape_postpone_request(drive);
2501                 return ide_stopped;
2502         }
2503         if (rq->cmd[0] & REQ_IDETAPE_READ) {
2504                 tape->buffer_head++;
2505 #if USE_IOTRACE
2506                 IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
2507 #endif
2508                 tape->postpone_cnt = 0;
2509                 pc = idetape_next_pc_storage(drive);
2510                 idetape_create_read_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2511                 goto out;
2512         }
2513         if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
2514                 tape->buffer_head++;
2515 #if USE_IOTRACE
2516                 IO_trace(IO_IDETAPE_FIFO, tape->pipeline_head, tape->buffer_head, tape->tape_head, tape->minor);
2517 #endif
2518                 tape->postpone_cnt = 0;
2519                 pc = idetape_next_pc_storage(drive);
2520                 idetape_create_write_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2521                 goto out;
2522         }
2523         if (rq->cmd[0] & REQ_IDETAPE_READ_BUFFER) {
2524                 tape->postpone_cnt = 0;
2525                 pc = idetape_next_pc_storage(drive);
2526                 idetape_create_read_buffer_cmd(tape, pc, rq->current_nr_sectors, (struct idetape_bh *)rq->special);
2527                 goto out;
2528         }
2529         if (rq->cmd[0] & REQ_IDETAPE_PC1) {
2530                 pc = (idetape_pc_t *) rq->buffer;
2531                 rq->cmd[0] &= ~(REQ_IDETAPE_PC1);
2532                 rq->cmd[0] |= REQ_IDETAPE_PC2;
2533                 goto out;
2534         }
2535         if (rq->cmd[0] & REQ_IDETAPE_PC2) {
2536                 idetape_media_access_finished(drive);
2537                 return ide_stopped;
2538         }
2539         BUG();
2540 out:
2541         return idetape_issue_packet_command(drive, pc);
2542 }
2543
2544 /*
2545  *      Pipeline related functions
2546  */
2547 static inline int idetape_pipeline_active (idetape_tape_t *tape)
2548 {
2549         int rc1, rc2;
2550
2551         rc1 = test_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
2552         rc2 = (tape->active_data_request != NULL);
2553         return rc1;
2554 }
2555
2556 /*
2557  *      idetape_kmalloc_stage uses __get_free_page to allocate a pipeline
2558  *      stage, along with all the necessary small buffers which together make
2559  *      a buffer of size tape->stage_size (or a bit more). We attempt to
2560  *      combine sequential pages as much as possible.
2561  *
2562  *      Returns a pointer to the new allocated stage, or NULL if we
2563  *      can't (or don't want to) allocate a stage.
2564  *
2565  *      Pipeline stages are optional and are used to increase performance.
2566  *      If we can't allocate them, we'll manage without them.
2567  */
2568 static idetape_stage_t *__idetape_kmalloc_stage (idetape_tape_t *tape, int full, int clear)
2569 {
2570         idetape_stage_t *stage;
2571         struct idetape_bh *prev_bh, *bh;
2572         int pages = tape->pages_per_stage;
2573         char *b_data = NULL;
2574
2575         if ((stage = kmalloc(sizeof (idetape_stage_t),GFP_KERNEL)) == NULL)
2576                 return NULL;
2577         stage->next = NULL;
2578
2579         bh = stage->bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
2580         if (bh == NULL)
2581                 goto abort;
2582         bh->b_reqnext = NULL;
2583         if ((bh->b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2584                 goto abort;
2585         if (clear)
2586                 memset(bh->b_data, 0, PAGE_SIZE);
2587         bh->b_size = PAGE_SIZE;
2588         atomic_set(&bh->b_count, full ? bh->b_size : 0);
2589
2590         while (--pages) {
2591                 if ((b_data = (char *) __get_free_page (GFP_KERNEL)) == NULL)
2592                         goto abort;
2593                 if (clear)
2594                         memset(b_data, 0, PAGE_SIZE);
2595                 if (bh->b_data == b_data + PAGE_SIZE) {
2596                         bh->b_size += PAGE_SIZE;
2597                         bh->b_data -= PAGE_SIZE;
2598                         if (full)
2599                                 atomic_add(PAGE_SIZE, &bh->b_count);
2600                         continue;
2601                 }
2602                 if (b_data == bh->b_data + bh->b_size) {
2603                         bh->b_size += PAGE_SIZE;
2604                         if (full)
2605                                 atomic_add(PAGE_SIZE, &bh->b_count);
2606                         continue;
2607                 }
2608                 prev_bh = bh;
2609                 if ((bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL)) == NULL) {
2610                         free_page((unsigned long) b_data);
2611                         goto abort;
2612                 }
2613                 bh->b_reqnext = NULL;
2614                 bh->b_data = b_data;
2615                 bh->b_size = PAGE_SIZE;
2616                 atomic_set(&bh->b_count, full ? bh->b_size : 0);
2617                 prev_bh->b_reqnext = bh;
2618         }
2619         bh->b_size -= tape->excess_bh_size;
2620         if (full)
2621                 atomic_sub(tape->excess_bh_size, &bh->b_count);
2622         return stage;
2623 abort:
2624         __idetape_kfree_stage(stage);
2625         return NULL;
2626 }
2627
2628 static idetape_stage_t *idetape_kmalloc_stage (idetape_tape_t *tape)
2629 {
2630         idetape_stage_t *cache_stage = tape->cache_stage;
2631
2632 #if IDETAPE_DEBUG_LOG
2633         if (tape->debug_level >= 4)
2634                 printk(KERN_INFO "ide-tape: Reached idetape_kmalloc_stage\n");
2635 #endif /* IDETAPE_DEBUG_LOG */
2636
2637         if (tape->nr_stages >= tape->max_stages)
2638                 return NULL;
2639         if (cache_stage != NULL) {
2640                 tape->cache_stage = NULL;
2641                 return cache_stage;
2642         }
2643         return __idetape_kmalloc_stage(tape, 0, 0);
2644 }
2645
2646 static int idetape_copy_stage_from_user (idetape_tape_t *tape, idetape_stage_t *stage, const char __user *buf, int n)
2647 {
2648         struct idetape_bh *bh = tape->bh;
2649         int count;
2650         int ret = 0;
2651
2652         while (n) {
2653 #if IDETAPE_DEBUG_BUGS
2654                 if (bh == NULL) {
2655                         printk(KERN_ERR "ide-tape: bh == NULL in "
2656                                 "idetape_copy_stage_from_user\n");
2657                         return 1;
2658                 }
2659 #endif /* IDETAPE_DEBUG_BUGS */
2660                 count = min((unsigned int)(bh->b_size - atomic_read(&bh->b_count)), (unsigned int)n);
2661                 if (copy_from_user(bh->b_data + atomic_read(&bh->b_count), buf, count))
2662                         ret = 1;
2663                 n -= count;
2664                 atomic_add(count, &bh->b_count);
2665                 buf += count;
2666                 if (atomic_read(&bh->b_count) == bh->b_size) {
2667                         bh = bh->b_reqnext;
2668                         if (bh)
2669                                 atomic_set(&bh->b_count, 0);
2670                 }
2671         }
2672         tape->bh = bh;
2673         return ret;
2674 }
2675
2676 static int idetape_copy_stage_to_user (idetape_tape_t *tape, char __user *buf, idetape_stage_t *stage, int n)
2677 {
2678         struct idetape_bh *bh = tape->bh;
2679         int count;
2680         int ret = 0;
2681
2682         while (n) {
2683 #if IDETAPE_DEBUG_BUGS
2684                 if (bh == NULL) {
2685                         printk(KERN_ERR "ide-tape: bh == NULL in "
2686                                 "idetape_copy_stage_to_user\n");
2687                         return 1;
2688                 }
2689 #endif /* IDETAPE_DEBUG_BUGS */
2690                 count = min(tape->b_count, n);
2691                 if  (copy_to_user(buf, tape->b_data, count))
2692                         ret = 1;
2693                 n -= count;
2694                 tape->b_data += count;
2695                 tape->b_count -= count;
2696                 buf += count;
2697                 if (!tape->b_count) {
2698                         tape->bh = bh = bh->b_reqnext;
2699                         if (bh) {
2700                                 tape->b_data = bh->b_data;
2701                                 tape->b_count = atomic_read(&bh->b_count);
2702                         }
2703                 }
2704         }
2705         return ret;
2706 }
2707
2708 static void idetape_init_merge_stage (idetape_tape_t *tape)
2709 {
2710         struct idetape_bh *bh = tape->merge_stage->bh;
2711         
2712         tape->bh = bh;
2713         if (tape->chrdev_direction == idetape_direction_write)
2714                 atomic_set(&bh->b_count, 0);
2715         else {
2716                 tape->b_data = bh->b_data;
2717                 tape->b_count = atomic_read(&bh->b_count);
2718         }
2719 }
2720
2721 static void idetape_switch_buffers (idetape_tape_t *tape, idetape_stage_t *stage)
2722 {
2723         struct idetape_bh *tmp;
2724
2725         tmp = stage->bh;
2726         stage->bh = tape->merge_stage->bh;
2727         tape->merge_stage->bh = tmp;
2728         idetape_init_merge_stage(tape);
2729 }
2730
2731 /*
2732  *      idetape_add_stage_tail adds a new stage at the end of the pipeline.
2733  */
2734 static void idetape_add_stage_tail (ide_drive_t *drive,idetape_stage_t *stage)
2735 {
2736         idetape_tape_t *tape = drive->driver_data;
2737         unsigned long flags;
2738         
2739 #if IDETAPE_DEBUG_LOG
2740         if (tape->debug_level >= 4)
2741                 printk (KERN_INFO "ide-tape: Reached idetape_add_stage_tail\n");
2742 #endif /* IDETAPE_DEBUG_LOG */
2743         spin_lock_irqsave(&tape->spinlock, flags);
2744         stage->next = NULL;
2745         if (tape->last_stage != NULL)
2746                 tape->last_stage->next=stage;
2747         else
2748                 tape->first_stage = tape->next_stage=stage;
2749         tape->last_stage = stage;
2750         if (tape->next_stage == NULL)
2751                 tape->next_stage = tape->last_stage;
2752         tape->nr_stages++;
2753         tape->nr_pending_stages++;
2754         spin_unlock_irqrestore(&tape->spinlock, flags);
2755 }
2756
2757 /*
2758  *      idetape_wait_for_request installs a completion in a pending request
2759  *      and sleeps until it is serviced.
2760  *
2761  *      The caller should ensure that the request will not be serviced
2762  *      before we install the completion (usually by disabling interrupts).
2763  */
2764 static void idetape_wait_for_request (ide_drive_t *drive, struct request *rq)
2765 {
2766         DECLARE_COMPLETION_ONSTACK(wait);
2767         idetape_tape_t *tape = drive->driver_data;
2768
2769 #if IDETAPE_DEBUG_BUGS
2770         if (rq == NULL || !blk_special_request(rq)) {
2771                 printk (KERN_ERR "ide-tape: bug: Trying to sleep on non-valid request\n");
2772                 return;
2773         }
2774 #endif /* IDETAPE_DEBUG_BUGS */
2775         rq->end_io_data = &wait;
2776         rq->end_io = blk_end_sync_rq;
2777         spin_unlock_irq(&tape->spinlock);
2778         wait_for_completion(&wait);
2779         /* The stage and its struct request have been deallocated */
2780         spin_lock_irq(&tape->spinlock);
2781 }
2782
2783 static ide_startstop_t idetape_read_position_callback (ide_drive_t *drive)
2784 {
2785         idetape_tape_t *tape = drive->driver_data;
2786         idetape_read_position_result_t *result;
2787         
2788 #if IDETAPE_DEBUG_LOG
2789         if (tape->debug_level >= 4)
2790                 printk(KERN_INFO "ide-tape: Reached idetape_read_position_callback\n");
2791 #endif /* IDETAPE_DEBUG_LOG */
2792
2793         if (!tape->pc->error) {
2794                 result = (idetape_read_position_result_t *) tape->pc->buffer;
2795 #if IDETAPE_DEBUG_LOG
2796                 if (tape->debug_level >= 2)
2797                         printk(KERN_INFO "ide-tape: BOP - %s\n",result->bop ? "Yes":"No");
2798                 if (tape->debug_level >= 2)
2799                         printk(KERN_INFO "ide-tape: EOP - %s\n",result->eop ? "Yes":"No");
2800 #endif /* IDETAPE_DEBUG_LOG */
2801                 if (result->bpu) {
2802                         printk(KERN_INFO "ide-tape: Block location is unknown to the tape\n");
2803                         clear_bit(IDETAPE_ADDRESS_VALID, &tape->flags);
2804                         idetape_end_request(drive, 0, 0);
2805                 } else {
2806 #if IDETAPE_DEBUG_LOG
2807                         if (tape->debug_level >= 2)
2808                                 printk(KERN_INFO "ide-tape: Block Location - %u\n", ntohl(result->first_block));
2809 #endif /* IDETAPE_DEBUG_LOG */
2810                         tape->partition = result->partition;
2811                         tape->first_frame_position = ntohl(result->first_block);
2812                         tape->last_frame_position = ntohl(result->last_block);
2813                         tape->blocks_in_buffer = result->blocks_in_buffer[2];
2814                         set_bit(IDETAPE_ADDRESS_VALID, &tape->flags);
2815                         idetape_end_request(drive, 1, 0);
2816                 }
2817         } else {
2818                 idetape_end_request(drive, 0, 0);
2819         }
2820         return ide_stopped;
2821 }
2822
2823 /*
2824  *      idetape_create_write_filemark_cmd will:
2825  *
2826  *              1.      Write a filemark if write_filemark=1.
2827  *              2.      Flush the device buffers without writing a filemark
2828  *                      if write_filemark=0.
2829  *
2830  */
2831 static void idetape_create_write_filemark_cmd (ide_drive_t *drive, idetape_pc_t *pc,int write_filemark)
2832 {
2833         idetape_init_pc(pc);
2834         pc->c[0] = IDETAPE_WRITE_FILEMARK_CMD;
2835         pc->c[4] = write_filemark;
2836         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2837         pc->callback = &idetape_pc_callback;
2838 }
2839
2840 static void idetape_create_test_unit_ready_cmd(idetape_pc_t *pc)
2841 {
2842         idetape_init_pc(pc);
2843         pc->c[0] = IDETAPE_TEST_UNIT_READY_CMD;
2844         pc->callback = &idetape_pc_callback;
2845 }
2846
2847 /*
2848  *      idetape_queue_pc_tail is based on the following functions:
2849  *
2850  *      ide_do_drive_cmd from ide.c
2851  *      cdrom_queue_request and cdrom_queue_packet_command from ide-cd.c
2852  *
2853  *      We add a special packet command request to the tail of the request
2854  *      queue, and wait for it to be serviced.
2855  *
2856  *      This is not to be called from within the request handling part
2857  *      of the driver ! We allocate here data in the stack, and it is valid
2858  *      until the request is finished. This is not the case for the bottom
2859  *      part of the driver, where we are always leaving the functions to wait
2860  *      for an interrupt or a timer event.
2861  *
2862  *      From the bottom part of the driver, we should allocate safe memory
2863  *      using idetape_next_pc_storage and idetape_next_rq_storage, and add
2864  *      the request to the request list without waiting for it to be serviced !
2865  *      In that case, we usually use idetape_queue_pc_head.
2866  */
2867 static int __idetape_queue_pc_tail (ide_drive_t *drive, idetape_pc_t *pc)
2868 {
2869         struct ide_tape_obj *tape = drive->driver_data;
2870         struct request rq;
2871
2872         idetape_init_rq(&rq, REQ_IDETAPE_PC1);
2873         rq.buffer = (char *) pc;
2874         rq.rq_disk = tape->disk;
2875         return ide_do_drive_cmd(drive, &rq, ide_wait);
2876 }
2877
2878 static void idetape_create_load_unload_cmd (ide_drive_t *drive, idetape_pc_t *pc,int cmd)
2879 {
2880         idetape_init_pc(pc);
2881         pc->c[0] = IDETAPE_LOAD_UNLOAD_CMD;
2882         pc->c[4] = cmd;
2883         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2884         pc->callback = &idetape_pc_callback;
2885 }
2886
2887 static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
2888 {
2889         idetape_tape_t *tape = drive->driver_data;
2890         idetape_pc_t pc;
2891         int load_attempted = 0;
2892
2893         /*
2894          * Wait for the tape to become ready
2895          */
2896         set_bit(IDETAPE_MEDIUM_PRESENT, &tape->flags);
2897         timeout += jiffies;
2898         while (time_before(jiffies, timeout)) {
2899                 idetape_create_test_unit_ready_cmd(&pc);
2900                 if (!__idetape_queue_pc_tail(drive, &pc))
2901                         return 0;
2902                 if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
2903                     || (tape->asc == 0x3A)) {   /* no media */
2904                         if (load_attempted)
2905                                 return -ENOMEDIUM;
2906                         idetape_create_load_unload_cmd(drive, &pc, IDETAPE_LU_LOAD_MASK);
2907                         __idetape_queue_pc_tail(drive, &pc);
2908                         load_attempted = 1;
2909                 /* not about to be ready */
2910                 } else if (!(tape->sense_key == 2 && tape->asc == 4 &&
2911                              (tape->ascq == 1 || tape->ascq == 8)))
2912                         return -EIO;
2913                 msleep(100);
2914         }
2915         return -EIO;
2916 }
2917
2918 static int idetape_queue_pc_tail (ide_drive_t *drive,idetape_pc_t *pc)
2919 {
2920         return __idetape_queue_pc_tail(drive, pc);
2921 }
2922
2923 static int idetape_flush_tape_buffers (ide_drive_t *drive)
2924 {
2925         idetape_pc_t pc;
2926         int rc;
2927
2928         idetape_create_write_filemark_cmd(drive, &pc, 0);
2929         if ((rc = idetape_queue_pc_tail(drive, &pc)))
2930                 return rc;
2931         idetape_wait_ready(drive, 60 * 5 * HZ);
2932         return 0;
2933 }
2934
2935 static void idetape_create_read_position_cmd (idetape_pc_t *pc)
2936 {
2937         idetape_init_pc(pc);
2938         pc->c[0] = IDETAPE_READ_POSITION_CMD;
2939         pc->request_transfer = 20;
2940         pc->callback = &idetape_read_position_callback;
2941 }
2942
2943 static int idetape_read_position (ide_drive_t *drive)
2944 {
2945         idetape_tape_t *tape = drive->driver_data;
2946         idetape_pc_t pc;
2947         int position;
2948
2949 #if IDETAPE_DEBUG_LOG
2950         if (tape->debug_level >= 4)
2951                 printk(KERN_INFO "ide-tape: Reached idetape_read_position\n");
2952 #endif /* IDETAPE_DEBUG_LOG */
2953
2954         idetape_create_read_position_cmd(&pc);
2955         if (idetape_queue_pc_tail(drive, &pc))
2956                 return -1;
2957         position = tape->first_frame_position;
2958         return position;
2959 }
2960
2961 static void idetape_create_locate_cmd (ide_drive_t *drive, idetape_pc_t *pc, unsigned int block, u8 partition, int skip)
2962 {
2963         idetape_init_pc(pc);
2964         pc->c[0] = IDETAPE_LOCATE_CMD;
2965         pc->c[1] = 2;
2966         put_unaligned(htonl(block), (unsigned int *) &pc->c[3]);
2967         pc->c[8] = partition;
2968         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
2969         pc->callback = &idetape_pc_callback;
2970 }
2971
2972 static int idetape_create_prevent_cmd (ide_drive_t *drive, idetape_pc_t *pc, int prevent)
2973 {
2974         idetape_tape_t *tape = drive->driver_data;
2975
2976         if (!tape->capabilities.lock)
2977                 return 0;
2978
2979         idetape_init_pc(pc);
2980         pc->c[0] = IDETAPE_PREVENT_CMD;
2981         pc->c[4] = prevent;
2982         pc->callback = &idetape_pc_callback;
2983         return 1;
2984 }
2985
2986 static int __idetape_discard_read_pipeline (ide_drive_t *drive)
2987 {
2988         idetape_tape_t *tape = drive->driver_data;
2989         unsigned long flags;
2990         int cnt;
2991
2992         if (tape->chrdev_direction != idetape_direction_read)
2993                 return 0;
2994
2995         /* Remove merge stage. */
2996         cnt = tape->merge_stage_size / tape->tape_block_size;
2997         if (test_and_clear_bit(IDETAPE_FILEMARK, &tape->flags))
2998                 ++cnt;          /* Filemarks count as 1 sector */
2999         tape->merge_stage_size = 0;
3000         if (tape->merge_stage != NULL) {
3001                 __idetape_kfree_stage(tape->merge_stage);
3002                 tape->merge_stage = NULL;
3003         }
3004
3005         /* Clear pipeline flags. */
3006         clear_bit(IDETAPE_PIPELINE_ERROR, &tape->flags);
3007         tape->chrdev_direction = idetape_direction_none;
3008
3009         /* Remove pipeline stages. */
3010         if (tape->first_stage == NULL)
3011                 return 0;
3012
3013         spin_lock_irqsave(&tape->spinlock, flags);
3014         tape->next_stage = NULL;
3015         if (idetape_pipeline_active(tape))
3016                 idetape_wait_for_request(drive, tape->active_data_request);
3017         spin_unlock_irqrestore(&tape->spinlock, flags);
3018
3019         while (tape->first_stage != NULL) {
3020                 struct request *rq_ptr = &tape->first_stage->rq;
3021
3022                 cnt += rq_ptr->nr_sectors - rq_ptr->current_nr_sectors; 
3023                 if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
3024                         ++cnt;
3025                 idetape_remove_stage_head(drive);
3026         }
3027         tape->nr_pending_stages = 0;
3028         tape->max_stages = tape->min_pipeline;
3029         return cnt;
3030 }
3031
3032 /*
3033  *      idetape_position_tape positions the tape to the requested block
3034  *      using the LOCATE packet command. A READ POSITION command is then
3035  *      issued to check where we are positioned.
3036  *
3037  *      Like all higher level operations, we queue the commands at the tail
3038  *      of the request queue and wait for their completion.
3039  *      
3040  */
3041 static int idetape_position_tape (ide_drive_t *drive, unsigned int block, u8 partition, int skip)
3042 {
3043         idetape_tape_t *tape = drive->driver_data;
3044         int retval;
3045         idetape_pc_t pc;
3046
3047         if (tape->chrdev_direction == idetape_direction_read)
3048                 __idetape_discard_read_pipeline(drive);
3049         idetape_wait_ready(drive, 60 * 5 * HZ);
3050         idetape_create_locate_cmd(drive, &pc, block, partition, skip);
3051         retval = idetape_queue_pc_tail(drive, &pc);
3052         if (retval)
3053                 return (retval);
3054
3055         idetape_create_read_position_cmd(&pc);
3056         return (idetape_queue_pc_tail(drive, &pc));
3057 }
3058
3059 static void idetape_discard_read_pipeline (ide_drive_t *drive, int restore_position)
3060 {
3061         idetape_tape_t *tape = drive->driver_data;
3062         int cnt;
3063         int seek, position;
3064
3065         cnt = __idetape_discard_read_pipeline(drive);
3066         if (restore_position) {
3067                 position = idetape_read_position(drive);
3068                 seek = position > cnt ? position - cnt : 0;
3069                 if (idetape_position_tape(drive, seek, 0, 0)) {
3070                         printk(KERN_INFO "ide-tape: %s: position_tape failed in discard_pipeline()\n", tape->name);
3071                         return;
3072                 }
3073         }
3074 }
3075
3076 /*
3077  * idetape_queue_rw_tail generates a read/write request for the block
3078  * device interface and wait for it to be serviced.
3079  */
3080 static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int blocks, struct idetape_bh *bh)
3081 {
3082         idetape_tape_t *tape = drive->driver_data;
3083         struct request rq;
3084
3085 #if IDETAPE_DEBUG_LOG
3086         if (tape->debug_level >= 2)
3087                 printk(KERN_INFO "ide-tape: idetape_queue_rw_tail: cmd=%d\n",cmd);
3088 #endif /* IDETAPE_DEBUG_LOG */
3089 #if IDETAPE_DEBUG_BUGS
3090         if (idetape_pipeline_active(tape)) {
3091                 printk(KERN_ERR "ide-tape: bug: the pipeline is active in idetape_queue_rw_tail\n");
3092                 return (0);
3093         }
3094 #endif /* IDETAPE_DEBUG_BUGS */ 
3095
3096         idetape_init_rq(&rq, cmd);
3097         rq.rq_disk = tape->disk;
3098         rq.special = (void *)bh;
3099         rq.sector = tape->first_frame_position;
3100         rq.nr_sectors = rq.current_nr_sectors = blocks;
3101         (void) ide_do_drive_cmd(drive, &rq, ide_wait);
3102
3103         if ((cmd & (REQ_IDETAPE_READ | REQ_IDETAPE_WRITE)) == 0)
3104                 return 0;
3105
3106         if (tape->merge_stage)
3107                 idetape_init_merge_stage(tape);
3108         if (rq.errors == IDETAPE_ERROR_GENERAL)
3109                 return -EIO;
3110         return (tape->tape_block_size * (blocks-rq.current_nr_sectors));
3111 }
3112
3113 /*
3114  *      idetape_insert_pipeline_into_queue is used to start servicing the
3115  *      pipeline stages, starting from tape->next_stage.
3116  */
3117 static void idetape_insert_pipeline_into_queue (ide_drive_t *drive)
3118 {
3119         idetape_tape_t *tape = drive->driver_data;
3120
3121         if (tape->next_stage == NULL)
3122                 return;
3123         if (!idetape_pipeline_active(tape)) {
3124                 set_bit(IDETAPE_PIPELINE_ACTIVE, &tape->flags);
3125                 idetape_active_next_stage(drive);
3126                 (void) ide_do_drive_cmd(drive, tape->active_data_request, ide_end);
3127         }
3128 }
3129
3130 static void idetape_create_inquiry_cmd (idetape_pc_t *pc)
3131 {
3132         idetape_init_pc(pc);
3133         pc->c[0] = IDETAPE_INQUIRY_CMD;
3134         pc->c[4] = pc->request_transfer = 254;
3135         pc->callback = &idetape_pc_callback;
3136 }
3137
3138 static void idetape_create_rewind_cmd (ide_drive_t *drive, idetape_pc_t *pc)
3139 {
3140         idetape_init_pc(pc);
3141         pc->c[0] = IDETAPE_REWIND_CMD;
3142         set_bit(PC_WAIT_FOR_DSC, &pc->flags);
3143         pc->callback = &idetape_pc_callback;
3144 }
3145
3146 #if 0
3147 static void idetape_create_mode_select_cmd (idetape_pc_t *pc, int length)
3148 {
3149         idetape_init_pc(pc);
3150         set_bit(PC_WRITING, &pc->flags);
3151         pc->c[0] = IDETAPE_MODE_SELECT_CMD;
3152         pc-&