]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/ide/ide-tape.c
ide-tape: convert driver to using generic ide_atapi_pc
[linux-2.6-omap-h63xx.git] / drivers / ide / ide-tape.c
1 /*
2  * IDE ATAPI streaming tape driver.
3  *
4  * Copyright (C) 1995-1999  Gadi Oxman <gadio@netvision.net.il>
5  * Copyright (C) 2003-2005  Bartlomiej Zolnierkiewicz
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  * For a historical changelog see
15  * Documentation/ide/ChangeLog.ide-tape.1995-2002
16  */
17
18 #define IDETAPE_VERSION "1.20"
19
20 #include <linux/module.h>
21 #include <linux/types.h>
22 #include <linux/string.h>
23 #include <linux/kernel.h>
24 #include <linux/delay.h>
25 #include <linux/timer.h>
26 #include <linux/mm.h>
27 #include <linux/interrupt.h>
28 #include <linux/jiffies.h>
29 #include <linux/major.h>
30 #include <linux/errno.h>
31 #include <linux/genhd.h>
32 #include <linux/slab.h>
33 #include <linux/pci.h>
34 #include <linux/ide.h>
35 #include <linux/smp_lock.h>
36 #include <linux/completion.h>
37 #include <linux/bitops.h>
38 #include <linux/mutex.h>
39 #include <scsi/scsi.h>
40
41 #include <asm/byteorder.h>
42 #include <linux/irq.h>
43 #include <linux/uaccess.h>
44 #include <linux/io.h>
45 #include <asm/unaligned.h>
46 #include <linux/mtio.h>
47
48 enum {
49         /* output errors only */
50         DBG_ERR =               (1 << 0),
51         /* output all sense key/asc */
52         DBG_SENSE =             (1 << 1),
53         /* info regarding all chrdev-related procedures */
54         DBG_CHRDEV =            (1 << 2),
55         /* all remaining procedures */
56         DBG_PROCS =             (1 << 3),
57         /* buffer alloc info (pc_stack & rq_stack) */
58         DBG_PCRQ_STACK =        (1 << 4),
59 };
60
61 /* define to see debug info */
62 #define IDETAPE_DEBUG_LOG               0
63
64 #if IDETAPE_DEBUG_LOG
65 #define debug_log(lvl, fmt, args...)                    \
66 {                                                       \
67         if (tape->debug_mask & lvl)                     \
68         printk(KERN_INFO "ide-tape: " fmt, ## args);    \
69 }
70 #else
71 #define debug_log(lvl, fmt, args...) do {} while (0)
72 #endif
73
74 /**************************** Tunable parameters *****************************/
75
76
77 /*
78  * Pipelined mode parameters.
79  *
80  * We try to use the minimum number of stages which is enough to keep the tape
81  * constantly streaming. To accomplish that, we implement a feedback loop around
82  * the maximum number of stages:
83  *
84  * We start from MIN maximum stages (we will not even use MIN stages if we don't
85  * need them), increment it by RATE*(MAX-MIN) whenever we sense that the
86  * pipeline is empty, until we reach the optimum value or until we reach MAX.
87  *
88  * Setting the following parameter to 0 is illegal: the pipelined mode cannot be
89  * disabled (idetape_calculate_speeds() divides by tape->max_stages.)
90  */
91 #define IDETAPE_MIN_PIPELINE_STAGES       1
92 #define IDETAPE_MAX_PIPELINE_STAGES     400
93 #define IDETAPE_INCREASE_STAGES_RATE     20
94
95 /*
96  * After each failed packet command we issue a request sense command and retry
97  * the packet command IDETAPE_MAX_PC_RETRIES times.
98  *
99  * Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
100  */
101 #define IDETAPE_MAX_PC_RETRIES          3
102
103 /*
104  * With each packet command, we allocate a buffer of IDETAPE_PC_BUFFER_SIZE
105  * bytes. This is used for several packet commands (Not for READ/WRITE commands)
106  */
107 #define IDETAPE_PC_BUFFER_SIZE          256
108
109 /*
110  *      In various places in the driver, we need to allocate storage
111  *      for packet commands and requests, which will remain valid while
112  *      we leave the driver to wait for an interrupt or a timeout event.
113  */
114 #define IDETAPE_PC_STACK                (10 + IDETAPE_MAX_PC_RETRIES)
115
116 /*
117  * Some drives (for example, Seagate STT3401A Travan) require a very long
118  * timeout, because they don't return an interrupt or clear their busy bit
119  * until after the command completes (even retension commands).
120  */
121 #define IDETAPE_WAIT_CMD                (900*HZ)
122
123 /*
124  * The following parameter is used to select the point in the internal tape fifo
125  * in which we will start to refill the buffer. Decreasing the following
126  * parameter will improve the system's latency and interactive response, while
127  * using a high value might improve system throughput.
128  */
129 #define IDETAPE_FIFO_THRESHOLD          2
130
131 /*
132  * DSC polling parameters.
133  *
134  * Polling for DSC (a single bit in the status register) is a very important
135  * function in ide-tape. There are two cases in which we poll for DSC:
136  *
137  * 1. Before a read/write packet command, to ensure that we can transfer data
138  * from/to the tape's data buffers, without causing an actual media access.
139  * In case the tape is not ready yet, we take out our request from the device
140  * request queue, so that ide.c could service requests from the other device
141  * on the same interface in the meantime.
142  *
143  * 2. After the successful initialization of a "media access packet command",
144  * which is a command that can take a long time to complete (the interval can
145  * range from several seconds to even an hour). Again, we postpone our request
146  * in the middle to free the bus for the other device. The polling frequency
147  * here should be lower than the read/write frequency since those media access
148  * commands are slow. We start from a "fast" frequency - IDETAPE_DSC_MA_FAST
149  * (1 second), and if we don't receive DSC after IDETAPE_DSC_MA_THRESHOLD
150  * (5 min), we switch it to a lower frequency - IDETAPE_DSC_MA_SLOW (1 min).
151  *
152  * We also set a timeout for the timer, in case something goes wrong. The
153  * timeout should be longer then the maximum execution time of a tape operation.
154  */
155
156 /* DSC timings. */
157 #define IDETAPE_DSC_RW_MIN              5*HZ/100        /* 50 msec */
158 #define IDETAPE_DSC_RW_MAX              40*HZ/100       /* 400 msec */
159 #define IDETAPE_DSC_RW_TIMEOUT          2*60*HZ         /* 2 minutes */
160 #define IDETAPE_DSC_MA_FAST             2*HZ            /* 2 seconds */
161 #define IDETAPE_DSC_MA_THRESHOLD        5*60*HZ         /* 5 minutes */
162 #define IDETAPE_DSC_MA_SLOW             30*HZ           /* 30 seconds */
163 #define IDETAPE_DSC_MA_TIMEOUT          2*60*60*HZ      /* 2 hours */
164
165 /*************************** End of tunable parameters ***********************/
166
167 /* Read/Write error simulation */
168 #define SIMULATE_ERRORS                 0
169
170 /* tape directions */
171 enum {
172         IDETAPE_DIR_NONE  = (1 << 0),
173         IDETAPE_DIR_READ  = (1 << 1),
174         IDETAPE_DIR_WRITE = (1 << 2),
175 };
176
177 struct idetape_bh {
178         u32 b_size;
179         atomic_t b_count;
180         struct idetape_bh *b_reqnext;
181         char *b_data;
182 };
183
184 /* Packet command flag bits. */
185 enum {
186         /* Set when an error is considered normal - We won't retry */
187         PC_FLAG_ABORT           = (1 << 0),
188         /* 1 When polling for DSC on a media access command */
189         PC_FLAG_WAIT_FOR_DSC    = (1 << 1),
190         /* 1 when we prefer to use DMA if possible */
191         PC_FLAG_DMA_RECOMMENDED = (1 << 2),
192         /* 1 while DMA in progress */
193         PC_FLAG_DMA_IN_PROGRESS = (1 << 3),
194         /* 1 when encountered problem during DMA */
195         PC_FLAG_DMA_ERROR       = (1 << 4),
196         /* Data direction */
197         PC_FLAG_WRITING         = (1 << 5),
198 };
199
200 /* Tape door status */
201 #define DOOR_UNLOCKED                   0
202 #define DOOR_LOCKED                     1
203 #define DOOR_EXPLICITLY_LOCKED          2
204
205 /* Some defines for the SPACE command */
206 #define IDETAPE_SPACE_OVER_FILEMARK     1
207 #define IDETAPE_SPACE_TO_EOD            3
208
209 /* Some defines for the LOAD UNLOAD command */
210 #define IDETAPE_LU_LOAD_MASK            1
211 #define IDETAPE_LU_RETENSION_MASK       2
212 #define IDETAPE_LU_EOT_MASK             4
213
214 /*
215  * Special requests for our block device strategy routine.
216  *
217  * In order to service a character device command, we add special requests to
218  * the tail of our block device request queue and wait for their completion.
219  */
220
221 enum {
222         REQ_IDETAPE_PC1         = (1 << 0), /* packet command (first stage) */
223         REQ_IDETAPE_PC2         = (1 << 1), /* packet command (second stage) */
224         REQ_IDETAPE_READ        = (1 << 2),
225         REQ_IDETAPE_WRITE       = (1 << 3),
226 };
227
228 /* Error codes returned in rq->errors to the higher part of the driver. */
229 #define IDETAPE_ERROR_GENERAL           101
230 #define IDETAPE_ERROR_FILEMARK          102
231 #define IDETAPE_ERROR_EOD               103
232
233 /* Structures related to the SELECT SENSE / MODE SENSE packet commands. */
234 #define IDETAPE_BLOCK_DESCRIPTOR        0
235 #define IDETAPE_CAPABILITIES_PAGE       0x2a
236
237 /* Tape flag bits values. */
238 enum {
239         IDETAPE_FLAG_IGNORE_DSC         = (1 << 0),
240         /* 0 When the tape position is unknown */
241         IDETAPE_FLAG_ADDRESS_VALID      = (1 << 1),
242         /* Device already opened */
243         IDETAPE_FLAG_BUSY                       = (1 << 2),
244         /* Error detected in a pipeline stage */
245         IDETAPE_FLAG_PIPELINE_ERR       = (1 << 3),
246         /* Attempt to auto-detect the current user block size */
247         IDETAPE_FLAG_DETECT_BS          = (1 << 4),
248         /* Currently on a filemark */
249         IDETAPE_FLAG_FILEMARK           = (1 << 5),
250         /* DRQ interrupt device */
251         IDETAPE_FLAG_DRQ_INTERRUPT      = (1 << 6),
252         /* pipeline active */
253         IDETAPE_FLAG_PIPELINE_ACTIVE    = (1 << 7),
254         /* 0 = no tape is loaded, so we don't rewind after ejecting */
255         IDETAPE_FLAG_MEDIUM_PRESENT     = (1 << 8),
256 };
257
258 /* A pipeline stage. */
259 typedef struct idetape_stage_s {
260         struct request rq;                      /* The corresponding request */
261         struct idetape_bh *bh;                  /* The data buffers */
262         struct idetape_stage_s *next;           /* Pointer to the next stage */
263 } idetape_stage_t;
264
265 /*
266  * Most of our global data which we need to save even as we leave the driver due
267  * to an interrupt or a timer event is stored in the struct defined below.
268  */
269 typedef struct ide_tape_obj {
270         ide_drive_t     *drive;
271         ide_driver_t    *driver;
272         struct gendisk  *disk;
273         struct kref     kref;
274
275         /*
276          *      Since a typical character device operation requires more
277          *      than one packet command, we provide here enough memory
278          *      for the maximum of interconnected packet commands.
279          *      The packet commands are stored in the circular array pc_stack.
280          *      pc_stack_index points to the last used entry, and warps around
281          *      to the start when we get to the last array entry.
282          *
283          *      pc points to the current processed packet command.
284          *
285          *      failed_pc points to the last failed packet command, or contains
286          *      NULL if we do not need to retry any packet command. This is
287          *      required since an additional packet command is needed before the
288          *      retry, to get detailed information on what went wrong.
289          */
290         /* Current packet command */
291         struct ide_atapi_pc *pc;
292         /* Last failed packet command */
293         struct ide_atapi_pc *failed_pc;
294         /* Packet command stack */
295         struct ide_atapi_pc pc_stack[IDETAPE_PC_STACK];
296         /* Next free packet command storage space */
297         int pc_stack_index;
298         struct request rq_stack[IDETAPE_PC_STACK];
299         /* We implement a circular array */
300         int rq_stack_index;
301
302         /*
303          * DSC polling variables.
304          *
305          * While polling for DSC we use postponed_rq to postpone the current
306          * request so that ide.c will be able to service pending requests on the
307          * other device. Note that at most we will have only one DSC (usually
308          * data transfer) request in the device request queue. Additional
309          * requests can be queued in our internal pipeline, but they will be
310          * visible to ide.c only one at a time.
311          */
312         struct request *postponed_rq;
313         /* The time in which we started polling for DSC */
314         unsigned long dsc_polling_start;
315         /* Timer used to poll for dsc */
316         struct timer_list dsc_timer;
317         /* Read/Write dsc polling frequency */
318         unsigned long best_dsc_rw_freq;
319         unsigned long dsc_poll_freq;
320         unsigned long dsc_timeout;
321
322         /* Read position information */
323         u8 partition;
324         /* Current block */
325         unsigned int first_frame;
326
327         /* Last error information */
328         u8 sense_key, asc, ascq;
329
330         /* Character device operation */
331         unsigned int minor;
332         /* device name */
333         char name[4];
334         /* Current character device data transfer direction */
335         u8 chrdev_dir;
336
337         /* tape block size, usually 512 or 1024 bytes */
338         unsigned short blk_size;
339         int user_bs_factor;
340
341         /* Copy of the tape's Capabilities and Mechanical Page */
342         u8 caps[20];
343
344         /*
345          * Active data transfer request parameters.
346          *
347          * At most, there is only one ide-tape originated data transfer request
348          * in the device request queue. This allows ide.c to easily service
349          * requests from the other device when we postpone our active request.
350          * In the pipelined operation mode, we use our internal pipeline
351          * structure to hold more data requests. The data buffer size is chosen
352          * based on the tape's recommendation.
353          */
354         /* ptr to the request which is waiting in the device request queue */
355         struct request *active_data_rq;
356         /* Data buffer size chosen based on the tape's recommendation */
357         int stage_size;
358         idetape_stage_t *merge_stage;
359         int merge_stage_size;
360         struct idetape_bh *bh;
361         char *b_data;
362         int b_count;
363
364         /*
365          * Pipeline parameters.
366          *
367          * To accomplish non-pipelined mode, we simply set the following
368          * variables to zero (or NULL, where appropriate).
369          */
370         /* Number of currently used stages */
371         int nr_stages;
372         /* Number of pending stages */
373         int nr_pending_stages;
374         /* We will not allocate more than this number of stages */
375         int max_stages, min_pipeline, max_pipeline;
376         /* The first stage which will be removed from the pipeline */
377         idetape_stage_t *first_stage;
378         /* The currently active stage */
379         idetape_stage_t *active_stage;
380         /* Will be serviced after the currently active request */
381         idetape_stage_t *next_stage;
382         /* New requests will be added to the pipeline here */
383         idetape_stage_t *last_stage;
384         /* Optional free stage which we can use */
385         idetape_stage_t *cache_stage;
386         int pages_per_stage;
387         /* Wasted space in each stage */
388         int excess_bh_size;
389
390         /* Status/Action flags: long for set_bit */
391         unsigned long flags;
392         /* protects the ide-tape queue */
393         spinlock_t lock;
394
395         /* Measures average tape speed */
396         unsigned long avg_time;
397         int avg_size;
398         int avg_speed;
399
400         /* the door is currently locked */
401         int door_locked;
402         /* the tape hardware is write protected */
403         char drv_write_prot;
404         /* the tape is write protected (hardware or opened as read-only) */
405         char write_prot;
406
407         /*
408          * Limit the number of times a request can be postponed, to avoid an
409          * infinite postpone deadlock.
410          */
411         int postpone_cnt;
412
413         /*
414          * Measures number of frames:
415          *
416          * 1. written/read to/from the driver pipeline (pipeline_head).
417          * 2. written/read to/from the tape buffers (idetape_bh).
418          * 3. written/read by the tape to/from the media (tape_head).
419          */
420         int pipeline_head;
421         int buffer_head;
422         int tape_head;
423         int last_tape_head;
424
425         /* Speed control at the tape buffers input/output */
426         unsigned long insert_time;
427         int insert_size;
428         int insert_speed;
429         int max_insert_speed;
430         int measure_insert_time;
431
432         /* Speed regulation negative feedback loop */
433         int speed_control;
434         int pipeline_head_speed;
435         int controlled_pipeline_head_speed;
436         int uncontrolled_pipeline_head_speed;
437         int controlled_last_pipeline_head;
438         unsigned long uncontrolled_pipeline_head_time;
439         unsigned long controlled_pipeline_head_time;
440         int controlled_previous_pipeline_head;
441         int uncontrolled_previous_pipeline_head;
442         unsigned long controlled_previous_head_time;
443         unsigned long uncontrolled_previous_head_time;
444         int restart_speed_control_req;
445
446         u32 debug_mask;
447 } idetape_tape_t;
448
449 static DEFINE_MUTEX(idetape_ref_mutex);
450
451 static struct class *idetape_sysfs_class;
452
453 #define to_ide_tape(obj) container_of(obj, struct ide_tape_obj, kref)
454
455 #define ide_tape_g(disk) \
456         container_of((disk)->private_data, struct ide_tape_obj, driver)
457
458 static struct ide_tape_obj *ide_tape_get(struct gendisk *disk)
459 {
460         struct ide_tape_obj *tape = NULL;
461
462         mutex_lock(&idetape_ref_mutex);
463         tape = ide_tape_g(disk);
464         if (tape)
465                 kref_get(&tape->kref);
466         mutex_unlock(&idetape_ref_mutex);
467         return tape;
468 }
469
470 static void ide_tape_release(struct kref *);
471
472 static void ide_tape_put(struct ide_tape_obj *tape)
473 {
474         mutex_lock(&idetape_ref_mutex);
475         kref_put(&tape->kref, ide_tape_release);
476         mutex_unlock(&idetape_ref_mutex);
477 }
478
479 /*
480  * The variables below are used for the character device interface. Additional
481  * state variables are defined in our ide_drive_t structure.
482  */
483 static struct ide_tape_obj *idetape_devs[MAX_HWIFS * MAX_DRIVES];
484
485 #define ide_tape_f(file) ((file)->private_data)
486
487 static struct ide_tape_obj *ide_tape_chrdev_get(unsigned int i)
488 {
489         struct ide_tape_obj *tape = NULL;
490
491         mutex_lock(&idetape_ref_mutex);
492         tape = idetape_devs[i];
493         if (tape)
494                 kref_get(&tape->kref);
495         mutex_unlock(&idetape_ref_mutex);
496         return tape;
497 }
498
499 static void idetape_input_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
500                                   unsigned int bcount)
501 {
502         struct idetape_bh *bh = pc->bh;
503         int count;
504
505         while (bcount) {
506                 if (bh == NULL) {
507                         printk(KERN_ERR "ide-tape: bh == NULL in "
508                                 "idetape_input_buffers\n");
509                         ide_atapi_discard_data(drive, bcount);
510                         return;
511                 }
512                 count = min(
513                         (unsigned int)(bh->b_size - atomic_read(&bh->b_count)),
514                         bcount);
515                 HWIF(drive)->atapi_input_bytes(drive, bh->b_data +
516                                         atomic_read(&bh->b_count), count);
517                 bcount -= count;
518                 atomic_add(count, &bh->b_count);
519                 if (atomic_read(&bh->b_count) == bh->b_size) {
520                         bh = bh->b_reqnext;
521                         if (bh)
522                                 atomic_set(&bh->b_count, 0);
523                 }
524         }
525         pc->bh = bh;
526 }
527
528 static void idetape_output_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
529                                    unsigned int bcount)
530 {
531         struct idetape_bh *bh = pc->bh;
532         int count;
533
534         while (bcount) {
535                 if (bh == NULL) {
536                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
537                                         __func__);
538                         return;
539                 }
540                 count = min((unsigned int)pc->b_count, (unsigned int)bcount);
541                 HWIF(drive)->atapi_output_bytes(drive, pc->b_data, count);
542                 bcount -= count;
543                 pc->b_data += count;
544                 pc->b_count -= count;
545                 if (!pc->b_count) {
546                         bh = bh->b_reqnext;
547                         pc->bh = bh;
548                         if (bh) {
549                                 pc->b_data = bh->b_data;
550                                 pc->b_count = atomic_read(&bh->b_count);
551                         }
552                 }
553         }
554 }
555
556 static void idetape_update_buffers(struct ide_atapi_pc *pc)
557 {
558         struct idetape_bh *bh = pc->bh;
559         int count;
560         unsigned int bcount = pc->xferred;
561
562         if (pc->flags & PC_FLAG_WRITING)
563                 return;
564         while (bcount) {
565                 if (bh == NULL) {
566                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
567                                         __func__);
568                         return;
569                 }
570                 count = min((unsigned int)bh->b_size, (unsigned int)bcount);
571                 atomic_set(&bh->b_count, count);
572                 if (atomic_read(&bh->b_count) == bh->b_size)
573                         bh = bh->b_reqnext;
574                 bcount -= count;
575         }
576         pc->bh = bh;
577 }
578
579 /*
580  *      idetape_next_pc_storage returns a pointer to a place in which we can
581  *      safely store a packet command, even though we intend to leave the
582  *      driver. A storage space for a maximum of IDETAPE_PC_STACK packet
583  *      commands is allocated at initialization time.
584  */
585 static struct ide_atapi_pc *idetape_next_pc_storage(ide_drive_t *drive)
586 {
587         idetape_tape_t *tape = drive->driver_data;
588
589         debug_log(DBG_PCRQ_STACK, "pc_stack_index=%d\n", tape->pc_stack_index);
590
591         if (tape->pc_stack_index == IDETAPE_PC_STACK)
592                 tape->pc_stack_index = 0;
593         return (&tape->pc_stack[tape->pc_stack_index++]);
594 }
595
596 /*
597  *      idetape_next_rq_storage is used along with idetape_next_pc_storage.
598  *      Since we queue packet commands in the request queue, we need to
599  *      allocate a request, along with the allocation of a packet command.
600  */
601
602 /**************************************************************
603  *                                                            *
604  *  This should get fixed to use kmalloc(.., GFP_ATOMIC)      *
605  *  followed later on by kfree().   -ml                       *
606  *                                                            *
607  **************************************************************/
608
609 static struct request *idetape_next_rq_storage(ide_drive_t *drive)
610 {
611         idetape_tape_t *tape = drive->driver_data;
612
613         debug_log(DBG_PCRQ_STACK, "rq_stack_index=%d\n", tape->rq_stack_index);
614
615         if (tape->rq_stack_index == IDETAPE_PC_STACK)
616                 tape->rq_stack_index = 0;
617         return (&tape->rq_stack[tape->rq_stack_index++]);
618 }
619
620 static void idetape_init_pc(struct ide_atapi_pc *pc)
621 {
622         memset(pc->c, 0, 12);
623         pc->retries = 0;
624         pc->flags = 0;
625         pc->req_xfer = 0;
626         pc->buf = pc->pc_buf;
627         pc->buf_size = IDETAPE_PC_BUFFER_SIZE;
628         pc->bh = NULL;
629         pc->b_data = NULL;
630 }
631
632 /*
633  * called on each failed packet command retry to analyze the request sense. We
634  * currently do not utilize this information.
635  */
636 static void idetape_analyze_error(ide_drive_t *drive, u8 *sense)
637 {
638         idetape_tape_t *tape = drive->driver_data;
639         struct ide_atapi_pc *pc = tape->failed_pc;
640
641         tape->sense_key = sense[2] & 0xF;
642         tape->asc       = sense[12];
643         tape->ascq      = sense[13];
644
645         debug_log(DBG_ERR, "pc = %x, sense key = %x, asc = %x, ascq = %x\n",
646                  pc->c[0], tape->sense_key, tape->asc, tape->ascq);
647
648         /* Correct pc->xferred by asking the tape.       */
649         if (pc->flags & PC_FLAG_DMA_ERROR) {
650                 pc->xferred = pc->req_xfer -
651                         tape->blk_size *
652                         be32_to_cpu(get_unaligned((u32 *)&sense[3]));
653                 idetape_update_buffers(pc);
654         }
655
656         /*
657          * If error was the result of a zero-length read or write command,
658          * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
659          * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
660          */
661         if ((pc->c[0] == READ_6 || pc->c[0] == WRITE_6)
662             /* length == 0 */
663             && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) {
664                 if (tape->sense_key == 5) {
665                         /* don't report an error, everything's ok */
666                         pc->error = 0;
667                         /* don't retry read/write */
668                         pc->flags |= PC_FLAG_ABORT;
669                 }
670         }
671         if (pc->c[0] == READ_6 && (sense[2] & 0x80)) {
672                 pc->error = IDETAPE_ERROR_FILEMARK;
673                 pc->flags |= PC_FLAG_ABORT;
674         }
675         if (pc->c[0] == WRITE_6) {
676                 if ((sense[2] & 0x40) || (tape->sense_key == 0xd
677                      && tape->asc == 0x0 && tape->ascq == 0x2)) {
678                         pc->error = IDETAPE_ERROR_EOD;
679                         pc->flags |= PC_FLAG_ABORT;
680                 }
681         }
682         if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
683                 if (tape->sense_key == 8) {
684                         pc->error = IDETAPE_ERROR_EOD;
685                         pc->flags |= PC_FLAG_ABORT;
686                 }
687                 if (!(pc->flags & PC_FLAG_ABORT) &&
688                     pc->xferred)
689                         pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
690         }
691 }
692
693 static void idetape_activate_next_stage(ide_drive_t *drive)
694 {
695         idetape_tape_t *tape = drive->driver_data;
696         idetape_stage_t *stage = tape->next_stage;
697         struct request *rq = &stage->rq;
698
699         debug_log(DBG_PROCS, "Enter %s\n", __func__);
700
701         if (stage == NULL) {
702                 printk(KERN_ERR "ide-tape: bug: Trying to activate a non"
703                                 " existing stage\n");
704                 return;
705         }
706
707         rq->rq_disk = tape->disk;
708         rq->buffer = NULL;
709         rq->special = (void *)stage->bh;
710         tape->active_data_rq = rq;
711         tape->active_stage = stage;
712         tape->next_stage = stage->next;
713 }
714
715 /* Free a stage along with its related buffers completely. */
716 static void __idetape_kfree_stage(idetape_stage_t *stage)
717 {
718         struct idetape_bh *prev_bh, *bh = stage->bh;
719         int size;
720
721         while (bh != NULL) {
722                 if (bh->b_data != NULL) {
723                         size = (int) bh->b_size;
724                         while (size > 0) {
725                                 free_page((unsigned long) bh->b_data);
726                                 size -= PAGE_SIZE;
727                                 bh->b_data += PAGE_SIZE;
728                         }
729                 }
730                 prev_bh = bh;
731                 bh = bh->b_reqnext;
732                 kfree(prev_bh);
733         }
734         kfree(stage);
735 }
736
737 static void idetape_kfree_stage(idetape_tape_t *tape, idetape_stage_t *stage)
738 {
739         __idetape_kfree_stage(stage);
740 }
741
742 /*
743  * Remove tape->first_stage from the pipeline. The caller should avoid race
744  * conditions.
745  */
746 static void idetape_remove_stage_head(ide_drive_t *drive)
747 {
748         idetape_tape_t *tape = drive->driver_data;
749         idetape_stage_t *stage;
750
751         debug_log(DBG_PROCS, "Enter %s\n", __func__);
752
753         if (tape->first_stage == NULL) {
754                 printk(KERN_ERR "ide-tape: bug: tape->first_stage is NULL\n");
755                 return;
756         }
757         if (tape->active_stage == tape->first_stage) {
758                 printk(KERN_ERR "ide-tape: bug: Trying to free our active "
759                                 "pipeline stage\n");
760                 return;
761         }
762         stage = tape->first_stage;
763         tape->first_stage = stage->next;
764         idetape_kfree_stage(tape, stage);
765         tape->nr_stages--;
766         if (tape->first_stage == NULL) {
767                 tape->last_stage = NULL;
768                 if (tape->next_stage != NULL)
769                         printk(KERN_ERR "ide-tape: bug: tape->next_stage !="
770                                         " NULL\n");
771                 if (tape->nr_stages)
772                         printk(KERN_ERR "ide-tape: bug: nr_stages should be 0 "
773                                         "now\n");
774         }
775 }
776
777 /*
778  * This will free all the pipeline stages starting from new_last_stage->next
779  * to the end of the list, and point tape->last_stage to new_last_stage.
780  */
781 static void idetape_abort_pipeline(ide_drive_t *drive,
782                                    idetape_stage_t *new_last_stage)
783 {
784         idetape_tape_t *tape = drive->driver_data;
785         idetape_stage_t *stage = new_last_stage->next;
786         idetape_stage_t *nstage;
787
788         debug_log(DBG_PROCS, "%s: Enter %s\n", tape->name, __func__);
789
790         while (stage) {
791                 nstage = stage->next;
792                 idetape_kfree_stage(tape, stage);
793                 --tape->nr_stages;
794                 --tape->nr_pending_stages;
795                 stage = nstage;
796         }
797         if (new_last_stage)
798                 new_last_stage->next = NULL;
799         tape->last_stage = new_last_stage;
800         tape->next_stage = NULL;
801 }
802
803 /*
804  * Finish servicing a request and insert a pending pipeline request into the
805  * main device queue.
806  */
807 static int idetape_end_request(ide_drive_t *drive, int uptodate, int nr_sects)
808 {
809         struct request *rq = HWGROUP(drive)->rq;
810         idetape_tape_t *tape = drive->driver_data;
811         unsigned long flags;
812         int error;
813         int remove_stage = 0;
814         idetape_stage_t *active_stage;
815
816         debug_log(DBG_PROCS, "Enter %s\n", __func__);
817
818         switch (uptodate) {
819         case 0: error = IDETAPE_ERROR_GENERAL; break;
820         case 1: error = 0; break;
821         default: error = uptodate;
822         }
823         rq->errors = error;
824         if (error)
825                 tape->failed_pc = NULL;
826
827         if (!blk_special_request(rq)) {
828                 ide_end_request(drive, uptodate, nr_sects);
829                 return 0;
830         }
831
832         spin_lock_irqsave(&tape->lock, flags);
833
834         /* The request was a pipelined data transfer request */
835         if (tape->active_data_rq == rq) {
836                 active_stage = tape->active_stage;
837                 tape->active_stage = NULL;
838                 tape->active_data_rq = NULL;
839                 tape->nr_pending_stages--;
840                 if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
841                         remove_stage = 1;
842                         if (error) {
843                                 set_bit(IDETAPE_FLAG_PIPELINE_ERR,
844                                         &tape->flags);
845                                 if (error == IDETAPE_ERROR_EOD)
846                                         idetape_abort_pipeline(drive,
847                                                                 active_stage);
848                         }
849                 } else if (rq->cmd[0] & REQ_IDETAPE_READ) {
850                         if (error == IDETAPE_ERROR_EOD) {
851                                 set_bit(IDETAPE_FLAG_PIPELINE_ERR,
852                                         &tape->flags);
853                                 idetape_abort_pipeline(drive, active_stage);
854                         }
855                 }
856                 if (tape->next_stage != NULL) {
857                         idetape_activate_next_stage(drive);
858
859                         /* Insert the next request into the request queue. */
860                         (void)ide_do_drive_cmd(drive, tape->active_data_rq,
861                                                 ide_end);
862                 } else if (!error) {
863                         /*
864                          * This is a part of the feedback loop which tries to
865                          * find the optimum number of stages. We are starting
866                          * from a minimum maximum number of stages, and if we
867                          * sense that the pipeline is empty, we try to increase
868                          * it, until we reach the user compile time memory
869                          * limit.
870                          */
871                         int i = (tape->max_pipeline - tape->min_pipeline) / 10;
872
873                         tape->max_stages += max(i, 1);
874                         tape->max_stages = max(tape->max_stages,
875                                                 tape->min_pipeline);
876                         tape->max_stages = min(tape->max_stages,
877                                                 tape->max_pipeline);
878                 }
879         }
880         ide_end_drive_cmd(drive, 0, 0);
881
882         if (remove_stage)
883                 idetape_remove_stage_head(drive);
884         if (tape->active_data_rq == NULL)
885                 clear_bit(IDETAPE_FLAG_PIPELINE_ACTIVE, &tape->flags);
886         spin_unlock_irqrestore(&tape->lock, flags);
887         return 0;
888 }
889
890 static ide_startstop_t idetape_request_sense_callback(ide_drive_t *drive)
891 {
892         idetape_tape_t *tape = drive->driver_data;
893
894         debug_log(DBG_PROCS, "Enter %s\n", __func__);
895
896         if (!tape->pc->error) {
897                 idetape_analyze_error(drive, tape->pc->buf);
898                 idetape_end_request(drive, 1, 0);
899         } else {
900                 printk(KERN_ERR "ide-tape: Error in REQUEST SENSE itself - "
901                                 "Aborting request!\n");
902                 idetape_end_request(drive, 0, 0);
903         }
904         return ide_stopped;
905 }
906
907 static void idetape_create_request_sense_cmd(struct ide_atapi_pc *pc)
908 {
909         idetape_init_pc(pc);
910         pc->c[0] = REQUEST_SENSE;
911         pc->c[4] = 20;
912         pc->req_xfer = 20;
913         pc->idetape_callback = &idetape_request_sense_callback;
914 }
915
916 static void idetape_init_rq(struct request *rq, u8 cmd)
917 {
918         memset(rq, 0, sizeof(*rq));
919         rq->cmd_type = REQ_TYPE_SPECIAL;
920         rq->cmd[0] = cmd;
921 }
922
923 /*
924  * Generate a new packet command request in front of the request queue, before
925  * the current request, so that it will be processed immediately, on the next
926  * pass through the driver. The function below is called from the request
927  * handling part of the driver (the "bottom" part). Safe storage for the request
928  * should be allocated with ide_tape_next_{pc,rq}_storage() prior to that.
929  *
930  * Memory for those requests is pre-allocated at initialization time, and is
931  * limited to IDETAPE_PC_STACK requests. We assume that we have enough space for
932  * the maximum possible number of inter-dependent packet commands.
933  *
934  * The higher level of the driver - The ioctl handler and the character device
935  * handling functions should queue request to the lower level part and wait for
936  * their completion using idetape_queue_pc_tail or idetape_queue_rw_tail.
937  */
938 static void idetape_queue_pc_head(ide_drive_t *drive, struct ide_atapi_pc *pc,
939                                   struct request *rq)
940 {
941         struct ide_tape_obj *tape = drive->driver_data;
942
943         idetape_init_rq(rq, REQ_IDETAPE_PC1);
944         rq->buffer = (char *) pc;
945         rq->rq_disk = tape->disk;
946         (void) ide_do_drive_cmd(drive, rq, ide_preempt);
947 }
948
949 /*
950  *      idetape_retry_pc is called when an error was detected during the
951  *      last packet command. We queue a request sense packet command in
952  *      the head of the request list.
953  */
954 static ide_startstop_t idetape_retry_pc (ide_drive_t *drive)
955 {
956         idetape_tape_t *tape = drive->driver_data;
957         struct ide_atapi_pc *pc;
958         struct request *rq;
959
960         (void)ide_read_error(drive);
961         pc = idetape_next_pc_storage(drive);
962         rq = idetape_next_rq_storage(drive);
963         idetape_create_request_sense_cmd(pc);
964         set_bit(IDETAPE_FLAG_IGNORE_DSC, &tape->flags);
965         idetape_queue_pc_head(drive, pc, rq);
966         return ide_stopped;
967 }
968
969 /*
970  * Postpone the current request so that ide.c will be able to service requests
971  * from another device on the same hwgroup while we are polling for DSC.
972  */
973 static void idetape_postpone_request(ide_drive_t *drive)
974 {
975         idetape_tape_t *tape = drive->driver_data;
976
977         debug_log(DBG_PROCS, "Enter %s\n", __func__);
978
979         tape->postponed_rq = HWGROUP(drive)->rq;
980         ide_stall_queue(drive, tape->dsc_poll_freq);
981 }
982
983 typedef void idetape_io_buf(ide_drive_t *, struct ide_atapi_pc *, unsigned int);
984
985 /*
986  * This is the usual interrupt handler which will be called during a packet
987  * command. We will transfer some of the data (as requested by the drive) and
988  * will re-point interrupt handler to us. When data transfer is finished, we
989  * will act according to the algorithm described before
990  * idetape_issue_pc.
991  */
992 static ide_startstop_t idetape_pc_intr(ide_drive_t *drive)
993 {
994         ide_hwif_t *hwif = drive->hwif;
995         idetape_tape_t *tape = drive->driver_data;
996         struct ide_atapi_pc *pc = tape->pc;
997         xfer_func_t *xferfunc;
998         idetape_io_buf *iobuf;
999         unsigned int temp;
1000 #if SIMULATE_ERRORS
1001         static int error_sim_count;
1002 #endif
1003         u16 bcount;
1004         u8 stat, ireason;
1005
1006         debug_log(DBG_PROCS, "Enter %s - interrupt handler\n", __func__);
1007
1008         /* Clear the interrupt */
1009         stat = ide_read_status(drive);
1010
1011         if (pc->flags & PC_FLAG_DMA_IN_PROGRESS) {
1012                 if (hwif->ide_dma_end(drive) || (stat & ERR_STAT)) {
1013                         /*
1014                          * A DMA error is sometimes expected. For example,
1015                          * if the tape is crossing a filemark during a
1016                          * READ command, it will issue an irq and position
1017                          * itself before the filemark, so that only a partial
1018                          * data transfer will occur (which causes the DMA
1019                          * error). In that case, we will later ask the tape
1020                          * how much bytes of the original request were
1021                          * actually transferred (we can't receive that
1022                          * information from the DMA engine on most chipsets).
1023                          */
1024
1025                         /*
1026                          * On the contrary, a DMA error is never expected;
1027                          * it usually indicates a hardware error or abort.
1028                          * If the tape crosses a filemark during a READ
1029                          * command, it will issue an irq and position itself
1030                          * after the filemark (not before). Only a partial
1031                          * data transfer will occur, but no DMA error.
1032                          * (AS, 19 Apr 2001)
1033                          */
1034                         pc->flags |= PC_FLAG_DMA_ERROR;
1035                 } else {
1036                         pc->xferred = pc->req_xfer;
1037                         idetape_update_buffers(pc);
1038                 }
1039                 debug_log(DBG_PROCS, "DMA finished\n");
1040
1041         }
1042
1043         /* No more interrupts */
1044         if ((stat & DRQ_STAT) == 0) {
1045                 debug_log(DBG_SENSE, "Packet command completed, %d bytes"
1046                                 " transferred\n", pc->xferred);
1047
1048                 pc->flags &= ~PC_FLAG_DMA_IN_PROGRESS;
1049                 local_irq_enable();
1050
1051 #if SIMULATE_ERRORS
1052                 if ((pc->c[0] == WRITE_6 || pc->c[0] == READ_6) &&
1053                     (++error_sim_count % 100) == 0) {
1054                         printk(KERN_INFO "ide-tape: %s: simulating error\n",
1055                                 tape->name);
1056                         stat |= ERR_STAT;
1057                 }
1058 #endif
1059                 if ((stat & ERR_STAT) && pc->c[0] == REQUEST_SENSE)
1060                         stat &= ~ERR_STAT;
1061                 if ((stat & ERR_STAT) || (pc->flags & PC_FLAG_DMA_ERROR)) {
1062                         /* Error detected */
1063                         debug_log(DBG_ERR, "%s: I/O error\n", tape->name);
1064
1065                         if (pc->c[0] == REQUEST_SENSE) {
1066                                 printk(KERN_ERR "ide-tape: I/O error in request"
1067                                                 " sense command\n");
1068                                 return ide_do_reset(drive);
1069                         }
1070                         debug_log(DBG_ERR, "[cmd %x]: check condition\n",
1071                                         pc->c[0]);
1072
1073                         /* Retry operation */
1074                         return idetape_retry_pc(drive);
1075                 }
1076                 pc->error = 0;
1077                 if ((pc->flags & PC_FLAG_WAIT_FOR_DSC) &&
1078                     (stat & SEEK_STAT) == 0) {
1079                         /* Media access command */
1080                         tape->dsc_polling_start = jiffies;
1081                         tape->dsc_poll_freq = IDETAPE_DSC_MA_FAST;
1082                         tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
1083                         /* Allow ide.c to handle other requests */
1084                         idetape_postpone_request(drive);
1085                         return ide_stopped;
1086                 }
1087                 if (tape->failed_pc == pc)
1088                         tape->failed_pc = NULL;
1089                 /* Command finished - Call the callback function */
1090                 return pc->idetape_callback(drive);
1091         }
1092
1093         if (pc->flags & PC_FLAG_DMA_IN_PROGRESS) {
1094                 pc->flags &= ~PC_FLAG_DMA_IN_PROGRESS;
1095                 printk(KERN_ERR "ide-tape: The tape wants to issue more "
1096                                 "interrupts in DMA mode\n");
1097                 printk(KERN_ERR "ide-tape: DMA disabled, reverting to PIO\n");
1098                 ide_dma_off(drive);
1099                 return ide_do_reset(drive);
1100         }
1101         /* Get the number of bytes to transfer on this interrupt. */
1102         bcount = (hwif->INB(hwif->io_ports[IDE_BCOUNTH_OFFSET]) << 8) |
1103                   hwif->INB(hwif->io_ports[IDE_BCOUNTL_OFFSET]);
1104
1105         ireason = hwif->INB(hwif->io_ports[IDE_IREASON_OFFSET]);
1106
1107         if (ireason & CD) {
1108                 printk(KERN_ERR "ide-tape: CoD != 0 in %s\n", __func__);
1109                 return ide_do_reset(drive);
1110         }
1111         if (((ireason & IO) == IO) == !!(pc->flags & PC_FLAG_WRITING)) {
1112                 /* Hopefully, we will never get here */
1113                 printk(KERN_ERR "ide-tape: We wanted to %s, ",
1114                                 (ireason & IO) ? "Write" : "Read");
1115                 printk(KERN_ERR "ide-tape: but the tape wants us to %s !\n",
1116                                 (ireason & IO) ? "Read" : "Write");
1117                 return ide_do_reset(drive);
1118         }
1119         if (!(pc->flags & PC_FLAG_WRITING)) {
1120                 /* Reading - Check that we have enough space */
1121                 temp = pc->xferred + bcount;
1122                 if (temp > pc->req_xfer) {
1123                         if (temp > pc->buf_size) {
1124                                 printk(KERN_ERR "ide-tape: The tape wants to "
1125                                         "send us more data than expected "
1126                                         "- discarding data\n");
1127                                 ide_atapi_discard_data(drive, bcount);
1128                                 ide_set_handler(drive, &idetape_pc_intr,
1129                                                 IDETAPE_WAIT_CMD, NULL);
1130                                 return ide_started;
1131                         }
1132                         debug_log(DBG_SENSE, "The tape wants to send us more "
1133                                 "data than expected - allowing transfer\n");
1134                 }
1135                 iobuf = &idetape_input_buffers;
1136                 xferfunc = hwif->atapi_input_bytes;
1137         } else {
1138                 iobuf = &idetape_output_buffers;
1139                 xferfunc = hwif->atapi_output_bytes;
1140         }
1141
1142         if (pc->bh)
1143                 iobuf(drive, pc, bcount);
1144         else
1145                 xferfunc(drive, pc->cur_pos, bcount);
1146
1147         /* Update the current position */
1148         pc->xferred += bcount;
1149         pc->cur_pos += bcount;
1150
1151         debug_log(DBG_SENSE, "[cmd %x] transferred %d bytes on that intr.\n",
1152                         pc->c[0], bcount);
1153
1154         /* And set the interrupt handler again */
1155         ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1156         return ide_started;
1157 }
1158
1159 /*
1160  * Packet Command Interface
1161  *
1162  * The current Packet Command is available in tape->pc, and will not change
1163  * until we finish handling it. Each packet command is associated with a
1164  * callback function that will be called when the command is finished.
1165  *
1166  * The handling will be done in three stages:
1167  *
1168  * 1. idetape_issue_pc will send the packet command to the drive, and will set
1169  * the interrupt handler to idetape_pc_intr.
1170  *
1171  * 2. On each interrupt, idetape_pc_intr will be called. This step will be
1172  * repeated until the device signals us that no more interrupts will be issued.
1173  *
1174  * 3. ATAPI Tape media access commands have immediate status with a delayed
1175  * process. In case of a successful initiation of a media access packet command,
1176  * the DSC bit will be set when the actual execution of the command is finished.
1177  * Since the tape drive will not issue an interrupt, we have to poll for this
1178  * event. In this case, we define the request as "low priority request" by
1179  * setting rq_status to IDETAPE_RQ_POSTPONED, set a timer to poll for DSC and
1180  * exit the driver.
1181  *
1182  * ide.c will then give higher priority to requests which originate from the
1183  * other device, until will change rq_status to RQ_ACTIVE.
1184  *
1185  * 4. When the packet command is finished, it will be checked for errors.
1186  *
1187  * 5. In case an error was found, we queue a request sense packet command in
1188  * front of the request queue and retry the operation up to
1189  * IDETAPE_MAX_PC_RETRIES times.
1190  *
1191  * 6. In case no error was found, or we decided to give up and not to retry
1192  * again, the callback function will be called and then we will handle the next
1193  * request.
1194  */
1195 static ide_startstop_t idetape_transfer_pc(ide_drive_t *drive)
1196 {
1197         ide_hwif_t *hwif = drive->hwif;
1198         idetape_tape_t *tape = drive->driver_data;
1199         struct ide_atapi_pc *pc = tape->pc;
1200         int retries = 100;
1201         ide_startstop_t startstop;
1202         u8 ireason;
1203
1204         if (ide_wait_stat(&startstop, drive, DRQ_STAT, BUSY_STAT, WAIT_READY)) {
1205                 printk(KERN_ERR "ide-tape: Strange, packet command initiated "
1206                                 "yet DRQ isn't asserted\n");
1207                 return startstop;
1208         }
1209         ireason = hwif->INB(hwif->io_ports[IDE_IREASON_OFFSET]);
1210         while (retries-- && ((ireason & CD) == 0 || (ireason & IO))) {
1211                 printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while issuing "
1212                                 "a packet command, retrying\n");
1213                 udelay(100);
1214                 ireason = hwif->INB(hwif->io_ports[IDE_IREASON_OFFSET]);
1215                 if (retries == 0) {
1216                         printk(KERN_ERR "ide-tape: (IO,CoD != (0,1) while "
1217                                         "issuing a packet command, ignoring\n");
1218                         ireason |= CD;
1219                         ireason &= ~IO;
1220                 }
1221         }
1222         if ((ireason & CD) == 0 || (ireason & IO)) {
1223                 printk(KERN_ERR "ide-tape: (IO,CoD) != (0,1) while issuing "
1224                                 "a packet command\n");
1225                 return ide_do_reset(drive);
1226         }
1227         /* Set the interrupt routine */
1228         ide_set_handler(drive, &idetape_pc_intr, IDETAPE_WAIT_CMD, NULL);
1229 #ifdef CONFIG_BLK_DEV_IDEDMA
1230         /* Begin DMA, if necessary */
1231         if (pc->flags & PC_FLAG_DMA_IN_PROGRESS)
1232                 hwif->dma_start(drive);
1233 #endif
1234         /* Send the actual packet */
1235         HWIF(drive)->atapi_output_bytes(drive, pc->c, 12);
1236         return ide_started;
1237 }
1238
1239 static ide_startstop_t idetape_issue_pc(ide_drive_t *drive,
1240                 struct ide_atapi_pc *pc)
1241 {
1242         ide_hwif_t *hwif = drive->hwif;
1243         idetape_tape_t *tape = drive->driver_data;
1244         int dma_ok = 0;
1245         u16 bcount;
1246
1247         if (tape->pc->c[0] == REQUEST_SENSE &&
1248             pc->c[0] == REQUEST_SENSE) {
1249                 printk(KERN_ERR "ide-tape: possible ide-tape.c bug - "
1250                         "Two request sense in serial were issued\n");
1251         }
1252
1253         if (tape->failed_pc == NULL && pc->c[0] != REQUEST_SENSE)
1254                 tape->failed_pc = pc;
1255         /* Set the current packet command */
1256         tape->pc = pc;
1257
1258         if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
1259                 (pc->flags & PC_FLAG_ABORT)) {
1260                 /*
1261                  * We will "abort" retrying a packet command in case legitimate
1262                  * error code was received (crossing a filemark, or end of the
1263                  * media, for example).
1264                  */
1265                 if (!(pc->flags & PC_FLAG_ABORT)) {
1266                         if (!(pc->c[0] == TEST_UNIT_READY &&
1267                               tape->sense_key == 2 && tape->asc == 4 &&
1268                              (tape->ascq == 1 || tape->ascq == 8))) {
1269                                 printk(KERN_ERR "ide-tape: %s: I/O error, "
1270                                                 "pc = %2x, key = %2x, "
1271                                                 "asc = %2x, ascq = %2x\n",
1272                                                 tape->name, pc->c[0],
1273                                                 tape->sense_key, tape->asc,
1274                                                 tape->ascq);
1275                         }
1276                         /* Giving up */
1277                         pc->error = IDETAPE_ERROR_GENERAL;
1278                 }
1279                 tape->failed_pc = NULL;
1280                 return pc->idetape_callback(drive);
1281         }
1282         debug_log(DBG_SENSE, "Retry #%d, cmd = %02X\n", pc->retries, pc->c[0]);
1283
1284         pc->retries++;
1285         /* We haven't transferred any data yet */
1286         pc->xferred = 0;
1287         pc->cur_pos = pc->buf;
1288         /* Request to transfer the entire buffer at once */
1289         bcount = pc->req_xfer;
1290
1291         if (pc->flags & PC_FLAG_DMA_ERROR) {
1292                 pc->flags &= ~PC_FLAG_DMA_ERROR;
1293                 printk(KERN_WARNING "ide-tape: DMA disabled, "
1294                                 "reverting to PIO\n");
1295                 ide_dma_off(drive);
1296         }
1297         if ((pc->flags & PC_FLAG_DMA_RECOMMENDED) && drive->using_dma)
1298                 dma_ok = !hwif->dma_setup(drive);
1299
1300         ide_pktcmd_tf_load(drive, IDE_TFLAG_NO_SELECT_MASK |
1301                            IDE_TFLAG_OUT_DEVICE, bcount, dma_ok);
1302
1303         if (dma_ok)
1304                 /* Will begin DMA later */
1305                 pc->flags |= PC_FLAG_DMA_IN_PROGRESS;
1306         if (test_bit(IDETAPE_FLAG_DRQ_INTERRUPT, &tape->flags)) {
1307                 ide_execute_command(drive, WIN_PACKETCMD, &idetape_transfer_pc,
1308                                     IDETAPE_WAIT_CMD, NULL);
1309                 return ide_started;
1310         } else {
1311                 hwif->OUTB(WIN_PACKETCMD, hwif->io_ports[IDE_COMMAND_OFFSET]);
1312                 return idetape_transfer_pc(drive);
1313         }
1314 }
1315
1316 static ide_startstop_t idetape_pc_callback(ide_drive_t *drive)
1317 {
1318         idetape_tape_t *tape = drive->driver_data;
1319
1320         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1321
1322         idetape_end_request(drive, tape->pc->error ? 0 : 1, 0);
1323         return ide_stopped;
1324 }
1325
1326 /* A mode sense command is used to "sense" tape parameters. */
1327 static void idetape_create_mode_sense_cmd(struct ide_atapi_pc *pc, u8 page_code)
1328 {
1329         idetape_init_pc(pc);
1330         pc->c[0] = MODE_SENSE;
1331         if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
1332                 /* DBD = 1 - Don't return block descriptors */
1333                 pc->c[1] = 8;
1334         pc->c[2] = page_code;
1335         /*
1336          * Changed pc->c[3] to 0 (255 will at best return unused info).
1337          *
1338          * For SCSI this byte is defined as subpage instead of high byte
1339          * of length and some IDE drives seem to interpret it this way
1340          * and return an error when 255 is used.
1341          */
1342         pc->c[3] = 0;
1343         /* We will just discard data in that case */
1344         pc->c[4] = 255;
1345         if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
1346                 pc->req_xfer = 12;
1347         else if (page_code == IDETAPE_CAPABILITIES_PAGE)
1348                 pc->req_xfer = 24;
1349         else
1350                 pc->req_xfer = 50;
1351         pc->idetape_callback = &idetape_pc_callback;
1352 }
1353
1354 static void idetape_calculate_speeds(ide_drive_t *drive)
1355 {
1356         idetape_tape_t *tape = drive->driver_data;
1357
1358         if (time_after(jiffies,
1359                         tape->controlled_pipeline_head_time + 120 * HZ)) {
1360                 tape->controlled_previous_pipeline_head =
1361                         tape->controlled_last_pipeline_head;
1362                 tape->controlled_previous_head_time =
1363                         tape->controlled_pipeline_head_time;
1364                 tape->controlled_last_pipeline_head = tape->pipeline_head;
1365                 tape->controlled_pipeline_head_time = jiffies;
1366         }
1367         if (time_after(jiffies, tape->controlled_pipeline_head_time + 60 * HZ))
1368                 tape->controlled_pipeline_head_speed = (tape->pipeline_head -
1369                                 tape->controlled_last_pipeline_head) * 32 * HZ /
1370                                 (jiffies - tape->controlled_pipeline_head_time);
1371         else if (time_after(jiffies, tape->controlled_previous_head_time))
1372                 tape->controlled_pipeline_head_speed = (tape->pipeline_head -
1373                                 tape->controlled_previous_pipeline_head) * 32 *
1374                         HZ / (jiffies - tape->controlled_previous_head_time);
1375
1376         if (tape->nr_pending_stages < tape->max_stages/*- 1 */) {
1377                 /* -1 for read mode error recovery */
1378                 if (time_after(jiffies, tape->uncontrolled_previous_head_time +
1379                                         10 * HZ)) {
1380                         tape->uncontrolled_pipeline_head_time = jiffies;
1381                         tape->uncontrolled_pipeline_head_speed =
1382                                 (tape->pipeline_head -
1383                                  tape->uncontrolled_previous_pipeline_head) *
1384                                 32 * HZ / (jiffies -
1385                                         tape->uncontrolled_previous_head_time);
1386                 }
1387         } else {
1388                 tape->uncontrolled_previous_head_time = jiffies;
1389                 tape->uncontrolled_previous_pipeline_head = tape->pipeline_head;
1390                 if (time_after(jiffies, tape->uncontrolled_pipeline_head_time +
1391                                         30 * HZ))
1392                         tape->uncontrolled_pipeline_head_time = jiffies;
1393
1394         }
1395         tape->pipeline_head_speed = max(tape->uncontrolled_pipeline_head_speed,
1396                                         tape->controlled_pipeline_head_speed);
1397
1398         if (tape->speed_control == 1) {
1399                 if (tape->nr_pending_stages >= tape->max_stages / 2)
1400                         tape->max_insert_speed = tape->pipeline_head_speed +
1401                                 (1100 - tape->pipeline_head_speed) * 2 *
1402                                 (tape->nr_pending_stages - tape->max_stages / 2)
1403                                 / tape->max_stages;
1404                 else
1405                         tape->max_insert_speed = 500 +
1406                                 (tape->pipeline_head_speed - 500) * 2 *
1407                                 tape->nr_pending_stages / tape->max_stages;
1408
1409                 if (tape->nr_pending_stages >= tape->max_stages * 99 / 100)
1410                         tape->max_insert_speed = 5000;
1411         } else
1412                 tape->max_insert_speed = tape->speed_control;
1413
1414         tape->max_insert_speed = max(tape->max_insert_speed, 500);
1415 }
1416
1417 static ide_startstop_t idetape_media_access_finished(ide_drive_t *drive)
1418 {
1419         idetape_tape_t *tape = drive->driver_data;
1420         struct ide_atapi_pc *pc = tape->pc;
1421         u8 stat;
1422
1423         stat = ide_read_status(drive);
1424
1425         if (stat & SEEK_STAT) {
1426                 if (stat & ERR_STAT) {
1427                         /* Error detected */
1428                         if (pc->c[0] != TEST_UNIT_READY)
1429                                 printk(KERN_ERR "ide-tape: %s: I/O error, ",
1430                                                 tape->name);
1431                         /* Retry operation */
1432                         return idetape_retry_pc(drive);
1433                 }
1434                 pc->error = 0;
1435                 if (tape->failed_pc == pc)
1436                         tape->failed_pc = NULL;
1437         } else {
1438                 pc->error = IDETAPE_ERROR_GENERAL;
1439                 tape->failed_pc = NULL;
1440         }
1441         return pc->idetape_callback(drive);
1442 }
1443
1444 static ide_startstop_t idetape_rw_callback(ide_drive_t *drive)
1445 {
1446         idetape_tape_t *tape = drive->driver_data;
1447         struct request *rq = HWGROUP(drive)->rq;
1448         int blocks = tape->pc->xferred / tape->blk_size;
1449
1450         tape->avg_size += blocks * tape->blk_size;
1451         tape->insert_size += blocks * tape->blk_size;
1452         if (tape->insert_size > 1024 * 1024)
1453                 tape->measure_insert_time = 1;
1454         if (tape->measure_insert_time) {
1455                 tape->measure_insert_time = 0;
1456                 tape->insert_time = jiffies;
1457                 tape->insert_size = 0;
1458         }
1459         if (time_after(jiffies, tape->insert_time))
1460                 tape->insert_speed = tape->insert_size / 1024 * HZ /
1461                                         (jiffies - tape->insert_time);
1462         if (time_after_eq(jiffies, tape->avg_time + HZ)) {
1463                 tape->avg_speed = tape->avg_size * HZ /
1464                                 (jiffies - tape->avg_time) / 1024;
1465                 tape->avg_size = 0;
1466                 tape->avg_time = jiffies;
1467         }
1468         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1469
1470         tape->first_frame += blocks;
1471         rq->current_nr_sectors -= blocks;
1472
1473         if (!tape->pc->error)
1474                 idetape_end_request(drive, 1, 0);
1475         else
1476                 idetape_end_request(drive, tape->pc->error, 0);
1477         return ide_stopped;
1478 }
1479
1480 static void idetape_create_read_cmd(idetape_tape_t *tape,
1481                 struct ide_atapi_pc *pc,
1482                 unsigned int length, struct idetape_bh *bh)
1483 {
1484         idetape_init_pc(pc);
1485         pc->c[0] = READ_6;
1486         put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
1487         pc->c[1] = 1;
1488         pc->idetape_callback = &idetape_rw_callback;
1489         pc->bh = bh;
1490         atomic_set(&bh->b_count, 0);
1491         pc->buf = NULL;
1492         pc->buf_size = length * tape->blk_size;
1493         pc->req_xfer = pc->buf_size;
1494         if (pc->req_xfer == tape->stage_size)
1495                 pc->flags |= PC_FLAG_DMA_RECOMMENDED;
1496 }
1497
1498 static void idetape_create_write_cmd(idetape_tape_t *tape,
1499                 struct ide_atapi_pc *pc,
1500                 unsigned int length, struct idetape_bh *bh)
1501 {
1502         idetape_init_pc(pc);
1503         pc->c[0] = WRITE_6;
1504         put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
1505         pc->c[1] = 1;
1506         pc->idetape_callback = &idetape_rw_callback;
1507         pc->flags |= PC_FLAG_WRITING;
1508         pc->bh = bh;
1509         pc->b_data = bh->b_data;
1510         pc->b_count = atomic_read(&bh->b_count);
1511         pc->buf = NULL;
1512         pc->buf_size = length * tape->blk_size;
1513         pc->req_xfer = pc->buf_size;
1514         if (pc->req_xfer == tape->stage_size)
1515                 pc->flags |= PC_FLAG_DMA_RECOMMENDED;
1516 }
1517
1518 static ide_startstop_t idetape_do_request(ide_drive_t *drive,
1519                                           struct request *rq, sector_t block)
1520 {
1521         idetape_tape_t *tape = drive->driver_data;
1522         struct ide_atapi_pc *pc = NULL;
1523         struct request *postponed_rq = tape->postponed_rq;
1524         u8 stat;
1525
1526         debug_log(DBG_SENSE, "sector: %ld, nr_sectors: %ld,"
1527                         " current_nr_sectors: %d\n",
1528                         rq->sector, rq->nr_sectors, rq->current_nr_sectors);
1529
1530         if (!blk_special_request(rq)) {
1531                 /* We do not support buffer cache originated requests. */
1532                 printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
1533                         "request queue (%d)\n", drive->name, rq->cmd_type);
1534                 ide_end_request(drive, 0, 0);
1535                 return ide_stopped;
1536         }
1537
1538         /* Retry a failed packet command */
1539         if (tape->failed_pc && tape->pc->c[0] == REQUEST_SENSE)
1540                 return idetape_issue_pc(drive, tape->failed_pc);
1541
1542         if (postponed_rq != NULL)
1543                 if (rq != postponed_rq) {
1544                         printk(KERN_ERR "ide-tape: ide-tape.c bug - "
1545                                         "Two DSC requests were queued\n");
1546                         idetape_end_request(drive, 0, 0);
1547                         return ide_stopped;
1548                 }
1549
1550         tape->postponed_rq = NULL;
1551
1552         /*
1553          * If the tape is still busy, postpone our request and service
1554          * the other device meanwhile.
1555          */
1556         stat = ide_read_status(drive);
1557
1558         if (!drive->dsc_overlap && !(rq->cmd[0] & REQ_IDETAPE_PC2))
1559                 set_bit(IDETAPE_FLAG_IGNORE_DSC, &tape->flags);
1560
1561         if (drive->post_reset == 1) {
1562                 set_bit(IDETAPE_FLAG_IGNORE_DSC, &tape->flags);
1563                 drive->post_reset = 0;
1564         }
1565
1566         if (time_after(jiffies, tape->insert_time))
1567                 tape->insert_speed = tape->insert_size / 1024 * HZ /
1568                                         (jiffies - tape->insert_time);
1569         idetape_calculate_speeds(drive);
1570         if (!test_and_clear_bit(IDETAPE_FLAG_IGNORE_DSC, &tape->flags) &&
1571             (stat & SEEK_STAT) == 0) {
1572                 if (postponed_rq == NULL) {
1573                         tape->dsc_polling_start = jiffies;
1574                         tape->dsc_poll_freq = tape->best_dsc_rw_freq;
1575                         tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
1576                 } else if (time_after(jiffies, tape->dsc_timeout)) {
1577                         printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
1578                                 tape->name);
1579                         if (rq->cmd[0] & REQ_IDETAPE_PC2) {
1580                                 idetape_media_access_finished(drive);
1581                                 return ide_stopped;
1582                         } else {
1583                                 return ide_do_reset(drive);
1584                         }
1585                 } else if (time_after(jiffies,
1586                                         tape->dsc_polling_start +
1587                                         IDETAPE_DSC_MA_THRESHOLD))
1588                         tape->dsc_poll_freq = IDETAPE_DSC_MA_SLOW;
1589                 idetape_postpone_request(drive);
1590                 return ide_stopped;
1591         }
1592         if (rq->cmd[0] & REQ_IDETAPE_READ) {
1593                 tape->buffer_head++;
1594                 tape->postpone_cnt = 0;
1595                 pc = idetape_next_pc_storage(drive);
1596                 idetape_create_read_cmd(tape, pc, rq->current_nr_sectors,
1597                                         (struct idetape_bh *)rq->special);
1598                 goto out;
1599         }
1600         if (rq->cmd[0] & REQ_IDETAPE_WRITE) {
1601                 tape->buffer_head++;
1602                 tape->postpone_cnt = 0;
1603                 pc = idetape_next_pc_storage(drive);
1604                 idetape_create_write_cmd(tape, pc, rq->current_nr_sectors,
1605                                          (struct idetape_bh *)rq->special);
1606                 goto out;
1607         }
1608         if (rq->cmd[0] & REQ_IDETAPE_PC1) {
1609                 pc = (struct ide_atapi_pc *) rq->buffer;
1610                 rq->cmd[0] &= ~(REQ_IDETAPE_PC1);
1611                 rq->cmd[0] |= REQ_IDETAPE_PC2;
1612                 goto out;
1613         }
1614         if (rq->cmd[0] & REQ_IDETAPE_PC2) {
1615                 idetape_media_access_finished(drive);
1616                 return ide_stopped;
1617         }
1618         BUG();
1619 out:
1620         return idetape_issue_pc(drive, pc);
1621 }
1622
1623 /* Pipeline related functions */
1624 static inline int idetape_pipeline_active(idetape_tape_t *tape)
1625 {
1626         int rc1, rc2;
1627
1628         rc1 = test_bit(IDETAPE_FLAG_PIPELINE_ACTIVE, &tape->flags);
1629         rc2 = (tape->active_data_rq != NULL);
1630         return rc1;
1631 }
1632
1633 /*
1634  * The function below uses __get_free_page to allocate a pipeline stage, along
1635  * with all the necessary small buffers which together make a buffer of size
1636  * tape->stage_size (or a bit more). We attempt to combine sequential pages as
1637  * much as possible.
1638  *
1639  * It returns a pointer to the new allocated stage, or NULL if we can't (or
1640  * don't want to) allocate a stage.
1641  *
1642  * Pipeline stages are optional and are used to increase performance. If we
1643  * can't allocate them, we'll manage without them.
1644  */
1645 static idetape_stage_t *__idetape_kmalloc_stage(idetape_tape_t *tape, int full,
1646                                                 int clear)
1647 {
1648         idetape_stage_t *stage;
1649         struct idetape_bh *prev_bh, *bh;
1650         int pages = tape->pages_per_stage;
1651         char *b_data = NULL;
1652
1653         stage = kmalloc(sizeof(idetape_stage_t), GFP_KERNEL);
1654         if (!stage)
1655                 return NULL;
1656         stage->next = NULL;
1657
1658         stage->bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
1659         bh = stage->bh;
1660         if (bh == NULL)
1661                 goto abort;
1662         bh->b_reqnext = NULL;
1663         bh->b_data = (char *) __get_free_page(GFP_KERNEL);
1664         if (!bh->b_data)
1665                 goto abort;
1666         if (clear)
1667                 memset(bh->b_data, 0, PAGE_SIZE);
1668         bh->b_size = PAGE_SIZE;
1669         atomic_set(&bh->b_count, full ? bh->b_size : 0);
1670
1671         while (--pages) {
1672                 b_data = (char *) __get_free_page(GFP_KERNEL);
1673                 if (!b_data)
1674                         goto abort;
1675                 if (clear)
1676                         memset(b_data, 0, PAGE_SIZE);
1677                 if (bh->b_data == b_data + PAGE_SIZE) {
1678                         bh->b_size += PAGE_SIZE;
1679                         bh->b_data -= PAGE_SIZE;
1680                         if (full)
1681                                 atomic_add(PAGE_SIZE, &bh->b_count);
1682                         continue;
1683                 }
1684                 if (b_data == bh->b_data + bh->b_size) {
1685                         bh->b_size += PAGE_SIZE;
1686                         if (full)
1687                                 atomic_add(PAGE_SIZE, &bh->b_count);
1688                         continue;
1689                 }
1690                 prev_bh = bh;
1691                 bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
1692                 if (!bh) {
1693                         free_page((unsigned long) b_data);
1694                         goto abort;
1695                 }
1696                 bh->b_reqnext = NULL;
1697                 bh->b_data = b_data;
1698                 bh->b_size = PAGE_SIZE;
1699                 atomic_set(&bh->b_count, full ? bh->b_size : 0);
1700                 prev_bh->b_reqnext = bh;
1701         }
1702         bh->b_size -= tape->excess_bh_size;
1703         if (full)
1704                 atomic_sub(tape->excess_bh_size, &bh->b_count);
1705         return stage;
1706 abort:
1707         __idetape_kfree_stage(stage);
1708         return NULL;
1709 }
1710
1711 static idetape_stage_t *idetape_kmalloc_stage(idetape_tape_t *tape)
1712 {
1713         idetape_stage_t *cache_stage = tape->cache_stage;
1714
1715         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1716
1717         if (tape->nr_stages >= tape->max_stages)
1718                 return NULL;
1719         if (cache_stage != NULL) {
1720                 tape->cache_stage = NULL;
1721                 return cache_stage;
1722         }
1723         return __idetape_kmalloc_stage(tape, 0, 0);
1724 }
1725
1726 static int idetape_copy_stage_from_user(idetape_tape_t *tape,
1727                 idetape_stage_t *stage, const char __user *buf, int n)
1728 {
1729         struct idetape_bh *bh = tape->bh;
1730         int count;
1731         int ret = 0;
1732
1733         while (n) {
1734                 if (bh == NULL) {
1735                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
1736                                         __func__);
1737                         return 1;
1738                 }
1739                 count = min((unsigned int)
1740                                 (bh->b_size - atomic_read(&bh->b_count)),
1741                                 (unsigned int)n);
1742                 if (copy_from_user(bh->b_data + atomic_read(&bh->b_count), buf,
1743                                 count))
1744                         ret = 1;
1745                 n -= count;
1746                 atomic_add(count, &bh->b_count);
1747                 buf += count;
1748                 if (atomic_read(&bh->b_count) == bh->b_size) {
1749                         bh = bh->b_reqnext;
1750                         if (bh)
1751                                 atomic_set(&bh->b_count, 0);
1752                 }
1753         }
1754         tape->bh = bh;
1755         return ret;
1756 }
1757
1758 static int idetape_copy_stage_to_user(idetape_tape_t *tape, char __user *buf,
1759                 idetape_stage_t *stage, int n)
1760 {
1761         struct idetape_bh *bh = tape->bh;
1762         int count;
1763         int ret = 0;
1764
1765         while (n) {
1766                 if (bh == NULL) {
1767                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
1768                                         __func__);
1769                         return 1;
1770                 }
1771                 count = min(tape->b_count, n);
1772                 if  (copy_to_user(buf, tape->b_data, count))
1773                         ret = 1;
1774                 n -= count;
1775                 tape->b_data += count;
1776                 tape->b_count -= count;
1777                 buf += count;
1778                 if (!tape->b_count) {
1779                         bh = bh->b_reqnext;
1780                         tape->bh = bh;
1781                         if (bh) {
1782                                 tape->b_data = bh->b_data;
1783                                 tape->b_count = atomic_read(&bh->b_count);
1784                         }
1785                 }
1786         }
1787         return ret;
1788 }
1789
1790 static void idetape_init_merge_stage(idetape_tape_t *tape)
1791 {
1792         struct idetape_bh *bh = tape->merge_stage->bh;
1793
1794         tape->bh = bh;
1795         if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
1796                 atomic_set(&bh->b_count, 0);
1797         else {
1798                 tape->b_data = bh->b_data;
1799                 tape->b_count = atomic_read(&bh->b_count);
1800         }
1801 }
1802
1803 static void idetape_switch_buffers(idetape_tape_t *tape, idetape_stage_t *stage)
1804 {
1805         struct idetape_bh *tmp;
1806
1807         tmp = stage->bh;
1808         stage->bh = tape->merge_stage->bh;
1809         tape->merge_stage->bh = tmp;
1810         idetape_init_merge_stage(tape);
1811 }
1812
1813 /* Add a new stage at the end of the pipeline. */
1814 static void idetape_add_stage_tail(ide_drive_t *drive, idetape_stage_t *stage)
1815 {
1816         idetape_tape_t *tape = drive->driver_data;
1817         unsigned long flags;
1818
1819         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1820
1821         spin_lock_irqsave(&tape->lock, flags);
1822         stage->next = NULL;
1823         if (tape->last_stage != NULL)
1824                 tape->last_stage->next = stage;
1825         else
1826                 tape->first_stage = stage;
1827                 tape->next_stage  = stage;
1828         tape->last_stage = stage;
1829         if (tape->next_stage == NULL)
1830                 tape->next_stage = tape->last_stage;
1831         tape->nr_stages++;
1832         tape->nr_pending_stages++;
1833         spin_unlock_irqrestore(&tape->lock, flags);
1834 }
1835
1836 /* Install a completion in a pending request and sleep until it is serviced. The
1837  * caller should ensure that the request will not be serviced before we install
1838  * the completion (usually by disabling interrupts).
1839  */
1840 static void idetape_wait_for_request(ide_drive_t *drive, struct request *rq)
1841 {
1842         DECLARE_COMPLETION_ONSTACK(wait);
1843         idetape_tape_t *tape = drive->driver_data;
1844
1845         if (rq == NULL || !blk_special_request(rq)) {
1846                 printk(KERN_ERR "ide-tape: bug: Trying to sleep on non-valid"
1847                                  " request\n");
1848                 return;
1849         }
1850         rq->end_io_data = &wait;
1851         rq->end_io = blk_end_sync_rq;
1852         spin_unlock_irq(&tape->lock);
1853         wait_for_completion(&wait);
1854         /* The stage and its struct request have been deallocated */
1855         spin_lock_irq(&tape->lock);
1856 }
1857
1858 static ide_startstop_t idetape_read_position_callback(ide_drive_t *drive)
1859 {
1860         idetape_tape_t *tape = drive->driver_data;
1861         u8 *readpos = tape->pc->buf;
1862
1863         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1864
1865         if (!tape->pc->error) {
1866                 debug_log(DBG_SENSE, "BOP - %s\n",
1867                                 (readpos[0] & 0x80) ? "Yes" : "No");
1868                 debug_log(DBG_SENSE, "EOP - %s\n",
1869                                 (readpos[0] & 0x40) ? "Yes" : "No");
1870
1871                 if (readpos[0] & 0x4) {
1872                         printk(KERN_INFO "ide-tape: Block location is unknown"
1873                                          "to the tape\n");
1874                         clear_bit(IDETAPE_FLAG_ADDRESS_VALID, &tape->flags);
1875                         idetape_end_request(drive, 0, 0);
1876                 } else {
1877                         debug_log(DBG_SENSE, "Block Location - %u\n",
1878                                         be32_to_cpu(*(u32 *)&readpos[4]));
1879
1880                         tape->partition = readpos[1];
1881                         tape->first_frame =
1882                                 be32_to_cpu(*(u32 *)&readpos[4]);
1883                         set_bit(IDETAPE_FLAG_ADDRESS_VALID, &tape->flags);
1884                         idetape_end_request(drive, 1, 0);
1885                 }
1886         } else {
1887                 idetape_end_request(drive, 0, 0);
1888         }
1889         return ide_stopped;
1890 }
1891
1892 /*
1893  * Write a filemark if write_filemark=1. Flush the device buffers without
1894  * writing a filemark otherwise.
1895  */
1896 static void idetape_create_write_filemark_cmd(ide_drive_t *drive,
1897                 struct ide_atapi_pc *pc, int write_filemark)
1898 {
1899         idetape_init_pc(pc);
1900         pc->c[0] = WRITE_FILEMARKS;
1901         pc->c[4] = write_filemark;
1902         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1903         pc->idetape_callback = &idetape_pc_callback;
1904 }
1905
1906 static void idetape_create_test_unit_ready_cmd(struct ide_atapi_pc *pc)
1907 {
1908         idetape_init_pc(pc);
1909         pc->c[0] = TEST_UNIT_READY;
1910         pc->idetape_callback = &idetape_pc_callback;
1911 }
1912
1913 /*
1914  * We add a special packet command request to the tail of the request queue, and
1915  * wait for it to be serviced. This is not to be called from within the request
1916  * handling part of the driver! We allocate here data on the stack and it is
1917  * valid until the request is finished. This is not the case for the bottom part
1918  * of the driver, where we are always leaving the functions to wait for an
1919  * interrupt or a timer event.
1920  *
1921  * From the bottom part of the driver, we should allocate safe memory using
1922  * idetape_next_pc_storage() and ide_tape_next_rq_storage(), and add the request
1923  * to the request list without waiting for it to be serviced! In that case, we
1924  * usually use idetape_queue_pc_head().
1925  */
1926 static int __idetape_queue_pc_tail(ide_drive_t *drive, struct ide_atapi_pc *pc)
1927 {
1928         struct ide_tape_obj *tape = drive->driver_data;
1929         struct request rq;
1930
1931         idetape_init_rq(&rq, REQ_IDETAPE_PC1);
1932         rq.buffer = (char *) pc;
1933         rq.rq_disk = tape->disk;
1934         return ide_do_drive_cmd(drive, &rq, ide_wait);
1935 }
1936
1937 static void idetape_create_load_unload_cmd(ide_drive_t *drive,
1938                 struct ide_atapi_pc *pc, int cmd)
1939 {
1940         idetape_init_pc(pc);
1941         pc->c[0] = START_STOP;
1942         pc->c[4] = cmd;
1943         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1944         pc->idetape_callback = &idetape_pc_callback;
1945 }
1946
1947 static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
1948 {
1949         idetape_tape_t *tape = drive->driver_data;
1950         struct ide_atapi_pc pc;
1951         int load_attempted = 0;
1952
1953         /* Wait for the tape to become ready */
1954         set_bit(IDETAPE_FLAG_MEDIUM_PRESENT, &tape->flags);
1955         timeout += jiffies;
1956         while (time_before(jiffies, timeout)) {
1957                 idetape_create_test_unit_ready_cmd(&pc);
1958                 if (!__idetape_queue_pc_tail(drive, &pc))
1959                         return 0;
1960                 if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
1961                     || (tape->asc == 0x3A)) {
1962                         /* no media */
1963                         if (load_attempted)
1964                                 return -ENOMEDIUM;
1965                         idetape_create_load_unload_cmd(drive, &pc,
1966                                                         IDETAPE_LU_LOAD_MASK);
1967                         __idetape_queue_pc_tail(drive, &pc);
1968                         load_attempted = 1;
1969                 /* not about to be ready */
1970                 } else if (!(tape->sense_key == 2 && tape->asc == 4 &&
1971                              (tape->ascq == 1 || tape->ascq == 8)))
1972                         return -EIO;
1973                 msleep(100);
1974         }
1975         return -EIO;
1976 }
1977
1978 static int idetape_queue_pc_tail(ide_drive_t *drive, struct ide_atapi_pc *pc)
1979 {
1980         return __idetape_queue_pc_tail(drive, pc);
1981 }
1982
1983 static int idetape_flush_tape_buffers(ide_drive_t *drive)
1984 {
1985         struct ide_atapi_pc pc;
1986         int rc;
1987
1988         idetape_create_write_filemark_cmd(drive, &pc, 0);
1989         rc = idetape_queue_pc_tail(drive, &pc);
1990         if (rc)
1991                 return rc;
1992         idetape_wait_ready(drive, 60 * 5 * HZ);
1993         return 0;
1994 }
1995
1996 static void idetape_create_read_position_cmd(struct ide_atapi_pc *pc)
1997 {
1998         idetape_init_pc(pc);
1999         pc->c[0] = READ_POSITION;
2000         pc->req_xfer = 20;
2001         pc->idetape_callback = &idetape_read_position_callback;
2002 }
2003
2004 static int idetape_read_position(ide_drive_t *drive)
2005 {
2006         idetape_tape_t *tape = drive->driver_data;
2007         struct ide_atapi_pc pc;
2008         int position;
2009
2010         debug_log(DBG_PROCS, "Enter %s\n", __func__);
2011
2012         idetape_create_read_position_cmd(&pc);
2013         if (idetape_queue_pc_tail(drive, &pc))
2014                 return -1;
2015         position = tape->first_frame;
2016         return position;
2017 }
2018
2019 static void idetape_create_locate_cmd(ide_drive_t *drive,
2020                 struct ide_atapi_pc *pc,
2021                 unsigned int block, u8 partition, int skip)
2022 {
2023         idetape_init_pc(pc);
2024         pc->c[0] = POSITION_TO_ELEMENT;
2025         pc->c[1] = 2;
2026         put_unaligned(cpu_to_be32(block), (unsigned int *) &pc->c[3]);
2027         pc->c[8] = partition;
2028         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
2029         pc->idetape_callback = &idetape_pc_callback;
2030 }
2031
2032 static int idetape_create_prevent_cmd(ide_drive_t *drive,
2033                 struct ide_atapi_pc *pc, int prevent)
2034 {
2035         idetape_tape_t *tape = drive->driver_data;
2036
2037         /* device supports locking according to capabilities page */
2038         if (!(tape->caps[6] & 0x01))
2039                 return 0;
2040
2041         idetape_init_pc(pc);
2042         pc->c[0] = ALLOW_MEDIUM_REMOVAL;
2043         pc->c[4] = prevent;
2044         pc->idetape_callback = &idetape_pc_callback;
2045         return 1;
2046 }
2047
2048 static int __idetape_discard_read_pipeline(ide_drive_t *drive)
2049 {
2050         idetape_tape_t *tape = drive->driver_data;
2051         unsigned long flags;
2052         int cnt;
2053
2054         if (tape->chrdev_dir != IDETAPE_DIR_READ)
2055                 return 0;
2056
2057         /* Remove merge stage. */
2058         cnt = tape->merge_stage_size / tape->blk_size;
2059         if (test_and_clear_bit(IDETAPE_FLAG_FILEMARK, &tape->flags))
2060                 ++cnt;          /* Filemarks count as 1 sector */
2061         tape->merge_stage_size = 0;
2062         if (tape->merge_stage != NULL) {
2063                 __idetape_kfree_stage(tape->merge_stage);
2064                 tape->merge_stage = NULL;
2065         }
2066
2067         /* Clear pipeline flags. */
2068         clear_bit(IDETAPE_FLAG_PIPELINE_ERR, &tape->flags);
2069         tape->chrdev_dir = IDETAPE_DIR_NONE;
2070
2071         /* Remove pipeline stages. */
2072         if (tape->first_stage == NULL)
2073                 return 0;
2074
2075         spin_lock_irqsave(&tape->lock, flags);
2076         tape->next_stage = NULL;
2077         if (idetape_pipeline_active(tape))
2078                 idetape_wait_for_request(drive, tape->active_data_rq);
2079         spin_unlock_irqrestore(&tape->lock, flags);
2080
2081         while (tape->first_stage != NULL) {
2082                 struct request *rq_ptr = &tape->first_stage->rq;
2083
2084                 cnt += rq_ptr->nr_sectors - rq_ptr->current_nr_sectors;
2085                 if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
2086                         ++cnt;
2087                 idetape_remove_stage_head(drive);
2088         }
2089         tape->nr_pending_stages = 0;
2090         tape->max_stages = tape->min_pipeline;
2091         return cnt;
2092 }
2093
2094 /*
2095  * Position the tape to the requested block using the LOCATE packet command.
2096  * A READ POSITION command is then issued to check where we are positioned. Like
2097  * all higher level operations, we queue the commands at the tail of the request
2098  * queue and wait for their completion.
2099  */
2100 static int idetape_position_tape(ide_drive_t *drive, unsigned int block,
2101                 u8 partition, int skip)
2102 {
2103         idetape_tape_t *tape = drive->driver_data;
2104         int retval;
2105         struct ide_atapi_pc pc;
2106
2107         if (tape->chrdev_dir == IDETAPE_DIR_READ)
2108                 __idetape_discard_read_pipeline(drive);
2109         idetape_wait_ready(drive, 60 * 5 * HZ);
2110         idetape_create_locate_cmd(drive, &pc, block, partition, skip);
2111         retval = idetape_queue_pc_tail(drive, &pc);
2112         if (retval)
2113                 return (retval);
2114
2115         idetape_create_read_position_cmd(&pc);
2116         return (idetape_queue_pc_tail(drive, &pc));
2117 }
2118
2119 static void idetape_discard_read_pipeline(ide_drive_t *drive,
2120                                           int restore_position)
2121 {
2122         idetape_tape_t *tape = drive->driver_data;
2123         int cnt;
2124         int seek, position;
2125
2126         cnt = __idetape_discard_read_pipeline(drive);
2127         if (restore_position) {
2128                 position = idetape_read_position(drive);
2129                 seek = position > cnt ? position - cnt : 0;
2130                 if (idetape_position_tape(drive, seek, 0, 0)) {
2131                         printk(KERN_INFO "ide-tape: %s: position_tape failed in"
2132                                          " discard_pipeline()\n", tape->name);
2133                         return;
2134                 }
2135         }
2136 }
2137
2138 /*
2139  * Generate a read/write request for the block device interface and wait for it
2140  * to be serviced.
2141  */
2142 static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int blocks,
2143                                  struct idetape_bh *bh)
2144 {
2145         idetape_tape_t *tape = drive->driver_data;
2146         struct request rq;
2147
2148         debug_log(DBG_SENSE, "%s: cmd=%d\n", __func__, cmd);
2149
2150         if (idetape_pipeline_active(tape)) {
2151                 printk(KERN_ERR "ide-tape: bug: the pipeline is active in %s\n",
2152                                 __func__);
2153                 return (0);
2154         }
2155
2156         idetape_init_rq(&rq, cmd);
2157         rq.rq_disk = tape->disk;
2158         rq.special = (void *)bh;
2159         rq.sector = tape->first_frame;
2160         rq.nr_sectors           = blocks;
2161         rq.current_nr_sectors   = blocks;
2162         (void) ide_do_drive_cmd(drive, &rq, ide_wait);
2163
2164         if ((cmd & (REQ_IDETAPE_READ | REQ_IDETAPE_WRITE)) == 0)
2165                 return 0;
2166
2167         if (tape->merge_stage)
2168                 idetape_init_merge_stage(tape);
2169         if (rq.errors == IDETAPE_ERROR_GENERAL)
2170                 return -EIO;
2171         return (tape->blk_size * (blocks-rq.current_nr_sectors));
2172 }
2173
2174 /* start servicing the pipeline stages, starting from tape->next_stage. */
2175 static void idetape_plug_pipeline(ide_drive_t *drive)
2176 {
2177         idetape_tape_t *tape = drive->driver_data;
2178
2179         if (tape->next_stage == NULL)
2180                 return;
2181         if (!idetape_pipeline_active(tape)) {
2182                 set_bit(IDETAPE_FLAG_PIPELINE_ACTIVE, &tape->flags);
2183                 idetape_activate_next_stage(drive);
2184                 (void) ide_do_drive_cmd(drive, tape->active_data_rq, ide_end);
2185         }
2186 }
2187
2188 static void idetape_create_inquiry_cmd(struct ide_atapi_pc *pc)
2189 {
2190         idetape_init_pc(pc);
2191         pc->c[0] = INQUIRY;
2192         pc->c[4] = 254;
2193         pc->req_xfer = 254;
2194         pc->idetape_callback = &idetape_pc_callback;
2195 }
2196
2197 static void idetape_create_rewind_cmd(ide_drive_t *drive,
2198                 struct ide_atapi_pc *pc)
2199 {
2200         idetape_init_pc(pc);
2201         pc->c[0] = REZERO_UNIT;
2202         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
2203         pc->idetape_callback = &idetape_pc_callback;
2204 }
2205
2206 static void idetape_create_erase_cmd(struct ide_atapi_pc *pc)
2207 {
2208         idetape_init_pc(pc);
2209         pc->c[0] = ERASE;
2210         pc->c[1] = 1;
2211         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
2212         pc->idetape_callback = &idetape_pc_callback;
2213 }
2214
2215 static void idetape_create_space_cmd(struct ide_atapi_pc *pc, int count, u8 cmd)
2216 {
2217         idetape_init_pc(pc);
2218         pc->c[0] = SPACE;
2219         put_unaligned(cpu_to_be32(count), (unsigned int *) &pc->c[1]);
2220         pc->c[1] = cmd;
2221         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
2222         pc->idetape_callback = &idetape_pc_callback;
2223 }
2224
2225 static void idetape_wait_first_stage(ide_drive_t *drive)
2226 {
2227         idetape_tape_t *tape = drive->driver_data;
2228         unsigned long flags;
2229
2230         if (tape->first_stage == NULL)
2231                 return;
2232         spin_lock_irqsave(&tape->lock, flags);
2233         if (tape->active_stage == tape->first_stage)
2234                 idetape_wait_for_request(drive, tape->active_data_rq);
2235         spin_unlock_irqrestore(&tape->lock, flags);
2236 }
2237
2238 /*
2239  * Try to add a character device originated write request to our pipeline. In
2240  * case we don't succeed, we revert to non-pipelined operation mode for this
2241  * request. In order to accomplish that, we
2242  *
2243  * 1. Try to allocate a new pipeline stage.
2244  * 2. If we can't, wait for more and more requests to be serviced and try again
2245  * each time.
2246  * 3. If we still can't allocate a stage, fallback to non-pipelined operation
2247  * mode for this request.
2248  */
2249 static int idetape_add_chrdev_write_request(ide_drive_t *drive, int blocks)
2250 {
2251         idetape_tape_t *tape = drive->driver_data;
2252         idetape_stage_t *new_stage;
2253         unsigned long flags;
2254         struct request *rq;
2255
2256         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
2257
2258         /* Attempt to allocate a new stage. Beware possible race conditions. */
2259         while ((new_stage = idetape_kmalloc_stage(tape)) == NULL) {
2260                 spin_lock_irqsave(&tape->lock, flags);
2261                 if (idetape_pipeline_active(tape)) {
2262                         idetape_wait_for_request(drive, tape->active_data_rq);
2263                         spin_unlock_irqrestore(&tape->lock, flags);
2264                 } else {
2265                         spin_unlock_irqrestore(&tape->lock, flags);
2266                         idetape_plug_pipeline(drive);
2267                         if (idetape_pipeline_active(tape))
2268                                 continue;
2269                         /*
2270                          * The machine is short on memory. Fallback to non-
2271                          * pipelined operation mode for this request.
2272                          */
2273                         return idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE,
2274                                                 blocks, tape->merge_stage->bh);
2275                 }
2276         }
2277         rq = &new_stage->rq;
2278         idetape_init_rq(rq, REQ_IDETAPE_WRITE);
2279         /* Doesn't actually matter - We always assume sequential access */
2280         rq->sector = tape->first_frame;
2281         rq->current_nr_sectors = blocks;
2282         rq->nr_sectors = blocks;
2283
2284         idetape_switch_buffers(tape, new_stage);
2285         idetape_add_stage_tail(drive, new_stage);
2286         tape->pipeline_head++;
2287         idetape_calculate_speeds(drive);
2288
2289         /*
2290          * Estimate whether the tape has stopped writing by checking if our
2291          * write pipeline is currently empty. If we are not writing anymore,
2292          * wait for the pipeline to be almost completely full (90%) before
2293          * starting to service requests, so that we will be able to keep up with
2294          * the higher speeds of the tape.
2295          */
2296         if (!idetape_pipeline_active(tape)) {
2297                 if (tape->nr_stages >= tape->max_stages * 9 / 10 ||
2298                         tape->nr_stages >= tape->max_stages -
2299                         tape->uncontrolled_pipeline_head_speed * 3 * 1024 /
2300                         tape->blk_size) {
2301                         tape->measure_insert_time = 1;
2302                         tape->insert_time = jiffies;
2303                         tape->insert_size = 0;
2304                         tape->insert_speed = 0;
2305                         idetape_plug_pipeline(drive);
2306                 }
2307         }
2308         if (test_and_clear_bit(IDETAPE_FLAG_PIPELINE_ERR, &tape->flags))
2309                 /* Return a deferred error */
2310                 return -EIO;
2311         return blocks;
2312 }
2313
2314 /*
2315  * Wait until all pending pipeline requests are serviced. Typically called on
2316  * device close.
2317  */
2318 static void idetape_wait_for_pipeline(ide_drive_t *drive)
2319 {
2320         idetape_tape_t *tape = drive->driver_data;
2321         unsigned long flags;
2322
2323         while (tape->next_stage || idetape_pipeline_active(tape)) {
2324                 idetape_plug_pipeline(drive);
2325                 spin_lock_irqsave(&tape->lock, flags);
2326                 if (idetape_pipeline_active(tape))
2327                         idetape_wait_for_request(drive, tape->active_data_rq);
2328                 spin_unlock_irqrestore(&tape->lock, flags);
2329         }
2330 }
2331
2332 static void idetape_empty_write_pipeline(ide_drive_t *drive)
2333 {
2334         idetape_tape_t *tape = drive->driver_data;
2335         int blocks, min;
2336         struct idetape_bh *bh;
2337
2338         if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
2339                 printk(KERN_ERR "ide-tape: bug: Trying to empty write pipeline,"
2340                                 " but we are not writing.\n");
2341                 return;
2342         }
2343         if (tape->merge_stage_size > tape->stage_size) {
2344                 printk(KERN_ERR "ide-tape: bug: merge_buffer too big\n");
2345                 tape->merge_stage_size = tape->stage_size;
2346         }
2347         if (tape->merge_stage_size) {
2348                 blocks = tape->merge_stage_size / tape->blk_size;
2349                 if (tape->merge_stage_size % tape->blk_size) {
2350                         unsigned int i;
2351
2352                         blocks++;
2353                         i = tape->blk_size - tape->merge_stage_size %
2354                                 tape->blk_size;
2355                         bh = tape->bh->b_reqnext;
2356                         while (bh) {
2357                                 atomic_set(&bh->b_count, 0);
2358                                 bh = bh->b_reqnext;
2359                         }
2360                         bh = tape->bh;
2361                         while (i) {
2362                                 if (bh == NULL) {
2363                                         printk(KERN_INFO "ide-tape: bug,"
2364                                                          " bh NULL\n");
2365                                         break;
2366                                 }
2367                                 min = min(i, (unsigned int)(bh->b_size -
2368                                                 atomic_read(&bh->b_count)));
2369                                 memset(bh->b_data + atomic_read(&bh->b_count),
2370                                                 0, min);
2371                                 atomic_add(min, &bh->b_count);
2372                                 i -= min;
2373                                 bh = bh->b_reqnext;
2374                         }
2375                 }
2376                 (void) idetape_add_chrdev_write_request(drive, blocks);
2377                 tape->merge_stage_size = 0;
2378         }
2379         idetape_wait_for_pipeline(drive);
2380         if (tape->merge_stage != NULL) {
2381                 __idetape_kfree_stage(tape->merge_stage);
2382                 tape->merge_stage = NULL;
2383         }
2384         clear_bit(IDETAPE_FLAG_PIPELINE_ERR, &tape->flags);
2385         tape->chrdev_dir = IDETAPE_DIR_NONE;
2386
2387         /*
2388          * On the next backup, perform the feedback loop again. (I don't want to
2389          * keep sense information between backups, as some systems are
2390          * constantly on, and the system load can be totally different on the
2391          * next backup).
2392          */
2393         tape->max_stages = tape->min_pipeline;
2394         if (tape->first_stage != NULL ||
2395             tape->next_stage != NULL ||
2396             tape->last_stage != NULL ||
2397             tape->nr_stages != 0) {
2398                 printk(KERN_ERR "ide-tape: ide-tape pipeline bug, "
2399                         "first_stage %p, next_stage %p, "
2400                         "last_stage %p, nr_stages %d\n",
2401                         tape->first_stage, tape->next_stage,
2402                         tape->last_stage, tape->nr_stages);
2403         }
2404 }
2405
2406 static void idetape_restart_speed_control(ide_drive_t *drive)
2407 {
2408         idetape_tape_t *tape = drive->driver_data;
2409
2410         tape->restart_speed_control_req = 0;
2411         tape->pipeline_head = 0;
2412         tape->controlled_last_pipeline_head = 0;
2413         tape->controlled_previous_pipeline_head = 0;
2414         tape->uncontrolled_previous_pipeline_head = 0;
2415         tape->controlled_pipeline_head_speed = 5000;
2416         tape->pipeline_head_speed = 5000;
2417         tape->uncontrolled_pipeline_head_speed = 0;
2418         tape->controlled_pipeline_head_time =
2419                 tape->uncontrolled_pipeline_head_time = jiffies;
2420         tape->controlled_previous_head_time =
2421                 tape->uncontrolled_previous_head_time = jiffies;
2422 }
2423
2424 static int idetape_init_read(ide_drive_t *drive, int max_stages)
2425 {
2426         idetape_tape_t *tape = drive->driver_data;
2427         idetape_stage_t *new_stage;
2428         struct request rq;
2429         int bytes_read;
2430         u16 blocks = *(u16 *)&tape->caps[12];
2431
2432         /* Initialize read operation */
2433         if (tape->chrdev_dir != IDETAPE_DIR_READ) {
2434                 if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
2435                         idetape_empty_write_pipeline(drive);
2436                         idetape_flush_tape_buffers(drive);
2437                 }
2438                 if (tape->merge_stage || tape->merge_stage_size) {
2439                         printk(KERN_ERR "ide-tape: merge_stage_size should be"
2440                                          " 0 now\n");
2441                         tape->merge_stage_size = 0;
2442                 }
2443                 tape->merge_stage = __idetape_kmalloc_stage(tape, 0, 0);
2444                 if (!tape->merge_stage)
2445                         return -ENOMEM;
2446                 tape->chrdev_dir = IDETAPE_DIR_READ;
2447
2448                 /*
2449                  * Issue a read 0 command to ensure that DSC handshake is
2450                  * switched from completion mode to buffer available mode.
2451                  * No point in issuing this if DSC overlap isn't supported, some
2452                  * drives (Seagate STT3401A) will return an error.
2453                  */
2454                 if (drive->dsc_overlap) {
2455                         bytes_read = idetape_queue_rw_tail(drive,
2456                                                         REQ_IDETAPE_READ, 0,
2457                                                         tape->merge_stage->bh);
2458                         if (bytes_read < 0) {
2459                                 __idetape_kfree_stage(tape->merge_stage);
2460                                 tape->merge_stage = NULL;
2461                                 tape->chrdev_dir = IDETAPE_DIR_NONE;
2462                                 return bytes_read;
2463                         }
2464                 }
2465         }
2466         if (tape->restart_speed_control_req)
2467                 idetape_restart_speed_control(drive);
2468         idetape_init_rq(&rq, REQ_IDETAPE_READ);
2469         rq.sector = tape->first_frame;
2470         rq.nr_sectors = blocks;
2471         rq.current_nr_sectors = blocks;
2472         if (!test_bit(IDETAPE_FLAG_PIPELINE_ERR, &tape->flags) &&
2473             tape->nr_stages < max_stages) {
2474                 new_stage = idetape_kmalloc_stage(tape);
2475                 while (new_stage != NULL) {
2476                         new_stage->rq = rq;
2477                         idetape_add_stage_tail(drive, new_stage);
2478                         if (tape->nr_stages >= max_stages)
2479                                 break;
2480                         new_stage = idetape_kmalloc_stage(tape);
2481                 }
2482         }
2483         if (!idetape_pipeline_active(tape)) {
2484                 if (tape->nr_pending_stages >= 3 * max_stages / 4) {
2485                         tape->measure_insert_time = 1;
2486                         tape->insert_time = jiffies;
2487                         tape->insert_size = 0;
2488                         tape->insert_speed = 0;
2489                         idetape_plug_pipeline(drive);
2490                 }
2491         }
2492         return 0;
2493 }
2494
2495 /*
2496  * Called from idetape_chrdev_read() to service a character device read request
2497  * and add read-ahead requests to our pipeline.
2498  */
2499 static int idetape_add_chrdev_read_request(ide_drive_t *drive, int blocks)
2500 {
2501         idetape_tape_t *tape = drive->driver_data;
2502         unsigned long flags;
2503         struct request *rq_ptr;
2504         int bytes_read;
2505
2506         debug_log(DBG_PROCS, "Enter %s, %d blocks\n", __func__, blocks);
2507
2508         /* If we are at a filemark, return a read length of 0 */
2509         if (test_bit(IDETAPE_FLAG_FILEMARK, &tape->flags))
2510                 return 0;
2511
2512         /* Wait for the next block to reach the head of the pipeline. */
2513         idetape_init_read(drive, tape->max_stages);
2514         if (tape->first_stage == NULL) {
2515                 if (test_bit(IDETAPE_FLAG_PIPELINE_ERR, &tape->flags))
2516                         return 0;
2517                 return idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, blocks,
2518                                         tape->merge_stage->bh);
2519         }
2520         idetape_wait_first_stage(drive);
2521         rq_ptr = &tape->first_stage->rq;
2522         bytes_read = tape->blk_size * (rq_ptr->nr_sectors -
2523                                         rq_ptr->current_nr_sectors);
2524         rq_ptr->nr_sectors = 0;
2525         rq_ptr->current_nr_sectors = 0;
2526
2527         if (rq_ptr->errors == IDETAPE_ERROR_EOD)
2528                 return 0;
2529         else {
2530                 idetape_switch_buffers(tape, tape->first_stage);
2531                 if (rq_ptr->errors == IDETAPE_ERROR_FILEMARK)
2532                         set_bit(IDETAPE_FLAG_FILEMARK, &tape->flags);
2533                 spin_lock_irqsave(&tape->lock, flags);
2534                 idetape_remove_stage_head(drive);
2535                 spin_unlock_irqrestore(&tape->lock, flags);
2536                 tape->pipeline_head++;
2537                 idetape_calculate_speeds(drive);
2538         }
2539         if (bytes_read > blocks * tape->blk_size) {
2540                 printk(KERN_ERR "ide-tape: bug: trying to return more bytes"
2541                                 " than requested\n");
2542                 bytes_read = blocks * tape->blk_size;
2543         }
2544         return (bytes_read);
2545 }
2546
2547 static void idetape_pad_zeros(ide_drive_t *drive, int bcount)
2548 {
2549         idetape_tape_t *tape = drive->driver_data;
2550         struct idetape_bh *bh;
2551         int blocks;
2552
2553         while (bcount) {
2554                 unsigned int count;
2555
2556                 bh = tape->merge_stage->bh;
2557                 count = min(tape->stage_size, bcount);
2558                 bcount -= count;
2559                 blocks = count / tape->blk_size;
2560                 while (count) {
2561                         atomic_set(&bh->b_count,
2562                                    min(count, (unsigned int)bh->b_size));
2563                         memset(bh->b_data, 0, atomic_read(&bh->b_count));
2564                         count -= atomic_read(&bh->b_count);
2565                         bh = bh->b_reqnext;
2566                 }
2567                 idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks,
2568                                       tape->merge_stage->bh);
2569         }
2570 }
2571
2572 static int idetape_pipeline_size(ide_drive_t *drive)
2573 {
2574         idetape_tape_t *tape = drive->driver_data;
2575         idetape_stage_t *stage;
2576         struct request *rq;
2577         int size = 0;
2578
2579         idetape_wait_for_pipeline(drive);
2580         stage = tape->first_stage;
2581         while (stage != NULL) {
2582                 rq = &stage->rq;
2583                 size += tape->blk_size * (rq->nr_sectors -
2584                                 rq->current_nr_sectors);
2585                 if (rq->errors == IDETAPE_ERROR_FILEMARK)
2586                         size += tape->blk_size;
2587                 stage = stage->next;
2588         }
2589         size += tape->merge_stage_size;
2590         return size;
2591 }
2592
2593 /*
2594  * Rewinds the tape to the Beginning Of the current Partition (BOP). We
2595  * currently support only one partition.
2596  */
2597 static int idetape_rewind_tape(ide_drive_t *drive)
2598 {
2599         int retval;
2600         struct ide_atapi_pc pc;
2601         idetape_tape_t *tape;
2602         tape = drive->driver_data;
2603
2604         debug_log(DBG_SENSE, "Enter %s\n", __func__);
2605
2606         idetape_create_rewind_cmd(drive, &pc);
2607         retval = idetape_queue_pc_tail(drive, &pc);
2608         if (retval)
2609                 return retval;
2610
2611         idetape_create_read_position_cmd(&pc);
2612         retval = idetape_queue_pc_tail(drive, &pc);
2613         if (retval)
2614                 return retval;
2615         return 0;
2616 }
2617
2618 /* mtio.h compatible commands should be issued to the chrdev interface. */
2619 static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd,
2620                                 unsigned long arg)
2621 {
2622         idetape_tape_t *tape = drive->driver_data;
2623         void __user *argp = (void __user *)arg;
2624
2625         struct idetape_config {
2626                 int dsc_rw_frequency;
2627                 int dsc_media_access_frequency;
2628                 int nr_stages;
2629         } config;
2630
2631         debug_log(DBG_PROCS, "Enter %s\n", __func__);
2632
2633         switch (cmd) {
2634         case 0x0340:
2635                 if (copy_from_user(&config, argp, sizeof(config)))
2636                         return -EFAULT;
2637                 tape->best_dsc_rw_freq = config.dsc_rw_frequency;
2638                 tape->max_stages = config.nr_stages;
2639                 break;
2640         case 0x0350:
2641                 config.dsc_rw_frequency = (int) tape->best_dsc_rw_freq;
2642                 config.nr_stages = tape->max_stages;
2643                 if (copy_to_user(argp, &config, sizeof(config)))
2644                         return -EFAULT;
2645                 break;
2646         default:
2647                 return -EIO;
2648         }
2649         return 0;
2650 }
2651
2652 /*
2653  * The function below is now a bit more complicated than just passing the
2654  * command to the tape since we may have crossed some filemarks during our
2655  * pipelined read-ahead mode. As a minor side effect, the pipeline enables us to
2656  * support MTFSFM when the filemark is in our internal pipeline even if the tape
2657  * doesn't support spacing over filemarks in the reverse direction.
2658  */
2659 static int idetape_space_over_filemarks(ide_drive_t *drive, short mt_op,
2660                                         int mt_count)
2661 {
2662         idetape_tape_t *tape = drive->driver_data;
2663         struct ide_atapi_pc pc;
2664         unsigned long flags;
2665         int retval, count = 0;
2666         int sprev = !!(tape->caps[4] & 0x20);
2667
2668         if (mt_count == 0)
2669                 return 0;
2670         if (MTBSF == mt_op || MTBSFM == mt_op) {
2671                 if (!sprev)
2672                         return -EIO;
2673                 mt_count = -mt_count;
2674         }
2675
2676         if (tape->chrdev_dir == IDETAPE_DIR_READ) {
2677                 /* its a read-ahead buffer, scan it for crossed filemarks. */
2678                 tape->merge_stage_size = 0;
2679                 if (test_and_clear_bit(IDETAPE_FLAG_FILEMARK, &tape->flags))
2680                         ++count;
2681                 while (tape->first_stage != NULL) {
2682                         if (count == mt_count) {
2683                                 if (mt_op == MTFSFM)
2684                                         set_bit(IDETAPE_FLAG_FILEMARK,
2685                                                 &tape->flags);
2686                                 return 0;
2687                         }
2688                         spin_lock_irqsave(&tape->lock, flags);
2689                         if (tape->first_stage == tape->active_stage) {
2690                                 /*
2691                                  * We have reached the active stage in the read
2692                                  * pipeline. There is no point in allowing the
2693                                  * drive to continue reading any farther, so we
2694                                  * stop the pipeline.
2695                                  *
2696                                  * This section should be moved to a separate
2697                                  * subroutine because similar operations are
2698                                  * done in __idetape_discard_read_pipeline(),
2699                                  * for example.
2700                                  */
2701                                 tape->next_stage = NULL;
2702                                 spin_unlock_irqrestore(&tape->lock, flags);
2703                                 idetape_wait_first_stage(drive);
2704                                 tape->next_stage = tape->first_stage->next;
2705                         } else
2706                                 spin_unlock_irqrestore(&tape->lock, flags);
2707                         if (tape->first_stage->rq.errors ==
2708                                         IDETAPE_ERROR_FILEMARK)
2709                                 ++count;
2710                         idetape_remove_stage_head(drive);
2711                 }
2712                 idetape_discard_read_pipeline(drive, 0);
2713         }
2714
2715         /*
2716          * The filemark was not found in our internal pipeline; now we can issue
2717          * the space command.
2718          */
2719         switch (mt_op) {
2720         case MTFSF:
2721         case MTBSF:
2722                 idetape_create_space_cmd(&pc, mt_count - count,
2723                                          IDETAPE_SPACE_OVER_FILEMARK);
2724                 return idetape_queue_pc_tail(drive, &pc);
2725         case MTFSFM:
2726         case MTBSFM:
2727                 if (!sprev)
2728                         return -EIO;
2729                 retval = idetape_space_over_filemarks(drive, MTFSF,
2730                                                       mt_count - count);
2731                 if (retval)
2732                         return retval;
2733                 count = (MTBSFM == mt_op ? 1 : -1);
2734                 return idetape_space_over_filemarks(drive, MTFSF, count);
2735         default:
2736                 printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
2737                                 mt_op);
2738                 return -EIO;
2739         }
2740 }
2741
2742 /*
2743  * Our character device read / write functions.
2744  *
2745  * The tape is optimized to maximize throughput when it is transferring an
2746  * integral number of the "continuous transfer limit", which is a parameter of
2747  * the specific tape (26kB on my particular tape, 32kB for Onstream).
2748  *
2749  * As of version 1.3 of the driver, the character device provides an abstract
2750  * continuous view of the media - any mix of block sizes (even 1 byte) on the
2751  * same backup/restore procedure is supported. The driver will internally
2752  * convert the requests to the recommended transfer unit, so that an unmatch
2753  * between the user's block size to the recommended size will only result in a
2754  * (slightly) increased driver overhead, but will no longer hit performance.
2755  * This is not applicable to Onstream.
2756  */
2757 static ssize_t idetape_chrdev_read(struct file *file, char __user *buf,
2758                                    size_t count, loff_t *ppos)
2759 {
2760         struct ide_tape_obj *tape = ide_tape_f(file);
2761         ide_drive_t *drive = tape->drive;
2762         ssize_t bytes_read, temp, actually_read = 0, rc;
2763         ssize_t ret = 0;
2764         u16 ctl = *(u16 *)&tape->caps[12];
2765
2766         debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
2767
2768         if (tape->chrdev_dir != IDETAPE_DIR_READ) {
2769                 if (test_bit(IDETAPE_FLAG_DETECT_BS, &tape->flags))
2770                         if (count > tape->blk_size &&
2771                             (count % tape->blk_size) == 0)
2772                                 tape->user_bs_factor = count / tape->blk_size;
2773         }
2774         rc = idetape_init_read(drive, tape->max_stages);
2775         if (rc < 0)
2776                 return rc;
2777         if (count == 0)
2778                 return (0);
2779         if (tape->merge_stage_size) {
2780                 actually_read = min((unsigned int)(tape->merge_stage_size),
2781                                     (unsigned int)count);
2782                 if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage,
2783                                                actually_read))
2784                         ret = -EFAULT;
2785                 buf += actually_read;
2786                 tape->merge_stage_size -= actually_read;
2787                 count -= actually_read;
2788         }
2789         while (count >= tape->stage_size) {
2790                 bytes_read = idetape_add_chrdev_read_request(drive, ctl);
2791                 if (bytes_read <= 0)
2792                         goto finish;
2793                 if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage,
2794                                                bytes_read))
2795                         ret = -EFAULT;
2796                 buf += bytes_read;
2797                 count -= bytes_read;
2798                 actually_read += bytes_read;
2799         }
2800         if (count) {
2801                 bytes_read = idetape_add_chrdev_read_request(drive, ctl);
2802                 if (bytes_read <= 0)
2803                         goto finish;
2804                 temp = min((unsigned long)count, (unsigned long)bytes_read);
2805                 if (idetape_copy_stage_to_user(tape, buf, tape->merge_stage,
2806                                                temp))
2807                         ret = -EFAULT;
2808                 actually_read += temp;
2809                 tape->merge_stage_size = bytes_read-temp;
2810         }
2811 finish:
2812         if (!actually_read && test_bit(IDETAPE_FLAG_FILEMARK, &tape->flags)) {
2813                 debug_log(DBG_SENSE, "%s: spacing over filemark\n", tape->name);
2814
2815                 idetape_space_over_filemarks(drive, MTFSF, 1);
2816                 return 0;
2817         }
2818
2819         return ret ? ret : actually_read;
2820 }
2821
2822 static ssize_t idetape_chrdev_write(struct file *file, const char __user *buf,
2823                                      size_t count, loff_t *ppos)
2824 {
2825         struct ide_tape_obj *tape = ide_tape_f(file);
2826         ide_drive_t *drive = tape->drive;
2827         ssize_t actually_written = 0;
2828         ssize_t ret = 0;
2829         u16 ctl = *(u16 *)&tape->caps[12];
2830
2831         /* The drive is write protected. */
2832         if (tape->write_prot)
2833                 return -EACCES;
2834
2835         debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
2836
2837         /* Initialize write operation */
2838         if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
2839                 if (tape->chrdev_dir == IDETAPE_DIR_READ)
2840                         idetape_discard_read_pipeline(drive, 1);
2841                 if (tape->merge_stage || tape->merge_stage_size) {
2842                         printk(KERN_ERR "ide-tape: merge_stage_size "
2843                                 "should be 0 now\n");
2844                         tape->merge_stage_size = 0;
2845                 }
2846                 tape->merge_stage = __idetape_kmalloc_stage(tape, 0, 0);
2847                 if (!tape->merge_stage)
2848                         return -ENOMEM;
2849                 tape->chrdev_dir = IDETAPE_DIR_WRITE;
2850                 idetape_init_merge_stage(tape);
2851
2852                 /*
2853                  * Issue a write 0 command to ensure that DSC handshake is
2854                  * switched from completion mode to buffer available mode. No
2855                  * point in issuing this if DSC overlap isn't supported, some
2856                  * drives (Seagate STT3401A) will return an error.
2857                  */
2858                 if (drive->dsc_overlap) {
2859                         ssize_t retval = idetape_queue_rw_tail(drive,
2860                                                         REQ_IDETAPE_WRITE, 0,
2861                                                         tape->merge_stage->bh);
2862                         if (retval < 0) {
2863                                 __idetape_kfree_stage(tape->merge_stage);
2864                                 tape->merge_stage = NULL;
2865                                 tape->chrdev_dir = IDETAPE_DIR_NONE;
2866                                 return retval;
2867                         }
2868                 }
2869         }
2870         if (count == 0)
2871                 return (0);
2872         if (tape->restart_speed_control_req)
2873                 idetape_restart_speed_control(drive);
2874         if (tape->merge_stage_size) {
2875                 if (tape->merge_stage_size >= tape->stage_size) {
2876                         printk(KERN_ERR "ide-tape: bug: merge buf too big\n");
2877                         tape->merge_stage_size = 0;
2878                 }
2879                 actually_written = min((unsigned int)
2880                                 (tape->stage_size - tape->merge_stage_size),
2881                                 (unsigned int)count);
2882                 if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf,
2883                                                  actually_written))
2884                                 ret = -EFAULT;
2885                 buf += actually_written;
2886                 tape->merge_stage_size += actually_written;
2887                 count -= actually_written;
2888
2889                 if (tape->merge_stage_size == tape->stage_size) {
2890                         ssize_t retval;
2891                         tape->merge_stage_size = 0;
2892                         retval = idetape_add_chrdev_write_request(drive, ctl);
2893                         if (retval <= 0)
2894                                 return (retval);
2895                 }
2896         }
2897         while (count >= tape->stage_size) {
2898                 ssize_t retval;
2899                 if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf,
2900                                                  tape->stage_size))
2901                         ret = -EFAULT;
2902                 buf += tape->stage_size;
2903                 count -= tape->stage_size;
2904                 retval = idetape_add_chrdev_write_request(drive, ctl);
2905                 actually_written += tape->stage_size;
2906                 if (retval <= 0)
2907                         return (retval);
2908         }
2909         if (count) {
2910                 actually_written += count;
2911                 if (idetape_copy_stage_from_user(tape, tape->merge_stage, buf,
2912                                                  count))
2913                         ret = -EFAULT;
2914                 tape->merge_stage_size += count;
2915         }
2916         return ret ? ret : actually_written;
2917 }
2918
2919 static int idetape_write_filemark(ide_drive_t *drive)
2920 {
2921         struct ide_atapi_pc pc;
2922
2923         /* Write a filemark */
2924         idetape_create_write_filemark_cmd(drive, &pc, 1);
2925         if (idetape_queue_pc_tail(drive, &pc)) {
2926                 printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
2927                 return -EIO;
2928         }
2929         return 0;
2930 }
2931
2932 /*
2933  * Called from idetape_chrdev_ioctl when the general mtio MTIOCTOP ioctl is
2934  * requested.
2935  *
2936  * Note: MTBSF and MTBSFM are not supported when the tape doesn't support
2937  * spacing over filemarks in the reverse direction. In this case, MTFSFM is also
2938  * usually not supported (it is supported in the rare case in which we crossed
2939  * the filemark during our read-ahead pipelined operation mode).
2940  *
2941  * The following commands are currently not supported:
2942  *
2943  * MTFSS, MTBSS, MTWSM, MTSETDENSITY, MTSETDRVBUFFER, MT_ST_BOOLEANS,
2944  * MT_ST_WRITE_THRESHOLD.
2945  */
2946 static int idetape_mtioctop(ide_drive_t *drive, short mt_op, int mt_count)
2947 {
2948         idetape_tape_t *tape = drive->driver_data;
2949         struct ide_atapi_pc pc;
2950         int i, retval;
2951
2952         debug_log(DBG_ERR, "Handling MTIOCTOP ioctl: mt_op=%d, mt_count=%d\n",
2953                         mt_op, mt_count);
2954
2955         /* Commands which need our pipelined read-ahead stages. */
2956         switch (mt_op) {
2957         case MTFSF:
2958         case MTFSFM:
2959         case MTBSF:
2960         case MTBSFM:
2961                 if (!mt_count)
2962                         return 0;
2963                 return idetape_space_over_filemarks(drive, mt_op, mt_count);
2964         default:
2965                 break;
2966         }
2967
2968         switch (mt_op) {
2969         case MTWEOF:
2970                 if (tape->write_prot)
2971                         return -EACCES;
2972                 idetape_discard_read_pipeline(drive, 1);
2973                 for (i = 0; i < mt_count; i++) {
2974                         retval = idetape_write_filemark(drive);
2975                         if (retval)
2976                                 return retval;
2977                 }
2978                 return 0;
2979         case MTREW:
2980                 idetape_discard_read_pipeline(drive, 0);
2981                 if (idetape_rewind_tape(drive))
2982                         return -EIO;
2983                 return 0;
2984         case MTLOAD:
2985                 idetape_discard_read_pipeline(drive, 0);
2986                 idetape_create_load_unload_cmd(drive, &pc,
2987                                                IDETAPE_LU_LOAD_MASK);
2988                 return idetape_queue_pc_tail(drive, &pc);
2989         case MTUNLOAD:
2990         case MTOFFL:
2991                 /*
2992                  * If door is locked, attempt to unlock before
2993                  * attempting to eject.
2994                  */
2995                 if (tape->door_locked) {
2996                         if (idetape_create_prevent_cmd(drive, &pc, 0))
2997                                 if (!idetape_queue_pc_tail(drive, &pc))
2998                                         tape->door_locked = DOOR_UNLOCKED;
2999                 }
3000                 idetape_discard_read_pipeline(drive, 0);
3001                 idetape_create_load_unload_cmd(drive, &pc,
3002                                               !IDETAPE_LU_LOAD_MASK);
3003                 retval = idetape_queue_pc_tail(drive, &pc);
3004                 if (!retval)
3005                         clear_bit(IDETAPE_FLAG_MEDIUM_PRESENT, &tape->flags);
3006                 return retval;
3007         case MTNOP:
3008                 idetape_discard_read_pipeline(drive, 0);
3009                 return idetape_flush_tape_buffers(drive);
3010         case MTRETEN:
3011                 idetape_discard_read_pipeline(drive, 0);
3012                 idetape_create_load_unload_cmd(drive, &pc,
3013                         IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
3014                 return idetape_queue_pc_tail(drive, &pc);
3015         case MTEOM:
3016                 idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
3017                 return idetape_queue_pc_tail(drive, &pc);
3018         case MTERASE:
3019                 (void)idetape_rewind_tape(drive);
3020                 idetape_create_erase_cmd(&pc);
3021                 return idetape_queue_pc_tail(drive, &pc);
3022         case MTSETBLK:
3023                 if (mt_count) {
3024                         if (mt_count < tape->blk_size ||
3025                             mt_count % tape->blk_size)
3026                                 return -EIO;
3027                         tape->user_bs_factor = mt_count / tape->blk_size;
3028                         clear_bit(IDETAPE_FLAG_DETECT_BS, &tape->flags);
3029                 } else
3030                         set_bit(IDETAPE_FLAG_DETECT_BS, &tape->flags);
3031                 return 0;
3032         case MTSEEK:
3033                 idetape_discard_read_pipeline(drive, 0);
3034                 return idetape_position_tape(drive,
3035                         mt_count * tape->user_bs_factor, tape->partition, 0);
3036         case MTSETPART:
3037                 idetape_discard_read_pipeline(drive, 0);
3038                 return idetape_position_tape(drive, 0, mt_count, 0);
3039         case MTFSR:
3040         case MTBSR:
3041         case MTLOCK:
3042                 if (!idetape_create_prevent_cmd(drive, &pc, 1))
3043                         return 0;
3044                 retval = idetape_queue_pc_tail(drive, &pc);
3045                 if (retval)
3046                         return retval;
3047                 tape->door_locked = DOOR_EXPLICITLY_LOCKED;
3048                 return 0;
3049         case MTUNLOCK:
3050                 if (!idetape_create_prevent_cmd(drive, &pc, 0))
3051                         return 0;
3052                 retval = idetape_queue_pc_tail(drive, &pc);
3053                 if (retval)
3054                         return retval;
3055                 tape->door_locked = DOOR_UNLOCKED;
3056                 return 0;
3057         default:
3058                 printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
3059                                 mt_op);
3060                 return -EIO;
3061         }
3062 }
3063
3064 /*
3065  * Our character device ioctls. General mtio.h magnetic io commands are
3066  * supported here, and not in the corresponding block interface. Our own
3067  * ide-tape ioctls are supported on both interfaces.
3068  */
3069 static int idetape_chrdev_ioctl(struct inode *inode, struct file *file,
3070                                 unsigned int cmd, unsigned long arg)
3071 {
3072         struct ide_tape_obj *tape = ide_tape_f(file);
3073         ide_drive_t *drive = tape->drive;
3074         struct mtop mtop;
3075         struct mtget mtget;
3076         struct mtpos mtpos;
3077         int block_offset = 0, position = tape->first_frame;
3078         void __user *argp = (void __user *)arg;
3079
3080         debug_log(DBG_CHRDEV, "Enter %s, cmd=%u\n", __func__, cmd);
3081
3082         tape->restart_speed_control_req = 1;
3083         if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
3084                 idetape_empty_write_pipeline(drive);
3085                 idetape_flush_tape_buffers(drive);
3086         }
3087         if (cmd == MTIOCGET || cmd == MTIOCPOS) {
3088                 block_offset = idetape_pipeline_size(drive) /
3089                         (tape->blk_size * tape->user_bs_factor);
3090                 position = idetape_read_position(drive);
3091                 if (position < 0)
3092                         return -EIO;
3093         }
3094         switch (cmd) {
3095         case MTIOCTOP:
3096                 if (copy_from_user(&mtop, argp, sizeof(struct mtop)))
3097                         return -EFAULT;
3098                 return idetape_mtioctop(drive, mtop.mt_op, mtop.mt_count);
3099         case MTIOCGET:
3100                 memset(&mtget, 0, sizeof(struct mtget));
3101                 mtget.mt_type = MT_ISSCSI2;
3102                 mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
3103                 mtget.mt_dsreg =
3104                         ((tape->blk_size * tape->user_bs_factor)
3105                          << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
3106
3107                 if (tape->drv_write_prot)
3108                         mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
3109
3110                 if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
3111                         return -EFAULT;
3112                 return 0;
3113         case MTIOCPOS:
3114                 mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
3115                 if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
3116                         return -EFAULT;
3117                 return 0;
3118         default:
3119                 if (tape->chrdev_dir == IDETAPE_DIR_READ)
3120                         idetape_discard_read_pipeline(drive, 1);
3121                 return idetape_blkdev_ioctl(drive, cmd, arg);
3122         }
3123 }
3124
3125 /*
3126  * Do a mode sense page 0 with block descriptor and if it succeeds set the tape
3127  * block size with the reported value.
3128  */
3129 static void ide_tape_get_bsize_from_bdesc(ide_drive_t *drive)
3130 {
3131         idetape_tape_t *tape = drive->driver_data;
3132         struct ide_atapi_pc pc;
3133
3134         idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
3135         if (idetape_queue_pc_tail(drive, &pc)) {
3136                 printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
3137                 if (tape->blk_size == 0) {
3138                         printk(KERN_WARNING "ide-tape: Cannot deal with zero "
3139                                             "block size, assuming 32k\n");
3140                         tape->blk_size = 32768;
3141                 }
3142                 return;
3143         }
3144         tape->blk_size = (pc.buf[4 + 5] << 16) +
3145                                 (pc.buf[4 + 6] << 8)  +
3146                                  pc.buf[4 + 7];
3147         tape->drv_write_prot = (pc.buf[2] & 0x80) >> 7;
3148 }
3149
3150 static int idetape_chrdev_open(struct inode *inode, struct file *filp)
3151 {
3152         unsigned int minor = iminor(inode), i = minor & ~0xc0;
3153         ide_drive_t *drive;
3154         idetape_tape_t *tape;
3155         struct ide_atapi_pc pc;
3156         int retval;
3157
3158         if (i >= MAX_HWIFS * MAX_DRIVES)
3159                 return -ENXIO;
3160
3161         tape = ide_tape_chrdev_get(i);
3162         if (!tape)
3163                 return -ENXIO;
3164
3165         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
3166
3167         /*
3168          * We really want to do nonseekable_open(inode, filp); here, but some
3169          * versions of tar incorrectly call lseek on tapes and bail out if that
3170          * fails.  So we disallow pread() and pwrite(), but permit lseeks.
3171          */
3172         filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
3173
3174         drive = tape->drive;
3175
3176         filp->private_data = tape;
3177
3178         if (test_and_set_bit(IDETAPE_FLAG_BUSY, &tape->flags)) {
3179                 retval = -EBUSY;
3180                 goto out_put_tape;
3181         }
3182
3183         retval = idetape_wait_ready(drive, 60 * HZ);
3184         if (retval) {
3185                 clear_bit(IDETAPE_FLAG_BUSY, &tape->flags);
3186                 printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
3187                 goto out_put_tape;
3188         }
3189
3190         idetape_read_position(drive);
3191         if (!test_bit(IDETAPE_FLAG_ADDRESS_VALID, &tape->flags))
3192                 (void)idetape_rewind_tape(drive);
3193
3194         if (tape->chrdev_dir != IDETAPE_DIR_READ)
3195                 clear_bit(IDETAPE_FLAG_PIPELINE_ERR, &tape->flags);
3196
3197         /* Read block size and write protect status from drive. */
3198         ide_tape_get_bsize_from_bdesc(drive);
3199
3200         /* Set write protect flag if device is opened as read-only. */
3201         if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
3202                 tape->write_prot = 1;
3203         else
3204                 tape->write_prot = tape->drv_write_prot;
3205
3206         /* Make sure drive isn't write protected if user wants to write. */
3207         if (tape->write_prot) {
3208                 if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
3209                     (filp->f_flags & O_ACCMODE) == O_RDWR) {
3210                         clear_bit(IDETAPE_FLAG_BUSY, &tape->flags);
3211                         retval = -EROFS;
3212                         goto out_put_tape;
3213                 }
3214         }
3215
3216         /* Lock the tape drive door so user can't eject. */
3217         if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
3218                 if (idetape_create_prevent_cmd(drive, &pc, 1)) {
3219                         if (!idetape_queue_pc_tail(drive, &pc)) {
3220                                 if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
3221                                         tape->door_locked = DOOR_LOCKED;
3222                         }
3223                 }
3224         }
3225         idetape_restart_speed_control(drive);
3226         tape->restart_speed_control_req = 0;
3227         return 0;
3228
3229 out_put_tape:
3230         ide_tape_put(tape);
3231         return retval;
3232 }
3233
3234 static void idetape_write_release(ide_drive_t *drive, unsigned int minor)
3235 {
3236         idetape_tape_t *tape = drive->driver_data;
3237
3238         idetape_empty_write_pipeline(drive);
3239         tape->merge_stage = __idetape_kmalloc_stage(tape, 1, 0);
3240         if (tape->merge_stage != NULL) {
3241                 idetape_pad_zeros(drive, tape->blk_size *
3242                                 (tape->user_bs_factor - 1));
3243                 __idetape_kfree_stage(tape->merge_stage);
3244                 tape->merge_stage = NULL;
3245         }
3246         idetape_write_filemark(drive);
3247         idetape_flush_tape_buffers(drive);
3248         idetape_flush_tape_buffers(drive);
3249 }
3250
3251 static int idetape_chrdev_release(struct inode *inode, struct file *filp)
3252 {
3253         struct ide_tape_obj *tape = ide_tape_f(filp);
3254         ide_drive_t *drive = tape->drive;
3255         struct ide_atapi_pc pc;
3256         unsigned int minor = iminor(inode);
3257
3258         lock_kernel();
3259         tape = drive->driver_data;
3260
3261         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
3262
3263         if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
3264                 idetape_write_release(drive, minor);
3265         if (tape->chrdev_dir == IDETAPE_DIR_READ) {
3266                 if (minor < 128)
3267                         idetape_discard_read_pipeline(drive, 1);
3268                 else
3269                         idetape_wait_for_pipeline(drive);
3270         }
3271         if (tape->cache_stage != NULL) {
3272                 __idetape_kfree_stage(tape->cache_stage);
3273                 tape->cache_stage = NULL;
3274         }
3275         if (minor < 128 && test_bit(IDETAPE_FLAG_MEDIUM_PRESENT, &tape->flags))
3276                 (void) idetape_rewind_tape(drive);
3277         if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
3278                 if (tape->door_locked == DOOR_LOCKED) {
3279                         if (idetape_create_prevent_cmd(drive, &pc, 0)) {
3280                                 if (!idetape_queue_pc_tail(drive, &pc))
3281                                         tape->door_locked = DOOR_UNLOCKED;
3282                         }
3283                 }
3284         }
3285         clear_bit(IDETAPE_FLAG_BUSY, &tape->flags);
3286         ide_tape_put(tape);
3287         unlock_kernel();
3288         return 0;
3289 }
3290
3291 /*
3292  * check the contents of the ATAPI IDENTIFY command results. We return:
3293  *
3294  * 1 - If the tape can be supported by us, based on the information we have so
3295  * far.
3296  *
3297  * 0 - If this tape driver is not currently supported by us.
3298  */
3299 static int idetape_identify_device(ide_drive_t *drive)
3300 {
3301         u8 gcw[2], protocol, device_type, removable, packet_size;
3302
3303         if (drive->id_read == 0)
3304                 return 1;
3305
3306         *((unsigned short *) &gcw) = drive->id->config;
3307
3308         protocol        =   (gcw[1] & 0xC0) >> 6;
3309         device_type     =    gcw[1] & 0x1F;
3310         removable       = !!(gcw[0] & 0x80);
3311         packet_size     =    gcw[0] & 0x3;
3312
3313         /* Check that we can support this device */
3314         if (protocol != 2)
3315                 printk(KERN_ERR "ide-tape: Protocol (0x%02x) is not ATAPI\n",
3316                                 protocol);
3317         else if (device_type != 1)
3318                 printk(KERN_ERR "ide-tape: Device type (0x%02x) is not set "
3319                                 "to tape\n", device_type);
3320         else if (!removable)
3321                 printk(KERN_ERR "ide-tape: The removable flag is not set\n");
3322         else if (packet_size != 0) {
3323                 printk(KERN_ERR "ide-tape: Packet size (0x%02x) is not 12"
3324                                 " bytes\n", packet_size);
3325         } else
3326                 return 1;
3327         return 0;
3328 }
3329
3330 static void idetape_get_inquiry_results(ide_drive_t *drive)
3331 {
3332         idetape_tape_t *tape = drive->driver_data;
3333         struct ide_atapi_pc pc;
3334         char fw_rev[6], vendor_id[10], product_id[18];
3335
3336         idetape_create_inquiry_cmd(&pc);
3337         if (idetape_queue_pc_tail(drive, &pc)) {
3338                 printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
3339                                 tape->name);
3340                 return;
3341         }
3342         memcpy(vendor_id, &pc.buf[8], 8);
3343         memcpy(product_id, &pc.buf[16], 16);
3344         memcpy(fw_rev, &pc.buf[32], 4);
3345
3346         ide_fixstring(vendor_id, 10, 0);
3347         ide_fixstring(product_id, 18, 0);
3348         ide_fixstring(fw_rev, 6, 0);
3349
3350         printk(KERN_INFO "ide-tape: %s <-> %s: %s %s rev %s\n",
3351                         drive->name, tape->name, vendor_id, product_id, fw_rev);
3352 }
3353
3354 /*
3355  * Ask the tape about its various parameters. In particular, we will adjust our
3356  * data transfer buffer size to the recommended value as returned by the tape.
3357  */
3358 static void idetape_get_mode_sense_results(ide_drive_t *drive)
3359 {
3360         idetape_tape_t *tape = drive->driver_data;
3361         struct ide_atapi_pc pc;
3362         u8 *caps;
3363         u8 speed, max_speed;
3364
3365         idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
3366         if (idetape_queue_pc_tail(drive, &pc)) {
3367                 printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
3368                                 " some default values\n");
3369                 tape->blk_size = 512;
3370                 put_unaligned(52,   (u16 *)&tape->caps[12]);
3371                 put_unaligned(540,  (u16 *)&tape->caps[14]);
3372                 put_unaligned(6*52, (u16 *)&tape->caps[16]);
3373                 return;
3374         }
3375         caps = pc.buf + 4 + pc.buf[3];
3376
3377         /* convert to host order and save for later use */
3378         speed = be16_to_cpu(*(u16 *)&caps[14]);
3379         max_speed = be16_to_cpu(*(u16 *)&caps[8]);
3380
3381         put_unaligned(max_speed, (u16 *)&caps[8]);
3382         put_unaligned(be16_to_cpu(*(u16 *)&caps[12]), (u16 *)&caps[12]);
3383         put_unaligned(speed, (u16 *)&caps[14]);
3384         put_unaligned(be16_to_cpu(*(u16 *)&caps[16]), (u16 *)&caps[16]);
3385
3386         if (!speed) {
3387                 printk(KERN_INFO "ide-tape: %s: invalid tape speed "
3388                                 "(assuming 650KB/sec)\n", drive->name);
3389                 put_unaligned(650, (u16 *)&caps[14]);
3390         }
3391         if (!max_speed) {
3392                 printk(KERN_INFO "ide-tape: %s: invalid max_speed "
3393                                 "(assuming 650KB/sec)\n", drive->name);
3394                 put_unaligned(650, (u16 *)&caps[8]);
3395         }
3396
3397         memcpy(&tape->caps, caps, 20);
3398         if (caps[7] & 0x02)
3399                 tape->blk_size = 512;
3400         else if (caps[7] & 0x04)
3401                 tape->blk_size = 1024;
3402 }
3403
3404 #ifdef CONFIG_IDE_PROC_FS
3405 static void idetape_add_settings(ide_drive_t *drive)
3406 {
3407         idetape_tape_t *tape = drive->driver_data;
3408
3409         ide_add_setting(drive, "buffer", SETTING_READ, TYPE_SHORT, 0, 0xffff,
3410                         1, 2, (u16 *)&tape->caps[16], NULL);
3411         ide_add_setting(drive, "pipeline_min", SETTING_RW, TYPE_INT, 1, 0xffff,
3412                         tape->stage_size / 1024, 1, &tape->min_pipeline, NULL);
3413         ide_add_setting(drive, "pipeline", SETTING_RW, TYPE_INT, 1, 0xffff,
3414                         tape->stage_size / 1024, 1, &tape->max_stages, NULL);
3415         ide_add_setting(drive, "pipeline_max", SETTING_RW, TYPE_INT, 1, 0xffff,
3416                         tape->stage_size / 1024, 1, &tape->max_pipeline, NULL);
3417         ide_add_setting(drive, "pipeline_used", SETTING_READ, TYPE_INT, 0,
3418                         0xffff, tape->stage_size / 1024, 1, &tape->nr_stages,
3419                         NULL);
3420         ide_add_setting(drive, "pipeline_pending", SETTING_READ, TYPE_INT, 0,
3421                         0xffff, tape->stage_size / 1024, 1,
3422                         &tape->nr_pending_stages, NULL);
3423         ide_add_setting(drive, "speed", SETTING_READ, TYPE_SHORT, 0, 0xffff,
3424                         1, 1, (u16 *)&tape->caps[14], NULL);
3425         ide_add_setting(drive, "stage", SETTING_READ, TYPE_INT, 0, 0xffff, 1,
3426                         1024, &tape->stage_size, NULL);
3427         ide_add_setting(drive, "tdsc", SETTING_RW, TYPE_INT, IDETAPE_DSC_RW_MIN,
3428                         IDETAPE_DSC_RW_MAX, 1000, HZ, &tape->best_dsc_rw_freq,
3429                         NULL);
3430         ide_add_setting(drive, "dsc_overlap", SETTING_RW, TYPE_BYTE, 0, 1, 1,
3431                         1, &drive->dsc_overlap, NULL);
3432         ide_add_setting(drive, "pipeline_head_speed_c", SETTING_READ, TYPE_INT,
3433                         0, 0xffff, 1, 1, &tape->controlled_pipeline_head_speed,
3434                         NULL);
3435         ide_add_setting(drive, "pipeline_head_speed_u", SETTING_READ, TYPE_INT,
3436                         0, 0xffff, 1, 1,
3437                         &tape->uncontrolled_pipeline_head_speed, NULL);
3438         ide_add_setting(drive, "avg_speed", SETTING_READ, TYPE_INT, 0, 0xffff,
3439                         1, 1, &tape->avg_speed, NULL);
3440         ide_add_setting(drive, "debug_mask", SETTING_RW, TYPE_INT, 0, 0xffff, 1,
3441                         1, &tape->debug_mask, NULL);
3442 }
3443 #else
3444 static inline void idetape_add_settings(ide_drive_t *drive) { ; }
3445 #endif
3446
3447 /*
3448  * The function below is called to:
3449  *
3450  * 1. Initialize our various state variables.
3451  * 2. Ask the tape for its capabilities.
3452  * 3. Allocate a buffer which will be used for data transfer. The buffer size
3453  * is chosen based on the recommendation which we received in step 2.
3454  *
3455  * Note that at this point ide.c already assigned us an irq, so that we can
3456  * queue requests here and wait for their completion.
3457  */
3458 static void idetape_setup(ide_drive_t *drive, idetape_tape_t *tape, int minor)
3459 {
3460         unsigned long t1, tmid, tn, t;
3461         int speed;
3462         int stage_size;
3463         u8 gcw[2];
3464         struct sysinfo si;
3465         u16 *ctl = (u16 *)&tape->caps[12];
3466
3467         spin_lock_init(&tape->lock);
3468         drive->dsc_overlap = 1;
3469         if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
3470                 printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
3471                                  tape->name);
3472                 drive->dsc_overlap = 0;
3473         }
3474         /* Seagate Travan drives do not support DSC overlap. */
3475         if (strstr(drive->id->model, "Seagate STT3401"))
3476                 drive->dsc_overlap = 0;
3477         tape->minor = minor;
3478         tape->name[0] = 'h';
3479         tape->name[1] = 't';
3480         tape->name[2] = '0' + minor;
3481         tape->chrdev_dir = IDETAPE_DIR_NONE;
3482         tape->pc = tape->pc_stack;
3483         tape->max_insert_speed = 10000;
3484         tape->speed_control = 1;
3485         *((unsigned short *) &gcw) = drive->id->config;
3486
3487         /* Command packet DRQ type */
3488         if (((gcw[0] & 0x60) >> 5) == 1)
3489                 set_bit(IDETAPE_FLAG_DRQ_INTERRUPT, &tape->flags);
3490
3491         tape->min_pipeline = 10;
3492         tape->max_pipeline = 10;
3493         tape->max_stages   = 10;
3494
3495         idetape_get_inquiry_results(drive);
3496         idetape_get_mode_sense_results(drive);
3497         ide_tape_get_bsize_from_bdesc(drive);
3498         tape->user_bs_factor = 1;
3499         tape->stage_size = *ctl * tape->blk_size;
3500         while (tape->stage_size > 0xffff) {
3501                 printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
3502                 *ctl /= 2;
3503                 tape->stage_size = *ctl * tape->blk_size;
3504         }
3505         stage_size = tape->stage_size;
3506         tape->pages_per_stage = stage_size / PAGE_SIZE;
3507         if (stage_size % PAGE_SIZE) {
3508                 tape->pages_per_stage++;
3509                 tape->excess_bh_size = PAGE_SIZE - stage_size % PAGE_SIZE;
3510         }
3511
3512         /* Select the "best" DSC read/write polling freq and pipeline size. */
3513         speed = max(*(u16 *)&tape->caps[14], *(u16 *)&tape->caps[8]);
3514
3515         tape->max_stages = speed * 1000 * 10 / tape->stage_size;
3516
3517         /* Limit memory use for pipeline to 10% of physical memory */
3518         si_meminfo(&si);
3519         if (tape->max_stages * tape->stage_size >
3520                         si.totalram * si.mem_unit / 10)
3521                 tape->max_stages =
3522                         si.totalram * si.mem_unit / (10 * tape->stage_size);
3523
3524         tape->max_stages   = min(tape->max_stages, IDETAPE_MAX_PIPELINE_STAGES);
3525         tape->min_pipeline = min(tape->max_stages, IDETAPE_MIN_PIPELINE_STAGES);
3526         tape->max_pipeline =
3527                 min(tape->max_stages * 2, IDETAPE_MAX_PIPELINE_STAGES);
3528         if (tape->max_stages == 0) {
3529                 tape->max_stages   = 1;
3530                 tape->min_pipeline = 1;
3531                 tape->max_pipeline = 1;
3532         }
3533
3534         t1 = (tape->stage_size * HZ) / (speed * 1000);
3535         tmid = (*(u16 *)&tape->caps[16] * 32 * HZ) / (speed * 125);
3536         tn = (IDETAPE_FIFO_THRESHOLD * tape->stage_size * HZ) / (speed * 1000);
3537
3538         if (tape->max_stages)
3539                 t = tn;
3540         else
3541                 t = t1;
3542
3543         /*
3544          * Ensure that the number we got makes sense; limit it within
3545          * IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
3546          */
3547         tape->best_dsc_rw_freq = max_t(unsigned long,
3548                                 min_t(unsigned long, t, IDETAPE_DSC_RW_MAX),
3549                                 IDETAPE_DSC_RW_MIN);
3550         printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
3551                 "%dkB pipeline, %lums tDSC%s\n",
3552                 drive->name, tape->name, *(u16 *)&tape->caps[14],
3553                 (*(u16 *)&tape->caps[16] * 512) / tape->stage_size,
3554                 tape->stage_size / 1024,
3555                 tape->max_stages * tape->stage_size / 1024,
3556                 tape->best_dsc_rw_freq * 1000 / HZ,
3557                 drive->using_dma ? ", DMA":"");
3558
3559         idetape_add_settings(drive);
3560 }
3561
3562 static void ide_tape_remove(ide_drive_t *drive)
3563 {
3564         idetape_tape_t *tape = drive->driver_data;
3565
3566         ide_proc_unregister_driver(drive, tape->driver);
3567
3568         ide_unregister_region(tape->disk);
3569
3570         ide_tape_put(tape);
3571 }
3572
3573 static void ide_tape_release(struct kref *kref)
3574 {
3575         struct ide_tape_obj *tape = to_ide_tape(kref);
3576         ide_drive_t *drive = tape->drive;
3577         struct gendisk *g = tape->disk;
3578
3579         BUG_ON(tape->first_stage != NULL || tape->merge_stage_size);
3580
3581         drive->dsc_overlap = 0;
3582         drive->driver_data = NULL;
3583         device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
3584         device_destroy(idetape_sysfs_class,
3585                         MKDEV(IDETAPE_MAJOR, tape->minor + 128));
3586         idetape_devs[tape->minor] = NULL;
3587         g->private_data = NULL;
3588         put_disk(g);
3589         kfree(tape);
3590 }
3591
3592 #ifdef CONFIG_IDE_PROC_FS
3593 static int proc_idetape_read_name
3594         (char *page, char **start, off_t off, int count, int *eof, void *data)
3595 {
3596         ide_drive_t     *drive = (ide_drive_t *) data;
3597         idetape_tape_t  *tape = drive->driver_data;
3598         char            *out = page;
3599         int             len;
3600
3601         len = sprintf(out, "%s\n", tape->name);
3602         PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
3603 }
3604
3605 static ide_proc_entry_t idetape_proc[] = {
3606         { "capacity",   S_IFREG|S_IRUGO,        proc_ide_read_capacity, NULL },
3607         { "name",       S_IFREG|S_IRUGO,        proc_idetape_read_name, NULL },
3608         { NULL, 0, NULL, NULL }
3609 };
3610 #endif
3611
3612 static int ide_tape_probe(ide_drive_t *);
3613
3614 static ide_driver_t idetape_driver = {
3615         .gen_driver = {
3616                 .owner          = THIS_MODULE,
3617                 .name           = "ide-tape",
3618                 .bus            = &ide_bus_type,
3619         },
3620         .probe                  = ide_tape_probe,
3621         .remove                 = ide_tape_remove,
3622         .version                = IDETAPE_VERSION,
3623         .media                  = ide_tape,
3624         .supports_dsc_overlap   = 1,
3625         .do_request             = idetape_do_request,
3626         .end_request            = idetape_end_request,
3627         .error                  = __ide_error,
3628         .abort                  = __ide_abort,
3629 #ifdef CONFIG_IDE_PROC_FS
3630         .proc                   = idetape_proc,
3631 #endif
3632 };
3633
3634 /* Our character device supporting functions, passed to register_chrdev. */
3635 static const struct file_operations idetape_fops = {
3636         .owner          = THIS_MODULE,
3637         .read           = idetape_chrdev_read,
3638         .write          = idetape_chrdev_write,
3639         .ioctl          = idetape_chrdev_ioctl,
3640         .open           = idetape_chrdev_open,
3641         .release        = idetape_chrdev_release,
3642 };
3643
3644 static int idetape_open(struct inode *inode, struct file *filp)
3645 {
3646         struct gendisk *disk = inode->i_bdev->bd_disk;
3647         struct ide_tape_obj *tape;
3648
3649         tape = ide_tape_get(disk);
3650         if (!tape)
3651                 return -ENXIO;
3652
3653         return 0;
3654 }
3655
3656 static int idetape_release(struct inode *inode, struct file *filp)
3657 {
3658         struct gendisk *disk = inode->i_bdev->bd_disk;
3659         struct ide_tape_obj *tape = ide_tape_g(disk);
3660
3661         ide_tape_put(tape);
3662
3663         return 0;
3664 }
3665
3666 static int idetape_ioctl(struct inode *inode, struct file *file,
3667                         unsigned int cmd, unsigned long arg)
3668 {
3669         struct block_device *bdev = inode->i_bdev;
3670         struct ide_tape_obj *tape = ide_tape_g(bdev->bd_disk);
3671         ide_drive_t *drive = tape->drive;
3672         int err = generic_ide_ioctl(drive, file, bdev, cmd, arg);
3673         if (err == -EINVAL)
3674                 err = idetape_blkdev_ioctl(drive, cmd, arg);
3675         return err;
3676 }
3677
3678 static struct block_device_operations idetape_block_ops = {
3679         .owner          = THIS_MODULE,
3680         .open           = idetape_open,
3681         .release        = idetape_release,
3682         .ioctl          = idetape_ioctl,
3683 };
3684
3685 static int ide_tape_probe(ide_drive_t *drive)
3686 {
3687         idetape_tape_t *tape;
3688         struct gendisk *g;
3689         int minor;
3690
3691         if (!strstr("ide-tape", drive->driver_req))
3692                 goto failed;
3693         if (!drive->present)
3694                 goto failed;
3695         if (drive->media != ide_tape)
3696                 goto failed;
3697         if (!idetape_identify_device(drive)) {
3698                 printk(KERN_ERR "ide-tape: %s: not supported by this version of"
3699                                 " the driver\n", drive->name);
3700                 goto failed;
3701         }
3702         if (drive->scsi) {
3703                 printk(KERN_INFO "ide-tape: passing drive %s to ide-scsi"
3704                                  " emulation.\n", drive->name);
3705                 goto failed;
3706         }
3707         tape = kzalloc(sizeof(idetape_tape_t), GFP_KERNEL);
3708         if (tape == NULL) {
3709                 printk(KERN_ERR "ide-tape: %s: Can't allocate a tape struct\n",
3710                                 drive->name);
3711                 goto failed;
3712         }
3713
3714         g = alloc_disk(1 << PARTN_BITS);
3715         if (!g)
3716                 goto out_free_tape;
3717
3718         ide_init_disk(g, drive);
3719
3720         ide_proc_register_driver(drive, &idetape_driver);
3721
3722         kref_init(&tape->kref);
3723
3724         tape->drive = drive;
3725         tape->driver = &idetape_driver;
3726         tape->disk = g;
3727
3728         g->private_data = &tape->driver;
3729
3730         drive->driver_data = tape;
3731
3732         mutex_lock(&idetape_ref_mutex);
3733         for (minor = 0; idetape_devs[minor]; minor++)
3734                 ;
3735         idetape_devs[minor] = tape;
3736         mutex_unlock(&idetape_ref_mutex);
3737
3738         idetape_setup(drive, tape, minor);
3739
3740         device_create(idetape_sysfs_class, &drive->gendev,
3741                       MKDEV(IDETAPE_MAJOR, minor), "%s", tape->name);
3742         device_create(idetape_sysfs_class, &drive->gendev,
3743                         MKDEV(IDETAPE_MAJOR, minor + 128), "n%s", tape->name);
3744
3745         g->fops = &idetape_block_ops;
3746         ide_register_region(g);
3747
3748         return 0;
3749
3750 out_free_tape:
3751         kfree(tape);
3752 failed:
3753         return -ENODEV;
3754 }
3755
3756 static void __exit idetape_exit(void)
3757 {
3758         driver_unregister(&idetape_driver.gen_driver);
3759         class_destroy(idetape_sysfs_class);
3760         unregister_chrdev(IDETAPE_MAJOR, "ht");
3761 }
3762
3763 static int __init idetape_init(void)
3764 {
3765         int error = 1;
3766         idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
3767         if (IS_ERR(idetape_sysfs_class)) {
3768                 idetape_sysfs_class = NULL;
3769                 printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
3770                 error = -EBUSY;
3771                 goto out;
3772         }
3773
3774         if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
3775                 printk(KERN_ERR "ide-tape: Failed to register chrdev"
3776                                 " interface\n");
3777                 error = -EBUSY;
3778                 goto out_free_class;
3779         }
3780
3781         error = driver_register(&idetape_driver.gen_driver);
3782         if (error)
3783                 goto out_free_driver;
3784
3785         return 0;
3786
3787 out_free_driver:
3788         driver_unregister(&idetape_driver.gen_driver);
3789 out_free_class:
3790         class_destroy(idetape_sysfs_class);
3791 out:
3792         return error;
3793 }
3794
3795 MODULE_ALIAS("ide:*m-tape*");
3796 module_init(idetape_init);
3797 module_exit(idetape_exit);
3798 MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);
3799 MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
3800 MODULE_LICENSE("GPL");