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