b2afbc7bcb6b19adb0dfb38469f4f9788b36914d
[safe/jmp/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 DRV_NAME "ide-tape"
19
20 #define IDETAPE_VERSION "1.20"
21
22 #include <linux/module.h>
23 #include <linux/types.h>
24 #include <linux/string.h>
25 #include <linux/kernel.h>
26 #include <linux/delay.h>
27 #include <linux/timer.h>
28 #include <linux/mm.h>
29 #include <linux/interrupt.h>
30 #include <linux/jiffies.h>
31 #include <linux/major.h>
32 #include <linux/errno.h>
33 #include <linux/genhd.h>
34 #include <linux/slab.h>
35 #include <linux/pci.h>
36 #include <linux/ide.h>
37 #include <linux/smp_lock.h>
38 #include <linux/completion.h>
39 #include <linux/bitops.h>
40 #include <linux/mutex.h>
41 #include <scsi/scsi.h>
42
43 #include <asm/byteorder.h>
44 #include <linux/irq.h>
45 #include <linux/uaccess.h>
46 #include <linux/io.h>
47 #include <asm/unaligned.h>
48 #include <linux/mtio.h>
49
50 enum {
51         /* output errors only */
52         DBG_ERR =               (1 << 0),
53         /* output all sense key/asc */
54         DBG_SENSE =             (1 << 1),
55         /* info regarding all chrdev-related procedures */
56         DBG_CHRDEV =            (1 << 2),
57         /* all remaining procedures */
58         DBG_PROCS =             (1 << 3),
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  * After each failed packet command we issue a request sense command and retry
77  * the packet command IDETAPE_MAX_PC_RETRIES times.
78  *
79  * Setting IDETAPE_MAX_PC_RETRIES to 0 will disable retries.
80  */
81 #define IDETAPE_MAX_PC_RETRIES          3
82
83 /*
84  * The following parameter is used to select the point in the internal tape fifo
85  * in which we will start to refill the buffer. Decreasing the following
86  * parameter will improve the system's latency and interactive response, while
87  * using a high value might improve system throughput.
88  */
89 #define IDETAPE_FIFO_THRESHOLD          2
90
91 /*
92  * DSC polling parameters.
93  *
94  * Polling for DSC (a single bit in the status register) is a very important
95  * function in ide-tape. There are two cases in which we poll for DSC:
96  *
97  * 1. Before a read/write packet command, to ensure that we can transfer data
98  * from/to the tape's data buffers, without causing an actual media access.
99  * In case the tape is not ready yet, we take out our request from the device
100  * request queue, so that ide.c could service requests from the other device
101  * on the same interface in the meantime.
102  *
103  * 2. After the successful initialization of a "media access packet command",
104  * which is a command that can take a long time to complete (the interval can
105  * range from several seconds to even an hour). Again, we postpone our request
106  * in the middle to free the bus for the other device. The polling frequency
107  * here should be lower than the read/write frequency since those media access
108  * commands are slow. We start from a "fast" frequency - IDETAPE_DSC_MA_FAST
109  * (1 second), and if we don't receive DSC after IDETAPE_DSC_MA_THRESHOLD
110  * (5 min), we switch it to a lower frequency - IDETAPE_DSC_MA_SLOW (1 min).
111  *
112  * We also set a timeout for the timer, in case something goes wrong. The
113  * timeout should be longer then the maximum execution time of a tape operation.
114  */
115
116 /* DSC timings. */
117 #define IDETAPE_DSC_RW_MIN              5*HZ/100        /* 50 msec */
118 #define IDETAPE_DSC_RW_MAX              40*HZ/100       /* 400 msec */
119 #define IDETAPE_DSC_RW_TIMEOUT          2*60*HZ         /* 2 minutes */
120 #define IDETAPE_DSC_MA_FAST             2*HZ            /* 2 seconds */
121 #define IDETAPE_DSC_MA_THRESHOLD        5*60*HZ         /* 5 minutes */
122 #define IDETAPE_DSC_MA_SLOW             30*HZ           /* 30 seconds */
123 #define IDETAPE_DSC_MA_TIMEOUT          2*60*60*HZ      /* 2 hours */
124
125 /*************************** End of tunable parameters ***********************/
126
127 /* tape directions */
128 enum {
129         IDETAPE_DIR_NONE  = (1 << 0),
130         IDETAPE_DIR_READ  = (1 << 1),
131         IDETAPE_DIR_WRITE = (1 << 2),
132 };
133
134 struct idetape_bh {
135         u32 b_size;
136         atomic_t b_count;
137         char *b_data;
138 };
139
140 /* Tape door status */
141 #define DOOR_UNLOCKED                   0
142 #define DOOR_LOCKED                     1
143 #define DOOR_EXPLICITLY_LOCKED          2
144
145 /* Some defines for the SPACE command */
146 #define IDETAPE_SPACE_OVER_FILEMARK     1
147 #define IDETAPE_SPACE_TO_EOD            3
148
149 /* Some defines for the LOAD UNLOAD command */
150 #define IDETAPE_LU_LOAD_MASK            1
151 #define IDETAPE_LU_RETENSION_MASK       2
152 #define IDETAPE_LU_EOT_MASK             4
153
154 /* Structures related to the SELECT SENSE / MODE SENSE packet commands. */
155 #define IDETAPE_BLOCK_DESCRIPTOR        0
156 #define IDETAPE_CAPABILITIES_PAGE       0x2a
157
158 /*
159  * Most of our global data which we need to save even as we leave the driver due
160  * to an interrupt or a timer event is stored in the struct defined below.
161  */
162 typedef struct ide_tape_obj {
163         ide_drive_t             *drive;
164         struct ide_driver       *driver;
165         struct gendisk          *disk;
166         struct device           dev;
167
168         /* used by REQ_IDETAPE_{READ,WRITE} requests */
169         struct ide_atapi_pc queued_pc;
170
171         /*
172          * DSC polling variables.
173          *
174          * While polling for DSC we use postponed_rq to postpone the current
175          * request so that ide.c will be able to service pending requests on the
176          * other device. Note that at most we will have only one DSC (usually
177          * data transfer) request in the device request queue.
178          */
179         struct request *postponed_rq;
180         /* The time in which we started polling for DSC */
181         unsigned long dsc_polling_start;
182         /* Timer used to poll for dsc */
183         struct timer_list dsc_timer;
184         /* Read/Write dsc polling frequency */
185         unsigned long best_dsc_rw_freq;
186         unsigned long dsc_poll_freq;
187         unsigned long dsc_timeout;
188
189         /* Read position information */
190         u8 partition;
191         /* Current block */
192         unsigned int first_frame;
193
194         /* Last error information */
195         u8 sense_key, asc, ascq;
196
197         /* Character device operation */
198         unsigned int minor;
199         /* device name */
200         char name[4];
201         /* Current character device data transfer direction */
202         u8 chrdev_dir;
203
204         /* tape block size, usually 512 or 1024 bytes */
205         unsigned short blk_size;
206         int user_bs_factor;
207
208         /* Copy of the tape's Capabilities and Mechanical Page */
209         u8 caps[20];
210
211         /*
212          * Active data transfer request parameters.
213          *
214          * At most, there is only one ide-tape originated data transfer request
215          * in the device request queue. This allows ide.c to easily service
216          * requests from the other device when we postpone our active request.
217          */
218
219         /* Data buffer size chosen based on the tape's recommendation */
220         int buffer_size;
221         /* merge buffer */
222         struct idetape_bh *merge_bh;
223         /* size of the merge buffer */
224         int merge_bh_size;
225         /* pointer to current buffer head within the merge buffer */
226         struct idetape_bh *bh;
227         char *b_data;
228         int b_count;
229
230         /* Measures average tape speed */
231         unsigned long avg_time;
232         int avg_size;
233         int avg_speed;
234
235         /* the door is currently locked */
236         int door_locked;
237         /* the tape hardware is write protected */
238         char drv_write_prot;
239         /* the tape is write protected (hardware or opened as read-only) */
240         char write_prot;
241
242         u32 debug_mask;
243 } idetape_tape_t;
244
245 static DEFINE_MUTEX(idetape_ref_mutex);
246
247 static struct class *idetape_sysfs_class;
248
249 static void ide_tape_release(struct device *);
250
251 static struct ide_tape_obj *ide_tape_get(struct gendisk *disk)
252 {
253         struct ide_tape_obj *tape = NULL;
254
255         mutex_lock(&idetape_ref_mutex);
256         tape = ide_drv_g(disk, ide_tape_obj);
257         if (tape) {
258                 if (ide_device_get(tape->drive))
259                         tape = NULL;
260                 else
261                         get_device(&tape->dev);
262         }
263         mutex_unlock(&idetape_ref_mutex);
264         return tape;
265 }
266
267 static void ide_tape_put(struct ide_tape_obj *tape)
268 {
269         ide_drive_t *drive = tape->drive;
270
271         mutex_lock(&idetape_ref_mutex);
272         put_device(&tape->dev);
273         ide_device_put(drive);
274         mutex_unlock(&idetape_ref_mutex);
275 }
276
277 /*
278  * The variables below are used for the character device interface. Additional
279  * state variables are defined in our ide_drive_t structure.
280  */
281 static struct ide_tape_obj *idetape_devs[MAX_HWIFS * MAX_DRIVES];
282
283 static struct ide_tape_obj *ide_tape_chrdev_get(unsigned int i)
284 {
285         struct ide_tape_obj *tape = NULL;
286
287         mutex_lock(&idetape_ref_mutex);
288         tape = idetape_devs[i];
289         if (tape)
290                 get_device(&tape->dev);
291         mutex_unlock(&idetape_ref_mutex);
292         return tape;
293 }
294
295 static int idetape_input_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
296                                   unsigned int bcount)
297 {
298         struct idetape_bh *bh = pc->bh;
299         int count;
300
301         if (bcount && bh) {
302                 count = min(
303                         (unsigned int)(bh->b_size - atomic_read(&bh->b_count)),
304                         bcount);
305                 drive->hwif->tp_ops->input_data(drive, NULL, bh->b_data +
306                                         atomic_read(&bh->b_count), count);
307                 bcount -= count;
308                 atomic_add(count, &bh->b_count);
309                 if (atomic_read(&bh->b_count) == bh->b_size)
310                         pc->bh = NULL;
311         }
312
313         return bcount;
314 }
315
316 static int idetape_output_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
317                                    unsigned int bcount)
318 {
319         struct idetape_bh *bh = pc->bh;
320         int count;
321
322         if (bcount && bh) {
323                 count = min((unsigned int)pc->b_count, (unsigned int)bcount);
324                 drive->hwif->tp_ops->output_data(drive, NULL, pc->b_data, count);
325                 bcount -= count;
326                 pc->b_data += count;
327                 pc->b_count -= count;
328                 if (!pc->b_count)
329                         pc->bh = NULL;
330         }
331
332         return bcount;
333 }
334
335 static void idetape_update_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc)
336 {
337         struct idetape_bh *bh = pc->bh;
338         unsigned int bcount = pc->xferred;
339
340         if (pc->flags & PC_FLAG_WRITING)
341                 return;
342         if (bcount) {
343                 if (bh == NULL || bcount > bh->b_size) {
344                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
345                                         __func__);
346                         return;
347                 }
348                 atomic_set(&bh->b_count, bcount);
349                 if (atomic_read(&bh->b_count) == bh->b_size)
350                         pc->bh = NULL;
351         }
352 }
353
354 /*
355  * called on each failed packet command retry to analyze the request sense. We
356  * currently do not utilize this information.
357  */
358 static void idetape_analyze_error(ide_drive_t *drive, u8 *sense)
359 {
360         idetape_tape_t *tape = drive->driver_data;
361         struct ide_atapi_pc *pc = drive->failed_pc;
362
363         tape->sense_key = sense[2] & 0xF;
364         tape->asc       = sense[12];
365         tape->ascq      = sense[13];
366
367         debug_log(DBG_ERR, "pc = %x, sense key = %x, asc = %x, ascq = %x\n",
368                  pc->c[0], tape->sense_key, tape->asc, tape->ascq);
369
370         /* Correct pc->xferred by asking the tape.       */
371         if (pc->flags & PC_FLAG_DMA_ERROR) {
372                 pc->xferred = pc->req_xfer -
373                         tape->blk_size *
374                         get_unaligned_be32(&sense[3]);
375                 idetape_update_buffers(drive, pc);
376         }
377
378         /*
379          * If error was the result of a zero-length read or write command,
380          * with sense key=5, asc=0x22, ascq=0, let it slide.  Some drives
381          * (i.e. Seagate STT3401A Travan) don't support 0-length read/writes.
382          */
383         if ((pc->c[0] == READ_6 || pc->c[0] == WRITE_6)
384             /* length == 0 */
385             && pc->c[4] == 0 && pc->c[3] == 0 && pc->c[2] == 0) {
386                 if (tape->sense_key == 5) {
387                         /* don't report an error, everything's ok */
388                         pc->error = 0;
389                         /* don't retry read/write */
390                         pc->flags |= PC_FLAG_ABORT;
391                 }
392         }
393         if (pc->c[0] == READ_6 && (sense[2] & 0x80)) {
394                 pc->error = IDE_DRV_ERROR_FILEMARK;
395                 pc->flags |= PC_FLAG_ABORT;
396         }
397         if (pc->c[0] == WRITE_6) {
398                 if ((sense[2] & 0x40) || (tape->sense_key == 0xd
399                      && tape->asc == 0x0 && tape->ascq == 0x2)) {
400                         pc->error = IDE_DRV_ERROR_EOD;
401                         pc->flags |= PC_FLAG_ABORT;
402                 }
403         }
404         if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
405                 if (tape->sense_key == 8) {
406                         pc->error = IDE_DRV_ERROR_EOD;
407                         pc->flags |= PC_FLAG_ABORT;
408                 }
409                 if (!(pc->flags & PC_FLAG_ABORT) &&
410                     pc->xferred)
411                         pc->retries = IDETAPE_MAX_PC_RETRIES + 1;
412         }
413 }
414
415 /* Free data buffers completely. */
416 static void ide_tape_kfree_buffer(idetape_tape_t *tape)
417 {
418         struct idetape_bh *bh = tape->merge_bh;
419
420         kfree(bh->b_data);
421         kfree(bh);
422 }
423
424 static void ide_tape_handle_dsc(ide_drive_t *);
425
426 static int ide_tape_callback(ide_drive_t *drive, int dsc)
427 {
428         idetape_tape_t *tape = drive->driver_data;
429         struct ide_atapi_pc *pc = drive->pc;
430         struct request *rq = drive->hwif->rq;
431         int uptodate = pc->error ? 0 : 1;
432         int err = uptodate ? 0 : IDE_DRV_ERROR_GENERAL;
433
434         debug_log(DBG_PROCS, "Enter %s\n", __func__);
435
436         if (dsc)
437                 ide_tape_handle_dsc(drive);
438
439         if (drive->failed_pc == pc)
440                 drive->failed_pc = NULL;
441
442         if (pc->c[0] == REQUEST_SENSE) {
443                 if (uptodate)
444                         idetape_analyze_error(drive, pc->buf);
445                 else
446                         printk(KERN_ERR "ide-tape: Error in REQUEST SENSE "
447                                         "itself - Aborting request!\n");
448         } else if (pc->c[0] == READ_6 || pc->c[0] == WRITE_6) {
449                 int blocks = pc->xferred / tape->blk_size;
450
451                 tape->avg_size += blocks * tape->blk_size;
452
453                 if (time_after_eq(jiffies, tape->avg_time + HZ)) {
454                         tape->avg_speed = tape->avg_size * HZ /
455                                 (jiffies - tape->avg_time) / 1024;
456                         tape->avg_size = 0;
457                         tape->avg_time = jiffies;
458                 }
459
460                 tape->first_frame += blocks;
461                 rq->current_nr_sectors -= blocks;
462
463                 if (pc->error) {
464                         uptodate = 0;
465                         err = pc->error;
466                 }
467         } else if (pc->c[0] == READ_POSITION && uptodate) {
468                 u8 *readpos = pc->buf;
469
470                 debug_log(DBG_SENSE, "BOP - %s\n",
471                                 (readpos[0] & 0x80) ? "Yes" : "No");
472                 debug_log(DBG_SENSE, "EOP - %s\n",
473                                 (readpos[0] & 0x40) ? "Yes" : "No");
474
475                 if (readpos[0] & 0x4) {
476                         printk(KERN_INFO "ide-tape: Block location is unknown"
477                                          "to the tape\n");
478                         clear_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags);
479                         uptodate = 0;
480                         err = IDE_DRV_ERROR_GENERAL;
481                 } else {
482                         debug_log(DBG_SENSE, "Block Location - %u\n",
483                                         be32_to_cpup((__be32 *)&readpos[4]));
484
485                         tape->partition = readpos[1];
486                         tape->first_frame = be32_to_cpup((__be32 *)&readpos[4]);
487                         set_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags);
488                 }
489         }
490
491         rq->errors = err;
492
493         return uptodate;
494 }
495
496 /*
497  * Postpone the current request so that ide.c will be able to service requests
498  * from another device on the same port while we are polling for DSC.
499  */
500 static void idetape_postpone_request(ide_drive_t *drive)
501 {
502         idetape_tape_t *tape = drive->driver_data;
503
504         debug_log(DBG_PROCS, "Enter %s\n", __func__);
505
506         tape->postponed_rq = drive->hwif->rq;
507
508         ide_stall_queue(drive, tape->dsc_poll_freq);
509 }
510
511 static void ide_tape_handle_dsc(ide_drive_t *drive)
512 {
513         idetape_tape_t *tape = drive->driver_data;
514
515         /* Media access command */
516         tape->dsc_polling_start = jiffies;
517         tape->dsc_poll_freq = IDETAPE_DSC_MA_FAST;
518         tape->dsc_timeout = jiffies + IDETAPE_DSC_MA_TIMEOUT;
519         /* Allow ide.c to handle other requests */
520         idetape_postpone_request(drive);
521 }
522
523 static int ide_tape_io_buffers(ide_drive_t *drive, struct ide_atapi_pc *pc,
524                                 unsigned int bcount, int write)
525 {
526         unsigned int bleft;
527
528         if (write)
529                 bleft = idetape_output_buffers(drive, pc, bcount);
530         else
531                 bleft = idetape_input_buffers(drive, pc, bcount);
532
533         return bcount - bleft;
534 }
535
536 /*
537  * Packet Command Interface
538  *
539  * The current Packet Command is available in drive->pc, and will not change
540  * until we finish handling it. Each packet command is associated with a
541  * callback function that will be called when the command is finished.
542  *
543  * The handling will be done in three stages:
544  *
545  * 1. ide_tape_issue_pc will send the packet command to the drive, and will set
546  * the interrupt handler to ide_pc_intr.
547  *
548  * 2. On each interrupt, ide_pc_intr will be called. This step will be
549  * repeated until the device signals us that no more interrupts will be issued.
550  *
551  * 3. ATAPI Tape media access commands have immediate status with a delayed
552  * process. In case of a successful initiation of a media access packet command,
553  * the DSC bit will be set when the actual execution of the command is finished.
554  * Since the tape drive will not issue an interrupt, we have to poll for this
555  * event. In this case, we define the request as "low priority request" by
556  * setting rq_status to IDETAPE_RQ_POSTPONED, set a timer to poll for DSC and
557  * exit the driver.
558  *
559  * ide.c will then give higher priority to requests which originate from the
560  * other device, until will change rq_status to RQ_ACTIVE.
561  *
562  * 4. When the packet command is finished, it will be checked for errors.
563  *
564  * 5. In case an error was found, we queue a request sense packet command in
565  * front of the request queue and retry the operation up to
566  * IDETAPE_MAX_PC_RETRIES times.
567  *
568  * 6. In case no error was found, or we decided to give up and not to retry
569  * again, the callback function will be called and then we will handle the next
570  * request.
571  */
572
573 static ide_startstop_t ide_tape_issue_pc(ide_drive_t *drive,
574                                          struct ide_cmd *cmd,
575                                          struct ide_atapi_pc *pc)
576 {
577         idetape_tape_t *tape = drive->driver_data;
578
579         if (drive->failed_pc == NULL && pc->c[0] != REQUEST_SENSE)
580                 drive->failed_pc = pc;
581
582         /* Set the current packet command */
583         drive->pc = pc;
584
585         if (pc->retries > IDETAPE_MAX_PC_RETRIES ||
586                 (pc->flags & PC_FLAG_ABORT)) {
587                 unsigned int done = blk_rq_bytes(drive->hwif->rq);
588
589                 /*
590                  * We will "abort" retrying a packet command in case legitimate
591                  * error code was received (crossing a filemark, or end of the
592                  * media, for example).
593                  */
594                 if (!(pc->flags & PC_FLAG_ABORT)) {
595                         if (!(pc->c[0] == TEST_UNIT_READY &&
596                               tape->sense_key == 2 && tape->asc == 4 &&
597                              (tape->ascq == 1 || tape->ascq == 8))) {
598                                 printk(KERN_ERR "ide-tape: %s: I/O error, "
599                                                 "pc = %2x, key = %2x, "
600                                                 "asc = %2x, ascq = %2x\n",
601                                                 tape->name, pc->c[0],
602                                                 tape->sense_key, tape->asc,
603                                                 tape->ascq);
604                         }
605                         /* Giving up */
606                         pc->error = IDE_DRV_ERROR_GENERAL;
607                 }
608
609                 drive->failed_pc = NULL;
610                 drive->pc_callback(drive, 0);
611                 ide_complete_rq(drive, -EIO, done);
612                 return ide_stopped;
613         }
614         debug_log(DBG_SENSE, "Retry #%d, cmd = %02X\n", pc->retries, pc->c[0]);
615
616         pc->retries++;
617
618         return ide_issue_pc(drive, cmd);
619 }
620
621 /* A mode sense command is used to "sense" tape parameters. */
622 static void idetape_create_mode_sense_cmd(struct ide_atapi_pc *pc, u8 page_code)
623 {
624         ide_init_pc(pc);
625         pc->c[0] = MODE_SENSE;
626         if (page_code != IDETAPE_BLOCK_DESCRIPTOR)
627                 /* DBD = 1 - Don't return block descriptors */
628                 pc->c[1] = 8;
629         pc->c[2] = page_code;
630         /*
631          * Changed pc->c[3] to 0 (255 will at best return unused info).
632          *
633          * For SCSI this byte is defined as subpage instead of high byte
634          * of length and some IDE drives seem to interpret it this way
635          * and return an error when 255 is used.
636          */
637         pc->c[3] = 0;
638         /* We will just discard data in that case */
639         pc->c[4] = 255;
640         if (page_code == IDETAPE_BLOCK_DESCRIPTOR)
641                 pc->req_xfer = 12;
642         else if (page_code == IDETAPE_CAPABILITIES_PAGE)
643                 pc->req_xfer = 24;
644         else
645                 pc->req_xfer = 50;
646 }
647
648 static ide_startstop_t idetape_media_access_finished(ide_drive_t *drive)
649 {
650         ide_hwif_t *hwif = drive->hwif;
651         idetape_tape_t *tape = drive->driver_data;
652         struct ide_atapi_pc *pc = drive->pc;
653         u8 stat;
654
655         stat = hwif->tp_ops->read_status(hwif);
656
657         if (stat & ATA_DSC) {
658                 if (stat & ATA_ERR) {
659                         /* Error detected */
660                         if (pc->c[0] != TEST_UNIT_READY)
661                                 printk(KERN_ERR "ide-tape: %s: I/O error, ",
662                                                 tape->name);
663                         /* Retry operation */
664                         ide_retry_pc(drive);
665                         return ide_stopped;
666                 }
667                 pc->error = 0;
668         } else {
669                 pc->error = IDE_DRV_ERROR_GENERAL;
670                 drive->failed_pc = NULL;
671         }
672         drive->pc_callback(drive, 0);
673         return ide_stopped;
674 }
675
676 static void ide_tape_create_rw_cmd(idetape_tape_t *tape,
677                                    struct ide_atapi_pc *pc, struct request *rq,
678                                    u8 opcode)
679 {
680         struct idetape_bh *bh = (struct idetape_bh *)rq->special;
681         unsigned int length = rq->current_nr_sectors;
682
683         ide_init_pc(pc);
684         put_unaligned(cpu_to_be32(length), (unsigned int *) &pc->c[1]);
685         pc->c[1] = 1;
686         pc->bh = bh;
687         pc->buf = NULL;
688         pc->buf_size = length * tape->blk_size;
689         pc->req_xfer = pc->buf_size;
690         if (pc->req_xfer == tape->buffer_size)
691                 pc->flags |= PC_FLAG_DMA_OK;
692
693         if (opcode == READ_6) {
694                 pc->c[0] = READ_6;
695                 atomic_set(&bh->b_count, 0);
696         } else if (opcode == WRITE_6) {
697                 pc->c[0] = WRITE_6;
698                 pc->flags |= PC_FLAG_WRITING;
699                 pc->b_data = bh->b_data;
700                 pc->b_count = atomic_read(&bh->b_count);
701         }
702
703         memcpy(rq->cmd, pc->c, 12);
704 }
705
706 static ide_startstop_t idetape_do_request(ide_drive_t *drive,
707                                           struct request *rq, sector_t block)
708 {
709         ide_hwif_t *hwif = drive->hwif;
710         idetape_tape_t *tape = drive->driver_data;
711         struct ide_atapi_pc *pc = NULL;
712         struct request *postponed_rq = tape->postponed_rq;
713         struct ide_cmd cmd;
714         u8 stat;
715
716         debug_log(DBG_SENSE, "sector: %llu, nr_sectors: %lu,"
717                         " current_nr_sectors: %u\n",
718                         (unsigned long long)rq->sector, rq->nr_sectors,
719                         rq->current_nr_sectors);
720
721         if (!(blk_special_request(rq) || blk_sense_request(rq))) {
722                 /* We do not support buffer cache originated requests. */
723                 printk(KERN_NOTICE "ide-tape: %s: Unsupported request in "
724                         "request queue (%d)\n", drive->name, rq->cmd_type);
725                 if (blk_fs_request(rq) == 0 && rq->errors == 0)
726                         rq->errors = -EIO;
727                 ide_complete_rq(drive, -EIO, ide_rq_bytes(rq));
728                 return ide_stopped;
729         }
730
731         /* Retry a failed packet command */
732         if (drive->failed_pc && drive->pc->c[0] == REQUEST_SENSE) {
733                 pc = drive->failed_pc;
734                 goto out;
735         }
736
737         if (postponed_rq != NULL)
738                 if (rq != postponed_rq) {
739                         printk(KERN_ERR "ide-tape: ide-tape.c bug - "
740                                         "Two DSC requests were queued\n");
741                         drive->failed_pc = NULL;
742                         rq->errors = 0;
743                         ide_complete_rq(drive, 0, blk_rq_bytes(rq));
744                         return ide_stopped;
745                 }
746
747         tape->postponed_rq = NULL;
748
749         /*
750          * If the tape is still busy, postpone our request and service
751          * the other device meanwhile.
752          */
753         stat = hwif->tp_ops->read_status(hwif);
754
755         if ((drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) == 0 &&
756             (rq->cmd[13] & REQ_IDETAPE_PC2) == 0)
757                 set_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags);
758
759         if (drive->dev_flags & IDE_DFLAG_POST_RESET) {
760                 set_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags);
761                 drive->dev_flags &= ~IDE_DFLAG_POST_RESET;
762         }
763
764         if (!test_and_clear_bit(IDE_AFLAG_IGNORE_DSC, &drive->atapi_flags) &&
765             (stat & ATA_DSC) == 0) {
766                 if (postponed_rq == NULL) {
767                         tape->dsc_polling_start = jiffies;
768                         tape->dsc_poll_freq = tape->best_dsc_rw_freq;
769                         tape->dsc_timeout = jiffies + IDETAPE_DSC_RW_TIMEOUT;
770                 } else if (time_after(jiffies, tape->dsc_timeout)) {
771                         printk(KERN_ERR "ide-tape: %s: DSC timeout\n",
772                                 tape->name);
773                         if (rq->cmd[13] & REQ_IDETAPE_PC2) {
774                                 idetape_media_access_finished(drive);
775                                 return ide_stopped;
776                         } else {
777                                 return ide_do_reset(drive);
778                         }
779                 } else if (time_after(jiffies,
780                                         tape->dsc_polling_start +
781                                         IDETAPE_DSC_MA_THRESHOLD))
782                         tape->dsc_poll_freq = IDETAPE_DSC_MA_SLOW;
783                 idetape_postpone_request(drive);
784                 return ide_stopped;
785         }
786         if (rq->cmd[13] & REQ_IDETAPE_READ) {
787                 pc = &tape->queued_pc;
788                 ide_tape_create_rw_cmd(tape, pc, rq, READ_6);
789                 goto out;
790         }
791         if (rq->cmd[13] & REQ_IDETAPE_WRITE) {
792                 pc = &tape->queued_pc;
793                 ide_tape_create_rw_cmd(tape, pc, rq, WRITE_6);
794                 goto out;
795         }
796         if (rq->cmd[13] & REQ_IDETAPE_PC1) {
797                 pc = (struct ide_atapi_pc *)rq->special;
798                 rq->cmd[13] &= ~(REQ_IDETAPE_PC1);
799                 rq->cmd[13] |= REQ_IDETAPE_PC2;
800                 goto out;
801         }
802         if (rq->cmd[13] & REQ_IDETAPE_PC2) {
803                 idetape_media_access_finished(drive);
804                 return ide_stopped;
805         }
806         BUG();
807
808 out:
809         /* prepare sense request for this command */
810         ide_prep_sense(drive, rq);
811
812         memset(&cmd, 0, sizeof(cmd));
813
814         if (rq_data_dir(rq))
815                 cmd.tf_flags |= IDE_TFLAG_WRITE;
816
817         cmd.rq = rq;
818
819         ide_init_sg_cmd(&cmd, pc->req_xfer);
820         ide_map_sg(drive, &cmd);
821
822         return ide_tape_issue_pc(drive, &cmd, pc);
823 }
824
825 /*
826  * It returns a pointer to the newly allocated buffer, or NULL in case
827  * of failure.
828  */
829 static struct idetape_bh *ide_tape_kmalloc_buffer(idetape_tape_t *tape,
830                                                   int full)
831 {
832         struct idetape_bh *bh;
833
834         bh = kmalloc(sizeof(struct idetape_bh), GFP_KERNEL);
835         if (!bh)
836                 return NULL;
837
838         bh->b_data = kmalloc(tape->buffer_size, GFP_KERNEL);
839         if (!bh->b_data) {
840                 kfree(bh);
841                 return NULL;
842         }
843
844         bh->b_size = tape->buffer_size;
845         atomic_set(&bh->b_count, full ? bh->b_size : 0);
846
847         return bh;
848 }
849
850 static int idetape_copy_stage_from_user(idetape_tape_t *tape,
851                                         const char __user *buf, int n)
852 {
853         struct idetape_bh *bh = tape->bh;
854         int ret = 0;
855
856         if (n) {
857                 if (bh == NULL || n > bh->b_size - atomic_read(&bh->b_count)) {
858                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
859                                         __func__);
860                         return 1;
861                 }
862                 if (copy_from_user(bh->b_data + atomic_read(&bh->b_count), buf,
863                                    n))
864                         ret = 1;
865                 atomic_add(n, &bh->b_count);
866                 if (atomic_read(&bh->b_count) == bh->b_size)
867                         tape->bh = NULL;
868         }
869
870         return ret;
871 }
872
873 static int idetape_copy_stage_to_user(idetape_tape_t *tape, char __user *buf,
874                                       int n)
875 {
876         struct idetape_bh *bh = tape->bh;
877         int ret = 0;
878
879         if (n) {
880                 if (bh == NULL || n > tape->b_count) {
881                         printk(KERN_ERR "ide-tape: bh == NULL in %s\n",
882                                         __func__);
883                         return 1;
884                 }
885                 if (copy_to_user(buf, tape->b_data, n))
886                         ret = 1;
887                 tape->b_data += n;
888                 tape->b_count -= n;
889                 if (!tape->b_count)
890                         tape->bh = NULL;
891         }
892         return ret;
893 }
894
895 static void idetape_init_merge_buffer(idetape_tape_t *tape)
896 {
897         struct idetape_bh *bh = tape->merge_bh;
898         tape->bh = tape->merge_bh;
899
900         if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
901                 atomic_set(&bh->b_count, 0);
902         else {
903                 tape->b_data = bh->b_data;
904                 tape->b_count = atomic_read(&bh->b_count);
905         }
906 }
907
908 /*
909  * Write a filemark if write_filemark=1. Flush the device buffers without
910  * writing a filemark otherwise.
911  */
912 static void idetape_create_write_filemark_cmd(ide_drive_t *drive,
913                 struct ide_atapi_pc *pc, int write_filemark)
914 {
915         ide_init_pc(pc);
916         pc->c[0] = WRITE_FILEMARKS;
917         pc->c[4] = write_filemark;
918         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
919 }
920
921 static int idetape_wait_ready(ide_drive_t *drive, unsigned long timeout)
922 {
923         idetape_tape_t *tape = drive->driver_data;
924         struct gendisk *disk = tape->disk;
925         int load_attempted = 0;
926
927         /* Wait for the tape to become ready */
928         set_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags);
929         timeout += jiffies;
930         while (time_before(jiffies, timeout)) {
931                 if (ide_do_test_unit_ready(drive, disk) == 0)
932                         return 0;
933                 if ((tape->sense_key == 2 && tape->asc == 4 && tape->ascq == 2)
934                     || (tape->asc == 0x3A)) {
935                         /* no media */
936                         if (load_attempted)
937                                 return -ENOMEDIUM;
938                         ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
939                         load_attempted = 1;
940                 /* not about to be ready */
941                 } else if (!(tape->sense_key == 2 && tape->asc == 4 &&
942                              (tape->ascq == 1 || tape->ascq == 8)))
943                         return -EIO;
944                 msleep(100);
945         }
946         return -EIO;
947 }
948
949 static int idetape_flush_tape_buffers(ide_drive_t *drive)
950 {
951         struct ide_tape_obj *tape = drive->driver_data;
952         struct ide_atapi_pc pc;
953         int rc;
954
955         idetape_create_write_filemark_cmd(drive, &pc, 0);
956         rc = ide_queue_pc_tail(drive, tape->disk, &pc);
957         if (rc)
958                 return rc;
959         idetape_wait_ready(drive, 60 * 5 * HZ);
960         return 0;
961 }
962
963 static void idetape_create_read_position_cmd(struct ide_atapi_pc *pc)
964 {
965         ide_init_pc(pc);
966         pc->c[0] = READ_POSITION;
967         pc->req_xfer = 20;
968 }
969
970 static int idetape_read_position(ide_drive_t *drive)
971 {
972         idetape_tape_t *tape = drive->driver_data;
973         struct ide_atapi_pc pc;
974         int position;
975
976         debug_log(DBG_PROCS, "Enter %s\n", __func__);
977
978         idetape_create_read_position_cmd(&pc);
979         if (ide_queue_pc_tail(drive, tape->disk, &pc))
980                 return -1;
981         position = tape->first_frame;
982         return position;
983 }
984
985 static void idetape_create_locate_cmd(ide_drive_t *drive,
986                 struct ide_atapi_pc *pc,
987                 unsigned int block, u8 partition, int skip)
988 {
989         ide_init_pc(pc);
990         pc->c[0] = POSITION_TO_ELEMENT;
991         pc->c[1] = 2;
992         put_unaligned(cpu_to_be32(block), (unsigned int *) &pc->c[3]);
993         pc->c[8] = partition;
994         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
995 }
996
997 static void __ide_tape_discard_merge_buffer(ide_drive_t *drive)
998 {
999         idetape_tape_t *tape = drive->driver_data;
1000
1001         if (tape->chrdev_dir != IDETAPE_DIR_READ)
1002                 return;
1003
1004         clear_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags);
1005         tape->merge_bh_size = 0;
1006         if (tape->merge_bh != NULL) {
1007                 ide_tape_kfree_buffer(tape);
1008                 tape->merge_bh = NULL;
1009         }
1010
1011         tape->chrdev_dir = IDETAPE_DIR_NONE;
1012 }
1013
1014 /*
1015  * Position the tape to the requested block using the LOCATE packet command.
1016  * A READ POSITION command is then issued to check where we are positioned. Like
1017  * all higher level operations, we queue the commands at the tail of the request
1018  * queue and wait for their completion.
1019  */
1020 static int idetape_position_tape(ide_drive_t *drive, unsigned int block,
1021                 u8 partition, int skip)
1022 {
1023         idetape_tape_t *tape = drive->driver_data;
1024         struct gendisk *disk = tape->disk;
1025         int retval;
1026         struct ide_atapi_pc pc;
1027
1028         if (tape->chrdev_dir == IDETAPE_DIR_READ)
1029                 __ide_tape_discard_merge_buffer(drive);
1030         idetape_wait_ready(drive, 60 * 5 * HZ);
1031         idetape_create_locate_cmd(drive, &pc, block, partition, skip);
1032         retval = ide_queue_pc_tail(drive, disk, &pc);
1033         if (retval)
1034                 return (retval);
1035
1036         idetape_create_read_position_cmd(&pc);
1037         return ide_queue_pc_tail(drive, disk, &pc);
1038 }
1039
1040 static void ide_tape_discard_merge_buffer(ide_drive_t *drive,
1041                                           int restore_position)
1042 {
1043         idetape_tape_t *tape = drive->driver_data;
1044         int seek, position;
1045
1046         __ide_tape_discard_merge_buffer(drive);
1047         if (restore_position) {
1048                 position = idetape_read_position(drive);
1049                 seek = position > 0 ? position : 0;
1050                 if (idetape_position_tape(drive, seek, 0, 0)) {
1051                         printk(KERN_INFO "ide-tape: %s: position_tape failed in"
1052                                          " %s\n", tape->name, __func__);
1053                         return;
1054                 }
1055         }
1056 }
1057
1058 /*
1059  * Generate a read/write request for the block device interface and wait for it
1060  * to be serviced.
1061  */
1062 static int idetape_queue_rw_tail(ide_drive_t *drive, int cmd, int blocks,
1063                                  struct idetape_bh *bh)
1064 {
1065         idetape_tape_t *tape = drive->driver_data;
1066         struct request *rq;
1067         int ret, errors;
1068
1069         debug_log(DBG_SENSE, "%s: cmd=%d\n", __func__, cmd);
1070
1071         rq = blk_get_request(drive->queue, READ, __GFP_WAIT);
1072         rq->cmd_type = REQ_TYPE_SPECIAL;
1073         rq->cmd[13] = cmd;
1074         rq->rq_disk = tape->disk;
1075         rq->special = (void *)bh;
1076         rq->sector = tape->first_frame;
1077         rq->nr_sectors = blocks;
1078         rq->current_nr_sectors = blocks;
1079         blk_execute_rq(drive->queue, tape->disk, rq, 0);
1080
1081         errors = rq->errors;
1082         ret = tape->blk_size * (blocks - rq->current_nr_sectors);
1083         blk_put_request(rq);
1084
1085         if ((cmd & (REQ_IDETAPE_READ | REQ_IDETAPE_WRITE)) == 0)
1086                 return 0;
1087
1088         if (tape->merge_bh)
1089                 idetape_init_merge_buffer(tape);
1090         if (errors == IDE_DRV_ERROR_GENERAL)
1091                 return -EIO;
1092         return ret;
1093 }
1094
1095 static void idetape_create_inquiry_cmd(struct ide_atapi_pc *pc)
1096 {
1097         ide_init_pc(pc);
1098         pc->c[0] = INQUIRY;
1099         pc->c[4] = 254;
1100         pc->req_xfer = 254;
1101 }
1102
1103 static void idetape_create_rewind_cmd(ide_drive_t *drive,
1104                 struct ide_atapi_pc *pc)
1105 {
1106         ide_init_pc(pc);
1107         pc->c[0] = REZERO_UNIT;
1108         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1109 }
1110
1111 static void idetape_create_erase_cmd(struct ide_atapi_pc *pc)
1112 {
1113         ide_init_pc(pc);
1114         pc->c[0] = ERASE;
1115         pc->c[1] = 1;
1116         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1117 }
1118
1119 static void idetape_create_space_cmd(struct ide_atapi_pc *pc, int count, u8 cmd)
1120 {
1121         ide_init_pc(pc);
1122         pc->c[0] = SPACE;
1123         put_unaligned(cpu_to_be32(count), (unsigned int *) &pc->c[1]);
1124         pc->c[1] = cmd;
1125         pc->flags |= PC_FLAG_WAIT_FOR_DSC;
1126 }
1127
1128 /* Queue up a character device originated write request. */
1129 static int idetape_add_chrdev_write_request(ide_drive_t *drive, int blocks)
1130 {
1131         idetape_tape_t *tape = drive->driver_data;
1132
1133         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
1134
1135         return idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE,
1136                                      blocks, tape->merge_bh);
1137 }
1138
1139 static void ide_tape_flush_merge_buffer(ide_drive_t *drive)
1140 {
1141         idetape_tape_t *tape = drive->driver_data;
1142         int blocks;
1143         struct idetape_bh *bh;
1144
1145         if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
1146                 printk(KERN_ERR "ide-tape: bug: Trying to empty merge buffer"
1147                                 " but we are not writing.\n");
1148                 return;
1149         }
1150         if (tape->merge_bh_size > tape->buffer_size) {
1151                 printk(KERN_ERR "ide-tape: bug: merge_buffer too big\n");
1152                 tape->merge_bh_size = tape->buffer_size;
1153         }
1154         if (tape->merge_bh_size) {
1155                 blocks = tape->merge_bh_size / tape->blk_size;
1156                 if (tape->merge_bh_size % tape->blk_size) {
1157                         unsigned int i = tape->blk_size -
1158                                 tape->merge_bh_size % tape->blk_size;
1159                         blocks++;
1160                         bh = tape->bh;
1161                         if (bh) {
1162                                 memset(bh->b_data + atomic_read(&bh->b_count),
1163                                        0, i);
1164                                 atomic_add(i, &bh->b_count);
1165                         } else
1166                                 printk(KERN_INFO "ide-tape: bug, bh NULL\n");
1167                 }
1168                 (void) idetape_add_chrdev_write_request(drive, blocks);
1169                 tape->merge_bh_size = 0;
1170         }
1171         if (tape->merge_bh != NULL) {
1172                 ide_tape_kfree_buffer(tape);
1173                 tape->merge_bh = NULL;
1174         }
1175         tape->chrdev_dir = IDETAPE_DIR_NONE;
1176 }
1177
1178 static int idetape_init_read(ide_drive_t *drive)
1179 {
1180         idetape_tape_t *tape = drive->driver_data;
1181         int bytes_read;
1182
1183         /* Initialize read operation */
1184         if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1185                 if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
1186                         ide_tape_flush_merge_buffer(drive);
1187                         idetape_flush_tape_buffers(drive);
1188                 }
1189                 if (tape->merge_bh || tape->merge_bh_size) {
1190                         printk(KERN_ERR "ide-tape: merge_bh_size should be"
1191                                          " 0 now\n");
1192                         tape->merge_bh_size = 0;
1193                 }
1194                 tape->merge_bh = ide_tape_kmalloc_buffer(tape, 0);
1195                 if (!tape->merge_bh)
1196                         return -ENOMEM;
1197                 tape->chrdev_dir = IDETAPE_DIR_READ;
1198
1199                 /*
1200                  * Issue a read 0 command to ensure that DSC handshake is
1201                  * switched from completion mode to buffer available mode.
1202                  * No point in issuing this if DSC overlap isn't supported, some
1203                  * drives (Seagate STT3401A) will return an error.
1204                  */
1205                 if (drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) {
1206                         bytes_read = idetape_queue_rw_tail(drive,
1207                                                         REQ_IDETAPE_READ, 0,
1208                                                         tape->merge_bh);
1209                         if (bytes_read < 0) {
1210                                 ide_tape_kfree_buffer(tape);
1211                                 tape->merge_bh = NULL;
1212                                 tape->chrdev_dir = IDETAPE_DIR_NONE;
1213                                 return bytes_read;
1214                         }
1215                 }
1216         }
1217
1218         return 0;
1219 }
1220
1221 /* called from idetape_chrdev_read() to service a chrdev read request. */
1222 static int idetape_add_chrdev_read_request(ide_drive_t *drive, int blocks)
1223 {
1224         idetape_tape_t *tape = drive->driver_data;
1225
1226         debug_log(DBG_PROCS, "Enter %s, %d blocks\n", __func__, blocks);
1227
1228         /* If we are at a filemark, return a read length of 0 */
1229         if (test_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags))
1230                 return 0;
1231
1232         idetape_init_read(drive);
1233
1234         return idetape_queue_rw_tail(drive, REQ_IDETAPE_READ, blocks,
1235                                      tape->merge_bh);
1236 }
1237
1238 static void idetape_pad_zeros(ide_drive_t *drive, int bcount)
1239 {
1240         idetape_tape_t *tape = drive->driver_data;
1241         struct idetape_bh *bh = tape->merge_bh;
1242         int blocks;
1243
1244         while (bcount) {
1245                 unsigned int count;
1246
1247                 count = min(tape->buffer_size, bcount);
1248                 bcount -= count;
1249                 blocks = count / tape->blk_size;
1250                 atomic_set(&bh->b_count, count);
1251                 memset(bh->b_data, 0, atomic_read(&bh->b_count));
1252
1253                 idetape_queue_rw_tail(drive, REQ_IDETAPE_WRITE, blocks,
1254                                       tape->merge_bh);
1255         }
1256 }
1257
1258 /*
1259  * Rewinds the tape to the Beginning Of the current Partition (BOP). We
1260  * currently support only one partition.
1261  */
1262 static int idetape_rewind_tape(ide_drive_t *drive)
1263 {
1264         struct ide_tape_obj *tape = drive->driver_data;
1265         struct gendisk *disk = tape->disk;
1266         int retval;
1267         struct ide_atapi_pc pc;
1268
1269         debug_log(DBG_SENSE, "Enter %s\n", __func__);
1270
1271         idetape_create_rewind_cmd(drive, &pc);
1272         retval = ide_queue_pc_tail(drive, disk, &pc);
1273         if (retval)
1274                 return retval;
1275
1276         idetape_create_read_position_cmd(&pc);
1277         retval = ide_queue_pc_tail(drive, disk, &pc);
1278         if (retval)
1279                 return retval;
1280         return 0;
1281 }
1282
1283 /* mtio.h compatible commands should be issued to the chrdev interface. */
1284 static int idetape_blkdev_ioctl(ide_drive_t *drive, unsigned int cmd,
1285                                 unsigned long arg)
1286 {
1287         idetape_tape_t *tape = drive->driver_data;
1288         void __user *argp = (void __user *)arg;
1289
1290         struct idetape_config {
1291                 int dsc_rw_frequency;
1292                 int dsc_media_access_frequency;
1293                 int nr_stages;
1294         } config;
1295
1296         debug_log(DBG_PROCS, "Enter %s\n", __func__);
1297
1298         switch (cmd) {
1299         case 0x0340:
1300                 if (copy_from_user(&config, argp, sizeof(config)))
1301                         return -EFAULT;
1302                 tape->best_dsc_rw_freq = config.dsc_rw_frequency;
1303                 break;
1304         case 0x0350:
1305                 config.dsc_rw_frequency = (int) tape->best_dsc_rw_freq;
1306                 config.nr_stages = 1;
1307                 if (copy_to_user(argp, &config, sizeof(config)))
1308                         return -EFAULT;
1309                 break;
1310         default:
1311                 return -EIO;
1312         }
1313         return 0;
1314 }
1315
1316 static int idetape_space_over_filemarks(ide_drive_t *drive, short mt_op,
1317                                         int mt_count)
1318 {
1319         idetape_tape_t *tape = drive->driver_data;
1320         struct gendisk *disk = tape->disk;
1321         struct ide_atapi_pc pc;
1322         int retval, count = 0;
1323         int sprev = !!(tape->caps[4] & 0x20);
1324
1325         if (mt_count == 0)
1326                 return 0;
1327         if (MTBSF == mt_op || MTBSFM == mt_op) {
1328                 if (!sprev)
1329                         return -EIO;
1330                 mt_count = -mt_count;
1331         }
1332
1333         if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1334                 tape->merge_bh_size = 0;
1335                 if (test_and_clear_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags))
1336                         ++count;
1337                 ide_tape_discard_merge_buffer(drive, 0);
1338         }
1339
1340         switch (mt_op) {
1341         case MTFSF:
1342         case MTBSF:
1343                 idetape_create_space_cmd(&pc, mt_count - count,
1344                                          IDETAPE_SPACE_OVER_FILEMARK);
1345                 return ide_queue_pc_tail(drive, disk, &pc);
1346         case MTFSFM:
1347         case MTBSFM:
1348                 if (!sprev)
1349                         return -EIO;
1350                 retval = idetape_space_over_filemarks(drive, MTFSF,
1351                                                       mt_count - count);
1352                 if (retval)
1353                         return retval;
1354                 count = (MTBSFM == mt_op ? 1 : -1);
1355                 return idetape_space_over_filemarks(drive, MTFSF, count);
1356         default:
1357                 printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1358                                 mt_op);
1359                 return -EIO;
1360         }
1361 }
1362
1363 /*
1364  * Our character device read / write functions.
1365  *
1366  * The tape is optimized to maximize throughput when it is transferring an
1367  * integral number of the "continuous transfer limit", which is a parameter of
1368  * the specific tape (26kB on my particular tape, 32kB for Onstream).
1369  *
1370  * As of version 1.3 of the driver, the character device provides an abstract
1371  * continuous view of the media - any mix of block sizes (even 1 byte) on the
1372  * same backup/restore procedure is supported. The driver will internally
1373  * convert the requests to the recommended transfer unit, so that an unmatch
1374  * between the user's block size to the recommended size will only result in a
1375  * (slightly) increased driver overhead, but will no longer hit performance.
1376  * This is not applicable to Onstream.
1377  */
1378 static ssize_t idetape_chrdev_read(struct file *file, char __user *buf,
1379                                    size_t count, loff_t *ppos)
1380 {
1381         struct ide_tape_obj *tape = file->private_data;
1382         ide_drive_t *drive = tape->drive;
1383         ssize_t bytes_read, temp, actually_read = 0, rc;
1384         ssize_t ret = 0;
1385         u16 ctl = *(u16 *)&tape->caps[12];
1386
1387         debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
1388
1389         if (tape->chrdev_dir != IDETAPE_DIR_READ) {
1390                 if (test_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags))
1391                         if (count > tape->blk_size &&
1392                             (count % tape->blk_size) == 0)
1393                                 tape->user_bs_factor = count / tape->blk_size;
1394         }
1395         rc = idetape_init_read(drive);
1396         if (rc < 0)
1397                 return rc;
1398         if (count == 0)
1399                 return (0);
1400         if (tape->merge_bh_size) {
1401                 actually_read = min((unsigned int)(tape->merge_bh_size),
1402                                     (unsigned int)count);
1403                 if (idetape_copy_stage_to_user(tape, buf, actually_read))
1404                         ret = -EFAULT;
1405                 buf += actually_read;
1406                 tape->merge_bh_size -= actually_read;
1407                 count -= actually_read;
1408         }
1409         while (count >= tape->buffer_size) {
1410                 bytes_read = idetape_add_chrdev_read_request(drive, ctl);
1411                 if (bytes_read <= 0)
1412                         goto finish;
1413                 if (idetape_copy_stage_to_user(tape, buf, bytes_read))
1414                         ret = -EFAULT;
1415                 buf += bytes_read;
1416                 count -= bytes_read;
1417                 actually_read += bytes_read;
1418         }
1419         if (count) {
1420                 bytes_read = idetape_add_chrdev_read_request(drive, ctl);
1421                 if (bytes_read <= 0)
1422                         goto finish;
1423                 temp = min((unsigned long)count, (unsigned long)bytes_read);
1424                 if (idetape_copy_stage_to_user(tape, buf, temp))
1425                         ret = -EFAULT;
1426                 actually_read += temp;
1427                 tape->merge_bh_size = bytes_read-temp;
1428         }
1429 finish:
1430         if (!actually_read && test_bit(IDE_AFLAG_FILEMARK, &drive->atapi_flags)) {
1431                 debug_log(DBG_SENSE, "%s: spacing over filemark\n", tape->name);
1432
1433                 idetape_space_over_filemarks(drive, MTFSF, 1);
1434                 return 0;
1435         }
1436
1437         return ret ? ret : actually_read;
1438 }
1439
1440 static ssize_t idetape_chrdev_write(struct file *file, const char __user *buf,
1441                                      size_t count, loff_t *ppos)
1442 {
1443         struct ide_tape_obj *tape = file->private_data;
1444         ide_drive_t *drive = tape->drive;
1445         ssize_t actually_written = 0;
1446         ssize_t ret = 0;
1447         u16 ctl = *(u16 *)&tape->caps[12];
1448
1449         /* The drive is write protected. */
1450         if (tape->write_prot)
1451                 return -EACCES;
1452
1453         debug_log(DBG_CHRDEV, "Enter %s, count %Zd\n", __func__, count);
1454
1455         /* Initialize write operation */
1456         if (tape->chrdev_dir != IDETAPE_DIR_WRITE) {
1457                 if (tape->chrdev_dir == IDETAPE_DIR_READ)
1458                         ide_tape_discard_merge_buffer(drive, 1);
1459                 if (tape->merge_bh || tape->merge_bh_size) {
1460                         printk(KERN_ERR "ide-tape: merge_bh_size "
1461                                 "should be 0 now\n");
1462                         tape->merge_bh_size = 0;
1463                 }
1464                 tape->merge_bh = ide_tape_kmalloc_buffer(tape, 0);
1465                 if (!tape->merge_bh)
1466                         return -ENOMEM;
1467                 tape->chrdev_dir = IDETAPE_DIR_WRITE;
1468                 idetape_init_merge_buffer(tape);
1469
1470                 /*
1471                  * Issue a write 0 command to ensure that DSC handshake is
1472                  * switched from completion mode to buffer available mode. No
1473                  * point in issuing this if DSC overlap isn't supported, some
1474                  * drives (Seagate STT3401A) will return an error.
1475                  */
1476                 if (drive->dev_flags & IDE_DFLAG_DSC_OVERLAP) {
1477                         ssize_t retval = idetape_queue_rw_tail(drive,
1478                                                         REQ_IDETAPE_WRITE, 0,
1479                                                         tape->merge_bh);
1480                         if (retval < 0) {
1481                                 ide_tape_kfree_buffer(tape);
1482                                 tape->merge_bh = NULL;
1483                                 tape->chrdev_dir = IDETAPE_DIR_NONE;
1484                                 return retval;
1485                         }
1486                 }
1487         }
1488         if (count == 0)
1489                 return (0);
1490         if (tape->merge_bh_size) {
1491                 if (tape->merge_bh_size >= tape->buffer_size) {
1492                         printk(KERN_ERR "ide-tape: bug: merge buf too big\n");
1493                         tape->merge_bh_size = 0;
1494                 }
1495                 actually_written = min((unsigned int)
1496                                 (tape->buffer_size - tape->merge_bh_size),
1497                                 (unsigned int)count);
1498                 if (idetape_copy_stage_from_user(tape, buf, actually_written))
1499                                 ret = -EFAULT;
1500                 buf += actually_written;
1501                 tape->merge_bh_size += actually_written;
1502                 count -= actually_written;
1503
1504                 if (tape->merge_bh_size == tape->buffer_size) {
1505                         ssize_t retval;
1506                         tape->merge_bh_size = 0;
1507                         retval = idetape_add_chrdev_write_request(drive, ctl);
1508                         if (retval <= 0)
1509                                 return (retval);
1510                 }
1511         }
1512         while (count >= tape->buffer_size) {
1513                 ssize_t retval;
1514                 if (idetape_copy_stage_from_user(tape, buf, tape->buffer_size))
1515                         ret = -EFAULT;
1516                 buf += tape->buffer_size;
1517                 count -= tape->buffer_size;
1518                 retval = idetape_add_chrdev_write_request(drive, ctl);
1519                 actually_written += tape->buffer_size;
1520                 if (retval <= 0)
1521                         return (retval);
1522         }
1523         if (count) {
1524                 actually_written += count;
1525                 if (idetape_copy_stage_from_user(tape, buf, count))
1526                         ret = -EFAULT;
1527                 tape->merge_bh_size += count;
1528         }
1529         return ret ? ret : actually_written;
1530 }
1531
1532 static int idetape_write_filemark(ide_drive_t *drive)
1533 {
1534         struct ide_tape_obj *tape = drive->driver_data;
1535         struct ide_atapi_pc pc;
1536
1537         /* Write a filemark */
1538         idetape_create_write_filemark_cmd(drive, &pc, 1);
1539         if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1540                 printk(KERN_ERR "ide-tape: Couldn't write a filemark\n");
1541                 return -EIO;
1542         }
1543         return 0;
1544 }
1545
1546 /*
1547  * Called from idetape_chrdev_ioctl when the general mtio MTIOCTOP ioctl is
1548  * requested.
1549  *
1550  * Note: MTBSF and MTBSFM are not supported when the tape doesn't support
1551  * spacing over filemarks in the reverse direction. In this case, MTFSFM is also
1552  * usually not supported.
1553  *
1554  * The following commands are currently not supported:
1555  *
1556  * MTFSS, MTBSS, MTWSM, MTSETDENSITY, MTSETDRVBUFFER, MT_ST_BOOLEANS,
1557  * MT_ST_WRITE_THRESHOLD.
1558  */
1559 static int idetape_mtioctop(ide_drive_t *drive, short mt_op, int mt_count)
1560 {
1561         idetape_tape_t *tape = drive->driver_data;
1562         struct gendisk *disk = tape->disk;
1563         struct ide_atapi_pc pc;
1564         int i, retval;
1565
1566         debug_log(DBG_ERR, "Handling MTIOCTOP ioctl: mt_op=%d, mt_count=%d\n",
1567                         mt_op, mt_count);
1568
1569         switch (mt_op) {
1570         case MTFSF:
1571         case MTFSFM:
1572         case MTBSF:
1573         case MTBSFM:
1574                 if (!mt_count)
1575                         return 0;
1576                 return idetape_space_over_filemarks(drive, mt_op, mt_count);
1577         default:
1578                 break;
1579         }
1580
1581         switch (mt_op) {
1582         case MTWEOF:
1583                 if (tape->write_prot)
1584                         return -EACCES;
1585                 ide_tape_discard_merge_buffer(drive, 1);
1586                 for (i = 0; i < mt_count; i++) {
1587                         retval = idetape_write_filemark(drive);
1588                         if (retval)
1589                                 return retval;
1590                 }
1591                 return 0;
1592         case MTREW:
1593                 ide_tape_discard_merge_buffer(drive, 0);
1594                 if (idetape_rewind_tape(drive))
1595                         return -EIO;
1596                 return 0;
1597         case MTLOAD:
1598                 ide_tape_discard_merge_buffer(drive, 0);
1599                 return ide_do_start_stop(drive, disk, IDETAPE_LU_LOAD_MASK);
1600         case MTUNLOAD:
1601         case MTOFFL:
1602                 /*
1603                  * If door is locked, attempt to unlock before
1604                  * attempting to eject.
1605                  */
1606                 if (tape->door_locked) {
1607                         if (!ide_set_media_lock(drive, disk, 0))
1608                                 tape->door_locked = DOOR_UNLOCKED;
1609                 }
1610                 ide_tape_discard_merge_buffer(drive, 0);
1611                 retval = ide_do_start_stop(drive, disk, !IDETAPE_LU_LOAD_MASK);
1612                 if (!retval)
1613                         clear_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags);
1614                 return retval;
1615         case MTNOP:
1616                 ide_tape_discard_merge_buffer(drive, 0);
1617                 return idetape_flush_tape_buffers(drive);
1618         case MTRETEN:
1619                 ide_tape_discard_merge_buffer(drive, 0);
1620                 return ide_do_start_stop(drive, disk,
1621                         IDETAPE_LU_RETENSION_MASK | IDETAPE_LU_LOAD_MASK);
1622         case MTEOM:
1623                 idetape_create_space_cmd(&pc, 0, IDETAPE_SPACE_TO_EOD);
1624                 return ide_queue_pc_tail(drive, disk, &pc);
1625         case MTERASE:
1626                 (void)idetape_rewind_tape(drive);
1627                 idetape_create_erase_cmd(&pc);
1628                 return ide_queue_pc_tail(drive, disk, &pc);
1629         case MTSETBLK:
1630                 if (mt_count) {
1631                         if (mt_count < tape->blk_size ||
1632                             mt_count % tape->blk_size)
1633                                 return -EIO;
1634                         tape->user_bs_factor = mt_count / tape->blk_size;
1635                         clear_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags);
1636                 } else
1637                         set_bit(IDE_AFLAG_DETECT_BS, &drive->atapi_flags);
1638                 return 0;
1639         case MTSEEK:
1640                 ide_tape_discard_merge_buffer(drive, 0);
1641                 return idetape_position_tape(drive,
1642                         mt_count * tape->user_bs_factor, tape->partition, 0);
1643         case MTSETPART:
1644                 ide_tape_discard_merge_buffer(drive, 0);
1645                 return idetape_position_tape(drive, 0, mt_count, 0);
1646         case MTFSR:
1647         case MTBSR:
1648         case MTLOCK:
1649                 retval = ide_set_media_lock(drive, disk, 1);
1650                 if (retval)
1651                         return retval;
1652                 tape->door_locked = DOOR_EXPLICITLY_LOCKED;
1653                 return 0;
1654         case MTUNLOCK:
1655                 retval = ide_set_media_lock(drive, disk, 0);
1656                 if (retval)
1657                         return retval;
1658                 tape->door_locked = DOOR_UNLOCKED;
1659                 return 0;
1660         default:
1661                 printk(KERN_ERR "ide-tape: MTIO operation %d not supported\n",
1662                                 mt_op);
1663                 return -EIO;
1664         }
1665 }
1666
1667 /*
1668  * Our character device ioctls. General mtio.h magnetic io commands are
1669  * supported here, and not in the corresponding block interface. Our own
1670  * ide-tape ioctls are supported on both interfaces.
1671  */
1672 static int idetape_chrdev_ioctl(struct inode *inode, struct file *file,
1673                                 unsigned int cmd, unsigned long arg)
1674 {
1675         struct ide_tape_obj *tape = file->private_data;
1676         ide_drive_t *drive = tape->drive;
1677         struct mtop mtop;
1678         struct mtget mtget;
1679         struct mtpos mtpos;
1680         int block_offset = 0, position = tape->first_frame;
1681         void __user *argp = (void __user *)arg;
1682
1683         debug_log(DBG_CHRDEV, "Enter %s, cmd=%u\n", __func__, cmd);
1684
1685         if (tape->chrdev_dir == IDETAPE_DIR_WRITE) {
1686                 ide_tape_flush_merge_buffer(drive);
1687                 idetape_flush_tape_buffers(drive);
1688         }
1689         if (cmd == MTIOCGET || cmd == MTIOCPOS) {
1690                 block_offset = tape->merge_bh_size /
1691                         (tape->blk_size * tape->user_bs_factor);
1692                 position = idetape_read_position(drive);
1693                 if (position < 0)
1694                         return -EIO;
1695         }
1696         switch (cmd) {
1697         case MTIOCTOP:
1698                 if (copy_from_user(&mtop, argp, sizeof(struct mtop)))
1699                         return -EFAULT;
1700                 return idetape_mtioctop(drive, mtop.mt_op, mtop.mt_count);
1701         case MTIOCGET:
1702                 memset(&mtget, 0, sizeof(struct mtget));
1703                 mtget.mt_type = MT_ISSCSI2;
1704                 mtget.mt_blkno = position / tape->user_bs_factor - block_offset;
1705                 mtget.mt_dsreg =
1706                         ((tape->blk_size * tape->user_bs_factor)
1707                          << MT_ST_BLKSIZE_SHIFT) & MT_ST_BLKSIZE_MASK;
1708
1709                 if (tape->drv_write_prot)
1710                         mtget.mt_gstat |= GMT_WR_PROT(0xffffffff);
1711
1712                 if (copy_to_user(argp, &mtget, sizeof(struct mtget)))
1713                         return -EFAULT;
1714                 return 0;
1715         case MTIOCPOS:
1716                 mtpos.mt_blkno = position / tape->user_bs_factor - block_offset;
1717                 if (copy_to_user(argp, &mtpos, sizeof(struct mtpos)))
1718                         return -EFAULT;
1719                 return 0;
1720         default:
1721                 if (tape->chrdev_dir == IDETAPE_DIR_READ)
1722                         ide_tape_discard_merge_buffer(drive, 1);
1723                 return idetape_blkdev_ioctl(drive, cmd, arg);
1724         }
1725 }
1726
1727 /*
1728  * Do a mode sense page 0 with block descriptor and if it succeeds set the tape
1729  * block size with the reported value.
1730  */
1731 static void ide_tape_get_bsize_from_bdesc(ide_drive_t *drive)
1732 {
1733         idetape_tape_t *tape = drive->driver_data;
1734         struct ide_atapi_pc pc;
1735
1736         idetape_create_mode_sense_cmd(&pc, IDETAPE_BLOCK_DESCRIPTOR);
1737         if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1738                 printk(KERN_ERR "ide-tape: Can't get block descriptor\n");
1739                 if (tape->blk_size == 0) {
1740                         printk(KERN_WARNING "ide-tape: Cannot deal with zero "
1741                                             "block size, assuming 32k\n");
1742                         tape->blk_size = 32768;
1743                 }
1744                 return;
1745         }
1746         tape->blk_size = (pc.buf[4 + 5] << 16) +
1747                                 (pc.buf[4 + 6] << 8)  +
1748                                  pc.buf[4 + 7];
1749         tape->drv_write_prot = (pc.buf[2] & 0x80) >> 7;
1750 }
1751
1752 static int idetape_chrdev_open(struct inode *inode, struct file *filp)
1753 {
1754         unsigned int minor = iminor(inode), i = minor & ~0xc0;
1755         ide_drive_t *drive;
1756         idetape_tape_t *tape;
1757         int retval;
1758
1759         if (i >= MAX_HWIFS * MAX_DRIVES)
1760                 return -ENXIO;
1761
1762         lock_kernel();
1763         tape = ide_tape_chrdev_get(i);
1764         if (!tape) {
1765                 unlock_kernel();
1766                 return -ENXIO;
1767         }
1768
1769         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
1770
1771         /*
1772          * We really want to do nonseekable_open(inode, filp); here, but some
1773          * versions of tar incorrectly call lseek on tapes and bail out if that
1774          * fails.  So we disallow pread() and pwrite(), but permit lseeks.
1775          */
1776         filp->f_mode &= ~(FMODE_PREAD | FMODE_PWRITE);
1777
1778         drive = tape->drive;
1779
1780         filp->private_data = tape;
1781
1782         if (test_and_set_bit(IDE_AFLAG_BUSY, &drive->atapi_flags)) {
1783                 retval = -EBUSY;
1784                 goto out_put_tape;
1785         }
1786
1787         retval = idetape_wait_ready(drive, 60 * HZ);
1788         if (retval) {
1789                 clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
1790                 printk(KERN_ERR "ide-tape: %s: drive not ready\n", tape->name);
1791                 goto out_put_tape;
1792         }
1793
1794         idetape_read_position(drive);
1795         if (!test_bit(IDE_AFLAG_ADDRESS_VALID, &drive->atapi_flags))
1796                 (void)idetape_rewind_tape(drive);
1797
1798         /* Read block size and write protect status from drive. */
1799         ide_tape_get_bsize_from_bdesc(drive);
1800
1801         /* Set write protect flag if device is opened as read-only. */
1802         if ((filp->f_flags & O_ACCMODE) == O_RDONLY)
1803                 tape->write_prot = 1;
1804         else
1805                 tape->write_prot = tape->drv_write_prot;
1806
1807         /* Make sure drive isn't write protected if user wants to write. */
1808         if (tape->write_prot) {
1809                 if ((filp->f_flags & O_ACCMODE) == O_WRONLY ||
1810                     (filp->f_flags & O_ACCMODE) == O_RDWR) {
1811                         clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
1812                         retval = -EROFS;
1813                         goto out_put_tape;
1814                 }
1815         }
1816
1817         /* Lock the tape drive door so user can't eject. */
1818         if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
1819                 if (!ide_set_media_lock(drive, tape->disk, 1)) {
1820                         if (tape->door_locked != DOOR_EXPLICITLY_LOCKED)
1821                                 tape->door_locked = DOOR_LOCKED;
1822                 }
1823         }
1824         unlock_kernel();
1825         return 0;
1826
1827 out_put_tape:
1828         ide_tape_put(tape);
1829         unlock_kernel();
1830         return retval;
1831 }
1832
1833 static void idetape_write_release(ide_drive_t *drive, unsigned int minor)
1834 {
1835         idetape_tape_t *tape = drive->driver_data;
1836
1837         ide_tape_flush_merge_buffer(drive);
1838         tape->merge_bh = ide_tape_kmalloc_buffer(tape, 1);
1839         if (tape->merge_bh != NULL) {
1840                 idetape_pad_zeros(drive, tape->blk_size *
1841                                 (tape->user_bs_factor - 1));
1842                 ide_tape_kfree_buffer(tape);
1843                 tape->merge_bh = NULL;
1844         }
1845         idetape_write_filemark(drive);
1846         idetape_flush_tape_buffers(drive);
1847         idetape_flush_tape_buffers(drive);
1848 }
1849
1850 static int idetape_chrdev_release(struct inode *inode, struct file *filp)
1851 {
1852         struct ide_tape_obj *tape = filp->private_data;
1853         ide_drive_t *drive = tape->drive;
1854         unsigned int minor = iminor(inode);
1855
1856         lock_kernel();
1857         tape = drive->driver_data;
1858
1859         debug_log(DBG_CHRDEV, "Enter %s\n", __func__);
1860
1861         if (tape->chrdev_dir == IDETAPE_DIR_WRITE)
1862                 idetape_write_release(drive, minor);
1863         if (tape->chrdev_dir == IDETAPE_DIR_READ) {
1864                 if (minor < 128)
1865                         ide_tape_discard_merge_buffer(drive, 1);
1866         }
1867
1868         if (minor < 128 && test_bit(IDE_AFLAG_MEDIUM_PRESENT, &drive->atapi_flags))
1869                 (void) idetape_rewind_tape(drive);
1870         if (tape->chrdev_dir == IDETAPE_DIR_NONE) {
1871                 if (tape->door_locked == DOOR_LOCKED) {
1872                         if (!ide_set_media_lock(drive, tape->disk, 0))
1873                                 tape->door_locked = DOOR_UNLOCKED;
1874                 }
1875         }
1876         clear_bit(IDE_AFLAG_BUSY, &drive->atapi_flags);
1877         ide_tape_put(tape);
1878         unlock_kernel();
1879         return 0;
1880 }
1881
1882 static void idetape_get_inquiry_results(ide_drive_t *drive)
1883 {
1884         idetape_tape_t *tape = drive->driver_data;
1885         struct ide_atapi_pc pc;
1886         u8 pc_buf[256];
1887         char fw_rev[4], vendor_id[8], product_id[16];
1888
1889         idetape_create_inquiry_cmd(&pc);
1890         pc.buf = &pc_buf[0];
1891         pc.buf_size = sizeof(pc_buf);
1892
1893         if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1894                 printk(KERN_ERR "ide-tape: %s: can't get INQUIRY results\n",
1895                                 tape->name);
1896                 return;
1897         }
1898         memcpy(vendor_id, &pc.buf[8], 8);
1899         memcpy(product_id, &pc.buf[16], 16);
1900         memcpy(fw_rev, &pc.buf[32], 4);
1901
1902         ide_fixstring(vendor_id, 8, 0);
1903         ide_fixstring(product_id, 16, 0);
1904         ide_fixstring(fw_rev, 4, 0);
1905
1906         printk(KERN_INFO "ide-tape: %s <-> %s: %.8s %.16s rev %.4s\n",
1907                         drive->name, tape->name, vendor_id, product_id, fw_rev);
1908 }
1909
1910 /*
1911  * Ask the tape about its various parameters. In particular, we will adjust our
1912  * data transfer buffer size to the recommended value as returned by the tape.
1913  */
1914 static void idetape_get_mode_sense_results(ide_drive_t *drive)
1915 {
1916         idetape_tape_t *tape = drive->driver_data;
1917         struct ide_atapi_pc pc;
1918         u8 *caps;
1919         u8 speed, max_speed;
1920
1921         idetape_create_mode_sense_cmd(&pc, IDETAPE_CAPABILITIES_PAGE);
1922         if (ide_queue_pc_tail(drive, tape->disk, &pc)) {
1923                 printk(KERN_ERR "ide-tape: Can't get tape parameters - assuming"
1924                                 " some default values\n");
1925                 tape->blk_size = 512;
1926                 put_unaligned(52,   (u16 *)&tape->caps[12]);
1927                 put_unaligned(540,  (u16 *)&tape->caps[14]);
1928                 put_unaligned(6*52, (u16 *)&tape->caps[16]);
1929                 return;
1930         }
1931         caps = pc.buf + 4 + pc.buf[3];
1932
1933         /* convert to host order and save for later use */
1934         speed = be16_to_cpup((__be16 *)&caps[14]);
1935         max_speed = be16_to_cpup((__be16 *)&caps[8]);
1936
1937         *(u16 *)&caps[8] = max_speed;
1938         *(u16 *)&caps[12] = be16_to_cpup((__be16 *)&caps[12]);
1939         *(u16 *)&caps[14] = speed;
1940         *(u16 *)&caps[16] = be16_to_cpup((__be16 *)&caps[16]);
1941
1942         if (!speed) {
1943                 printk(KERN_INFO "ide-tape: %s: invalid tape speed "
1944                                 "(assuming 650KB/sec)\n", drive->name);
1945                 *(u16 *)&caps[14] = 650;
1946         }
1947         if (!max_speed) {
1948                 printk(KERN_INFO "ide-tape: %s: invalid max_speed "
1949                                 "(assuming 650KB/sec)\n", drive->name);
1950                 *(u16 *)&caps[8] = 650;
1951         }
1952
1953         memcpy(&tape->caps, caps, 20);
1954
1955         /* device lacks locking support according to capabilities page */
1956         if ((caps[6] & 1) == 0)
1957                 drive->dev_flags &= ~IDE_DFLAG_DOORLOCKING;
1958
1959         if (caps[7] & 0x02)
1960                 tape->blk_size = 512;
1961         else if (caps[7] & 0x04)
1962                 tape->blk_size = 1024;
1963 }
1964
1965 #ifdef CONFIG_IDE_PROC_FS
1966 #define ide_tape_devset_get(name, field) \
1967 static int get_##name(ide_drive_t *drive) \
1968 { \
1969         idetape_tape_t *tape = drive->driver_data; \
1970         return tape->field; \
1971 }
1972
1973 #define ide_tape_devset_set(name, field) \
1974 static int set_##name(ide_drive_t *drive, int arg) \
1975 { \
1976         idetape_tape_t *tape = drive->driver_data; \
1977         tape->field = arg; \
1978         return 0; \
1979 }
1980
1981 #define ide_tape_devset_rw_field(_name, _field) \
1982 ide_tape_devset_get(_name, _field) \
1983 ide_tape_devset_set(_name, _field) \
1984 IDE_DEVSET(_name, DS_SYNC, get_##_name, set_##_name)
1985
1986 #define ide_tape_devset_r_field(_name, _field) \
1987 ide_tape_devset_get(_name, _field) \
1988 IDE_DEVSET(_name, 0, get_##_name, NULL)
1989
1990 static int mulf_tdsc(ide_drive_t *drive)        { return 1000; }
1991 static int divf_tdsc(ide_drive_t *drive)        { return   HZ; }
1992 static int divf_buffer(ide_drive_t *drive)      { return    2; }
1993 static int divf_buffer_size(ide_drive_t *drive) { return 1024; }
1994
1995 ide_devset_rw_flag(dsc_overlap, IDE_DFLAG_DSC_OVERLAP);
1996
1997 ide_tape_devset_rw_field(debug_mask, debug_mask);
1998 ide_tape_devset_rw_field(tdsc, best_dsc_rw_freq);
1999
2000 ide_tape_devset_r_field(avg_speed, avg_speed);
2001 ide_tape_devset_r_field(speed, caps[14]);
2002 ide_tape_devset_r_field(buffer, caps[16]);
2003 ide_tape_devset_r_field(buffer_size, buffer_size);
2004
2005 static const struct ide_proc_devset idetape_settings[] = {
2006         __IDE_PROC_DEVSET(avg_speed,    0, 0xffff, NULL, NULL),
2007         __IDE_PROC_DEVSET(buffer,       0, 0xffff, NULL, divf_buffer),
2008         __IDE_PROC_DEVSET(buffer_size,  0, 0xffff, NULL, divf_buffer_size),
2009         __IDE_PROC_DEVSET(debug_mask,   0, 0xffff, NULL, NULL),
2010         __IDE_PROC_DEVSET(dsc_overlap,  0,      1, NULL, NULL),
2011         __IDE_PROC_DEVSET(speed,        0, 0xffff, NULL, NULL),
2012         __IDE_PROC_DEVSET(tdsc,         IDETAPE_DSC_RW_MIN, IDETAPE_DSC_RW_MAX,
2013                                         mulf_tdsc, divf_tdsc),
2014         { NULL },
2015 };
2016 #endif
2017
2018 /*
2019  * The function below is called to:
2020  *
2021  * 1. Initialize our various state variables.
2022  * 2. Ask the tape for its capabilities.
2023  * 3. Allocate a buffer which will be used for data transfer. The buffer size
2024  * is chosen based on the recommendation which we received in step 2.
2025  *
2026  * Note that at this point ide.c already assigned us an irq, so that we can
2027  * queue requests here and wait for their completion.
2028  */
2029 static void idetape_setup(ide_drive_t *drive, idetape_tape_t *tape, int minor)
2030 {
2031         unsigned long t;
2032         int speed;
2033         int buffer_size;
2034         u16 *ctl = (u16 *)&tape->caps[12];
2035
2036         drive->pc_callback       = ide_tape_callback;
2037         drive->pc_update_buffers = idetape_update_buffers;
2038         drive->pc_io_buffers     = ide_tape_io_buffers;
2039
2040         drive->dev_flags |= IDE_DFLAG_DSC_OVERLAP;
2041
2042         if (drive->hwif->host_flags & IDE_HFLAG_NO_DSC) {
2043                 printk(KERN_INFO "ide-tape: %s: disabling DSC overlap\n",
2044                                  tape->name);
2045                 drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
2046         }
2047
2048         /* Seagate Travan drives do not support DSC overlap. */
2049         if (strstr((char *)&drive->id[ATA_ID_PROD], "Seagate STT3401"))
2050                 drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
2051
2052         tape->minor = minor;
2053         tape->name[0] = 'h';
2054         tape->name[1] = 't';
2055         tape->name[2] = '0' + minor;
2056         tape->chrdev_dir = IDETAPE_DIR_NONE;
2057
2058         idetape_get_inquiry_results(drive);
2059         idetape_get_mode_sense_results(drive);
2060         ide_tape_get_bsize_from_bdesc(drive);
2061         tape->user_bs_factor = 1;
2062         tape->buffer_size = *ctl * tape->blk_size;
2063         while (tape->buffer_size > 0xffff) {
2064                 printk(KERN_NOTICE "ide-tape: decreasing stage size\n");
2065                 *ctl /= 2;
2066                 tape->buffer_size = *ctl * tape->blk_size;
2067         }
2068         buffer_size = tape->buffer_size;
2069
2070         /* select the "best" DSC read/write polling freq */
2071         speed = max(*(u16 *)&tape->caps[14], *(u16 *)&tape->caps[8]);
2072
2073         t = (IDETAPE_FIFO_THRESHOLD * tape->buffer_size * HZ) / (speed * 1000);
2074
2075         /*
2076          * Ensure that the number we got makes sense; limit it within
2077          * IDETAPE_DSC_RW_MIN and IDETAPE_DSC_RW_MAX.
2078          */
2079         tape->best_dsc_rw_freq = clamp_t(unsigned long, t, IDETAPE_DSC_RW_MIN,
2080                                          IDETAPE_DSC_RW_MAX);
2081         printk(KERN_INFO "ide-tape: %s <-> %s: %dKBps, %d*%dkB buffer, "
2082                 "%lums tDSC%s\n",
2083                 drive->name, tape->name, *(u16 *)&tape->caps[14],
2084                 (*(u16 *)&tape->caps[16] * 512) / tape->buffer_size,
2085                 tape->buffer_size / 1024,
2086                 tape->best_dsc_rw_freq * 1000 / HZ,
2087                 (drive->dev_flags & IDE_DFLAG_USING_DMA) ? ", DMA" : "");
2088
2089         ide_proc_register_driver(drive, tape->driver);
2090 }
2091
2092 static void ide_tape_remove(ide_drive_t *drive)
2093 {
2094         idetape_tape_t *tape = drive->driver_data;
2095
2096         ide_proc_unregister_driver(drive, tape->driver);
2097         device_del(&tape->dev);
2098         ide_unregister_region(tape->disk);
2099
2100         mutex_lock(&idetape_ref_mutex);
2101         put_device(&tape->dev);
2102         mutex_unlock(&idetape_ref_mutex);
2103 }
2104
2105 static void ide_tape_release(struct device *dev)
2106 {
2107         struct ide_tape_obj *tape = to_ide_drv(dev, ide_tape_obj);
2108         ide_drive_t *drive = tape->drive;
2109         struct gendisk *g = tape->disk;
2110
2111         BUG_ON(tape->merge_bh_size);
2112
2113         drive->dev_flags &= ~IDE_DFLAG_DSC_OVERLAP;
2114         drive->driver_data = NULL;
2115         device_destroy(idetape_sysfs_class, MKDEV(IDETAPE_MAJOR, tape->minor));
2116         device_destroy(idetape_sysfs_class,
2117                         MKDEV(IDETAPE_MAJOR, tape->minor + 128));
2118         idetape_devs[tape->minor] = NULL;
2119         g->private_data = NULL;
2120         put_disk(g);
2121         kfree(tape);
2122 }
2123
2124 #ifdef CONFIG_IDE_PROC_FS
2125 static int proc_idetape_read_name
2126         (char *page, char **start, off_t off, int count, int *eof, void *data)
2127 {
2128         ide_drive_t     *drive = (ide_drive_t *) data;
2129         idetape_tape_t  *tape = drive->driver_data;
2130         char            *out = page;
2131         int             len;
2132
2133         len = sprintf(out, "%s\n", tape->name);
2134         PROC_IDE_READ_RETURN(page, start, off, count, eof, len);
2135 }
2136
2137 static ide_proc_entry_t idetape_proc[] = {
2138         { "capacity",   S_IFREG|S_IRUGO,        proc_ide_read_capacity, NULL },
2139         { "name",       S_IFREG|S_IRUGO,        proc_idetape_read_name, NULL },
2140         { NULL, 0, NULL, NULL }
2141 };
2142
2143 static ide_proc_entry_t *ide_tape_proc_entries(ide_drive_t *drive)
2144 {
2145         return idetape_proc;
2146 }
2147
2148 static const struct ide_proc_devset *ide_tape_proc_devsets(ide_drive_t *drive)
2149 {
2150         return idetape_settings;
2151 }
2152 #endif
2153
2154 static int ide_tape_probe(ide_drive_t *);
2155
2156 static struct ide_driver idetape_driver = {
2157         .gen_driver = {
2158                 .owner          = THIS_MODULE,
2159                 .name           = "ide-tape",
2160                 .bus            = &ide_bus_type,
2161         },
2162         .probe                  = ide_tape_probe,
2163         .remove                 = ide_tape_remove,
2164         .version                = IDETAPE_VERSION,
2165         .do_request             = idetape_do_request,
2166 #ifdef CONFIG_IDE_PROC_FS
2167         .proc_entries           = ide_tape_proc_entries,
2168         .proc_devsets           = ide_tape_proc_devsets,
2169 #endif
2170 };
2171
2172 /* Our character device supporting functions, passed to register_chrdev. */
2173 static const struct file_operations idetape_fops = {
2174         .owner          = THIS_MODULE,
2175         .read           = idetape_chrdev_read,
2176         .write          = idetape_chrdev_write,
2177         .ioctl          = idetape_chrdev_ioctl,
2178         .open           = idetape_chrdev_open,
2179         .release        = idetape_chrdev_release,
2180 };
2181
2182 static int idetape_open(struct block_device *bdev, fmode_t mode)
2183 {
2184         struct ide_tape_obj *tape = ide_tape_get(bdev->bd_disk);
2185
2186         if (!tape)
2187                 return -ENXIO;
2188
2189         return 0;
2190 }
2191
2192 static int idetape_release(struct gendisk *disk, fmode_t mode)
2193 {
2194         struct ide_tape_obj *tape = ide_drv_g(disk, ide_tape_obj);
2195
2196         ide_tape_put(tape);
2197         return 0;
2198 }
2199
2200 static int idetape_ioctl(struct block_device *bdev, fmode_t mode,
2201                         unsigned int cmd, unsigned long arg)
2202 {
2203         struct ide_tape_obj *tape = ide_drv_g(bdev->bd_disk, ide_tape_obj);
2204         ide_drive_t *drive = tape->drive;
2205         int err = generic_ide_ioctl(drive, bdev, cmd, arg);
2206         if (err == -EINVAL)
2207                 err = idetape_blkdev_ioctl(drive, cmd, arg);
2208         return err;
2209 }
2210
2211 static struct block_device_operations idetape_block_ops = {
2212         .owner          = THIS_MODULE,
2213         .open           = idetape_open,
2214         .release        = idetape_release,
2215         .locked_ioctl   = idetape_ioctl,
2216 };
2217
2218 static int ide_tape_probe(ide_drive_t *drive)
2219 {
2220         idetape_tape_t *tape;
2221         struct gendisk *g;
2222         int minor;
2223
2224         if (!strstr("ide-tape", drive->driver_req))
2225                 goto failed;
2226
2227         if (drive->media != ide_tape)
2228                 goto failed;
2229
2230         if ((drive->dev_flags & IDE_DFLAG_ID_READ) &&
2231             ide_check_atapi_device(drive, DRV_NAME) == 0) {
2232                 printk(KERN_ERR "ide-tape: %s: not supported by this version of"
2233                                 " the driver\n", drive->name);
2234                 goto failed;
2235         }
2236         tape = kzalloc(sizeof(idetape_tape_t), GFP_KERNEL);
2237         if (tape == NULL) {
2238                 printk(KERN_ERR "ide-tape: %s: Can't allocate a tape struct\n",
2239                                 drive->name);
2240                 goto failed;
2241         }
2242
2243         g = alloc_disk(1 << PARTN_BITS);
2244         if (!g)
2245                 goto out_free_tape;
2246
2247         ide_init_disk(g, drive);
2248
2249         tape->dev.parent = &drive->gendev;
2250         tape->dev.release = ide_tape_release;
2251         dev_set_name(&tape->dev, dev_name(&drive->gendev));
2252
2253         if (device_register(&tape->dev))
2254                 goto out_free_disk;
2255
2256         tape->drive = drive;
2257         tape->driver = &idetape_driver;
2258         tape->disk = g;
2259
2260         g->private_data = &tape->driver;
2261
2262         drive->driver_data = tape;
2263
2264         mutex_lock(&idetape_ref_mutex);
2265         for (minor = 0; idetape_devs[minor]; minor++)
2266                 ;
2267         idetape_devs[minor] = tape;
2268         mutex_unlock(&idetape_ref_mutex);
2269
2270         idetape_setup(drive, tape, minor);
2271
2272         device_create(idetape_sysfs_class, &drive->gendev,
2273                       MKDEV(IDETAPE_MAJOR, minor), NULL, "%s", tape->name);
2274         device_create(idetape_sysfs_class, &drive->gendev,
2275                       MKDEV(IDETAPE_MAJOR, minor + 128), NULL,
2276                       "n%s", tape->name);
2277
2278         g->fops = &idetape_block_ops;
2279         ide_register_region(g);
2280
2281         return 0;
2282
2283 out_free_disk:
2284         put_disk(g);
2285 out_free_tape:
2286         kfree(tape);
2287 failed:
2288         return -ENODEV;
2289 }
2290
2291 static void __exit idetape_exit(void)
2292 {
2293         driver_unregister(&idetape_driver.gen_driver);
2294         class_destroy(idetape_sysfs_class);
2295         unregister_chrdev(IDETAPE_MAJOR, "ht");
2296 }
2297
2298 static int __init idetape_init(void)
2299 {
2300         int error = 1;
2301         idetape_sysfs_class = class_create(THIS_MODULE, "ide_tape");
2302         if (IS_ERR(idetape_sysfs_class)) {
2303                 idetape_sysfs_class = NULL;
2304                 printk(KERN_ERR "Unable to create sysfs class for ide tapes\n");
2305                 error = -EBUSY;
2306                 goto out;
2307         }
2308
2309         if (register_chrdev(IDETAPE_MAJOR, "ht", &idetape_fops)) {
2310                 printk(KERN_ERR "ide-tape: Failed to register chrdev"
2311                                 " interface\n");
2312                 error = -EBUSY;
2313                 goto out_free_class;
2314         }
2315
2316         error = driver_register(&idetape_driver.gen_driver);
2317         if (error)
2318                 goto out_free_driver;
2319
2320         return 0;
2321
2322 out_free_driver:
2323         driver_unregister(&idetape_driver.gen_driver);
2324 out_free_class:
2325         class_destroy(idetape_sysfs_class);
2326 out:
2327         return error;
2328 }
2329
2330 MODULE_ALIAS("ide:*m-tape*");
2331 module_init(idetape_init);
2332 module_exit(idetape_exit);
2333 MODULE_ALIAS_CHARDEV_MAJOR(IDETAPE_MAJOR);
2334 MODULE_DESCRIPTION("ATAPI Streaming TAPE Driver");
2335 MODULE_LICENSE("GPL");