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