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