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