Merge master.kernel.org:/home/rmk/linux-2.6-serial
[linux-2.6] / drivers / block / pktcdvd.c
1 /*
2  * Copyright (C) 2000 Jens Axboe <axboe@suse.de>
3  * Copyright (C) 2001-2004 Peter Osterlund <petero2@telia.com>
4  *
5  * May be copied or modified under the terms of the GNU General Public
6  * License.  See linux/COPYING for more information.
7  *
8  * Packet writing layer for ATAPI and SCSI CD-RW, DVD+RW, DVD-RW and
9  * DVD-RAM devices.
10  *
11  * Theory of operation:
12  *
13  * At the lowest level, there is the standard driver for the CD/DVD device,
14  * typically ide-cd.c or sr.c. This driver can handle read and write requests,
15  * but it doesn't know anything about the special restrictions that apply to
16  * packet writing. One restriction is that write requests must be aligned to
17  * packet boundaries on the physical media, and the size of a write request
18  * must be equal to the packet size. Another restriction is that a
19  * GPCMD_FLUSH_CACHE command has to be issued to the drive before a read
20  * command, if the previous command was a write.
21  *
22  * The purpose of the packet writing driver is to hide these restrictions from
23  * higher layers, such as file systems, and present a block device that can be
24  * randomly read and written using 2kB-sized blocks.
25  *
26  * The lowest layer in the packet writing driver is the packet I/O scheduler.
27  * Its data is defined by the struct packet_iosched and includes two bio
28  * queues with pending read and write requests. These queues are processed
29  * by the pkt_iosched_process_queue() function. The write requests in this
30  * queue are already properly aligned and sized. This layer is responsible for
31  * issuing the flush cache commands and scheduling the I/O in a good order.
32  *
33  * The next layer transforms unaligned write requests to aligned writes. This
34  * transformation requires reading missing pieces of data from the underlying
35  * block device, assembling the pieces to full packets and queuing them to the
36  * packet I/O scheduler.
37  *
38  * At the top layer there is a custom make_request_fn function that forwards
39  * read requests directly to the iosched queue and puts write requests in the
40  * unaligned write queue. A kernel thread performs the necessary read
41  * gathering to convert the unaligned writes to aligned writes and then feeds
42  * them to the packet I/O scheduler.
43  *
44  *************************************************************************/
45
46 #include <linux/pktcdvd.h>
47 #include <linux/config.h>
48 #include <linux/module.h>
49 #include <linux/types.h>
50 #include <linux/kernel.h>
51 #include <linux/kthread.h>
52 #include <linux/errno.h>
53 #include <linux/spinlock.h>
54 #include <linux/file.h>
55 #include <linux/proc_fs.h>
56 #include <linux/seq_file.h>
57 #include <linux/miscdevice.h>
58 #include <linux/suspend.h>
59 #include <scsi/scsi_cmnd.h>
60 #include <scsi/scsi_ioctl.h>
61
62 #include <asm/uaccess.h>
63
64 #if PACKET_DEBUG
65 #define DPRINTK(fmt, args...) printk(KERN_NOTICE fmt, ##args)
66 #else
67 #define DPRINTK(fmt, args...)
68 #endif
69
70 #if PACKET_DEBUG > 1
71 #define VPRINTK(fmt, args...) printk(KERN_NOTICE fmt, ##args)
72 #else
73 #define VPRINTK(fmt, args...)
74 #endif
75
76 #define MAX_SPEED 0xffff
77
78 #define ZONE(sector, pd) (((sector) + (pd)->offset) & ~((pd)->settings.size - 1))
79
80 static struct pktcdvd_device *pkt_devs[MAX_WRITERS];
81 static struct proc_dir_entry *pkt_proc;
82 static int pkt_major;
83 static struct semaphore ctl_mutex;      /* Serialize open/close/setup/teardown */
84 static mempool_t *psd_pool;
85
86
87 static void pkt_bio_finished(struct pktcdvd_device *pd)
88 {
89         BUG_ON(atomic_read(&pd->cdrw.pending_bios) <= 0);
90         if (atomic_dec_and_test(&pd->cdrw.pending_bios)) {
91                 VPRINTK("pktcdvd: queue empty\n");
92                 atomic_set(&pd->iosched.attention, 1);
93                 wake_up(&pd->wqueue);
94         }
95 }
96
97 static void pkt_bio_destructor(struct bio *bio)
98 {
99         kfree(bio->bi_io_vec);
100         kfree(bio);
101 }
102
103 static struct bio *pkt_bio_alloc(int nr_iovecs)
104 {
105         struct bio_vec *bvl = NULL;
106         struct bio *bio;
107
108         bio = kmalloc(sizeof(struct bio), GFP_KERNEL);
109         if (!bio)
110                 goto no_bio;
111         bio_init(bio);
112
113         bvl = kcalloc(nr_iovecs, sizeof(struct bio_vec), GFP_KERNEL);
114         if (!bvl)
115                 goto no_bvl;
116
117         bio->bi_max_vecs = nr_iovecs;
118         bio->bi_io_vec = bvl;
119         bio->bi_destructor = pkt_bio_destructor;
120
121         return bio;
122
123  no_bvl:
124         kfree(bio);
125  no_bio:
126         return NULL;
127 }
128
129 /*
130  * Allocate a packet_data struct
131  */
132 static struct packet_data *pkt_alloc_packet_data(int frames)
133 {
134         int i;
135         struct packet_data *pkt;
136
137         pkt = kzalloc(sizeof(struct packet_data), GFP_KERNEL);
138         if (!pkt)
139                 goto no_pkt;
140
141         pkt->frames = frames;
142         pkt->w_bio = pkt_bio_alloc(frames);
143         if (!pkt->w_bio)
144                 goto no_bio;
145
146         for (i = 0; i < frames / FRAMES_PER_PAGE; i++) {
147                 pkt->pages[i] = alloc_page(GFP_KERNEL|__GFP_ZERO);
148                 if (!pkt->pages[i])
149                         goto no_page;
150         }
151
152         spin_lock_init(&pkt->lock);
153
154         for (i = 0; i < frames; i++) {
155                 struct bio *bio = pkt_bio_alloc(1);
156                 if (!bio)
157                         goto no_rd_bio;
158                 pkt->r_bios[i] = bio;
159         }
160
161         return pkt;
162
163 no_rd_bio:
164         for (i = 0; i < frames; i++) {
165                 struct bio *bio = pkt->r_bios[i];
166                 if (bio)
167                         bio_put(bio);
168         }
169
170 no_page:
171         for (i = 0; i < frames / FRAMES_PER_PAGE; i++)
172                 if (pkt->pages[i])
173                         __free_page(pkt->pages[i]);
174         bio_put(pkt->w_bio);
175 no_bio:
176         kfree(pkt);
177 no_pkt:
178         return NULL;
179 }
180
181 /*
182  * Free a packet_data struct
183  */
184 static void pkt_free_packet_data(struct packet_data *pkt)
185 {
186         int i;
187
188         for (i = 0; i < pkt->frames; i++) {
189                 struct bio *bio = pkt->r_bios[i];
190                 if (bio)
191                         bio_put(bio);
192         }
193         for (i = 0; i < pkt->frames / FRAMES_PER_PAGE; i++)
194                 __free_page(pkt->pages[i]);
195         bio_put(pkt->w_bio);
196         kfree(pkt);
197 }
198
199 static void pkt_shrink_pktlist(struct pktcdvd_device *pd)
200 {
201         struct packet_data *pkt, *next;
202
203         BUG_ON(!list_empty(&pd->cdrw.pkt_active_list));
204
205         list_for_each_entry_safe(pkt, next, &pd->cdrw.pkt_free_list, list) {
206                 pkt_free_packet_data(pkt);
207         }
208         INIT_LIST_HEAD(&pd->cdrw.pkt_free_list);
209 }
210
211 static int pkt_grow_pktlist(struct pktcdvd_device *pd, int nr_packets)
212 {
213         struct packet_data *pkt;
214
215         BUG_ON(!list_empty(&pd->cdrw.pkt_free_list));
216
217         while (nr_packets > 0) {
218                 pkt = pkt_alloc_packet_data(pd->settings.size >> 2);
219                 if (!pkt) {
220                         pkt_shrink_pktlist(pd);
221                         return 0;
222                 }
223                 pkt->id = nr_packets;
224                 pkt->pd = pd;
225                 list_add(&pkt->list, &pd->cdrw.pkt_free_list);
226                 nr_packets--;
227         }
228         return 1;
229 }
230
231 static void *pkt_rb_alloc(gfp_t gfp_mask, void *data)
232 {
233         return kmalloc(sizeof(struct pkt_rb_node), gfp_mask);
234 }
235
236 static void pkt_rb_free(void *ptr, void *data)
237 {
238         kfree(ptr);
239 }
240
241 static inline struct pkt_rb_node *pkt_rbtree_next(struct pkt_rb_node *node)
242 {
243         struct rb_node *n = rb_next(&node->rb_node);
244         if (!n)
245                 return NULL;
246         return rb_entry(n, struct pkt_rb_node, rb_node);
247 }
248
249 static void pkt_rbtree_erase(struct pktcdvd_device *pd, struct pkt_rb_node *node)
250 {
251         rb_erase(&node->rb_node, &pd->bio_queue);
252         mempool_free(node, pd->rb_pool);
253         pd->bio_queue_size--;
254         BUG_ON(pd->bio_queue_size < 0);
255 }
256
257 /*
258  * Find the first node in the pd->bio_queue rb tree with a starting sector >= s.
259  */
260 static struct pkt_rb_node *pkt_rbtree_find(struct pktcdvd_device *pd, sector_t s)
261 {
262         struct rb_node *n = pd->bio_queue.rb_node;
263         struct rb_node *next;
264         struct pkt_rb_node *tmp;
265
266         if (!n) {
267                 BUG_ON(pd->bio_queue_size > 0);
268                 return NULL;
269         }
270
271         for (;;) {
272                 tmp = rb_entry(n, struct pkt_rb_node, rb_node);
273                 if (s <= tmp->bio->bi_sector)
274                         next = n->rb_left;
275                 else
276                         next = n->rb_right;
277                 if (!next)
278                         break;
279                 n = next;
280         }
281
282         if (s > tmp->bio->bi_sector) {
283                 tmp = pkt_rbtree_next(tmp);
284                 if (!tmp)
285                         return NULL;
286         }
287         BUG_ON(s > tmp->bio->bi_sector);
288         return tmp;
289 }
290
291 /*
292  * Insert a node into the pd->bio_queue rb tree.
293  */
294 static void pkt_rbtree_insert(struct pktcdvd_device *pd, struct pkt_rb_node *node)
295 {
296         struct rb_node **p = &pd->bio_queue.rb_node;
297         struct rb_node *parent = NULL;
298         sector_t s = node->bio->bi_sector;
299         struct pkt_rb_node *tmp;
300
301         while (*p) {
302                 parent = *p;
303                 tmp = rb_entry(parent, struct pkt_rb_node, rb_node);
304                 if (s < tmp->bio->bi_sector)
305                         p = &(*p)->rb_left;
306                 else
307                         p = &(*p)->rb_right;
308         }
309         rb_link_node(&node->rb_node, parent, p);
310         rb_insert_color(&node->rb_node, &pd->bio_queue);
311         pd->bio_queue_size++;
312 }
313
314 /*
315  * Add a bio to a single linked list defined by its head and tail pointers.
316  */
317 static void pkt_add_list_last(struct bio *bio, struct bio **list_head, struct bio **list_tail)
318 {
319         bio->bi_next = NULL;
320         if (*list_tail) {
321                 BUG_ON((*list_head) == NULL);
322                 (*list_tail)->bi_next = bio;
323                 (*list_tail) = bio;
324         } else {
325                 BUG_ON((*list_head) != NULL);
326                 (*list_head) = bio;
327                 (*list_tail) = bio;
328         }
329 }
330
331 /*
332  * Remove and return the first bio from a single linked list defined by its
333  * head and tail pointers.
334  */
335 static inline struct bio *pkt_get_list_first(struct bio **list_head, struct bio **list_tail)
336 {
337         struct bio *bio;
338
339         if (*list_head == NULL)
340                 return NULL;
341
342         bio = *list_head;
343         *list_head = bio->bi_next;
344         if (*list_head == NULL)
345                 *list_tail = NULL;
346
347         bio->bi_next = NULL;
348         return bio;
349 }
350
351 /*
352  * Send a packet_command to the underlying block device and
353  * wait for completion.
354  */
355 static int pkt_generic_packet(struct pktcdvd_device *pd, struct packet_command *cgc)
356 {
357         char sense[SCSI_SENSE_BUFFERSIZE];
358         request_queue_t *q;
359         struct request *rq;
360         DECLARE_COMPLETION(wait);
361         int err = 0;
362
363         q = bdev_get_queue(pd->bdev);
364
365         rq = blk_get_request(q, (cgc->data_direction == CGC_DATA_WRITE) ? WRITE : READ,
366                              __GFP_WAIT);
367         rq->errors = 0;
368         rq->rq_disk = pd->bdev->bd_disk;
369         rq->bio = NULL;
370         rq->buffer = NULL;
371         rq->timeout = 60*HZ;
372         rq->data = cgc->buffer;
373         rq->data_len = cgc->buflen;
374         rq->sense = sense;
375         memset(sense, 0, sizeof(sense));
376         rq->sense_len = 0;
377         rq->flags |= REQ_BLOCK_PC | REQ_HARDBARRIER;
378         if (cgc->quiet)
379                 rq->flags |= REQ_QUIET;
380         memcpy(rq->cmd, cgc->cmd, CDROM_PACKET_SIZE);
381         if (sizeof(rq->cmd) > CDROM_PACKET_SIZE)
382                 memset(rq->cmd + CDROM_PACKET_SIZE, 0, sizeof(rq->cmd) - CDROM_PACKET_SIZE);
383
384         rq->ref_count++;
385         rq->flags |= REQ_NOMERGE;
386         rq->waiting = &wait;
387         rq->end_io = blk_end_sync_rq;
388         elv_add_request(q, rq, ELEVATOR_INSERT_BACK, 1);
389         generic_unplug_device(q);
390         wait_for_completion(&wait);
391
392         if (rq->errors)
393                 err = -EIO;
394
395         blk_put_request(rq);
396         return err;
397 }
398
399 /*
400  * A generic sense dump / resolve mechanism should be implemented across
401  * all ATAPI + SCSI devices.
402  */
403 static void pkt_dump_sense(struct packet_command *cgc)
404 {
405         static char *info[9] = { "No sense", "Recovered error", "Not ready",
406                                  "Medium error", "Hardware error", "Illegal request",
407                                  "Unit attention", "Data protect", "Blank check" };
408         int i;
409         struct request_sense *sense = cgc->sense;
410
411         printk("pktcdvd:");
412         for (i = 0; i < CDROM_PACKET_SIZE; i++)
413                 printk(" %02x", cgc->cmd[i]);
414         printk(" - ");
415
416         if (sense == NULL) {
417                 printk("no sense\n");
418                 return;
419         }
420
421         printk("sense %02x.%02x.%02x", sense->sense_key, sense->asc, sense->ascq);
422
423         if (sense->sense_key > 8) {
424                 printk(" (INVALID)\n");
425                 return;
426         }
427
428         printk(" (%s)\n", info[sense->sense_key]);
429 }
430
431 /*
432  * flush the drive cache to media
433  */
434 static int pkt_flush_cache(struct pktcdvd_device *pd)
435 {
436         struct packet_command cgc;
437
438         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
439         cgc.cmd[0] = GPCMD_FLUSH_CACHE;
440         cgc.quiet = 1;
441
442         /*
443          * the IMMED bit -- we default to not setting it, although that
444          * would allow a much faster close, this is safer
445          */
446 #if 0
447         cgc.cmd[1] = 1 << 1;
448 #endif
449         return pkt_generic_packet(pd, &cgc);
450 }
451
452 /*
453  * speed is given as the normal factor, e.g. 4 for 4x
454  */
455 static int pkt_set_speed(struct pktcdvd_device *pd, unsigned write_speed, unsigned read_speed)
456 {
457         struct packet_command cgc;
458         struct request_sense sense;
459         int ret;
460
461         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
462         cgc.sense = &sense;
463         cgc.cmd[0] = GPCMD_SET_SPEED;
464         cgc.cmd[2] = (read_speed >> 8) & 0xff;
465         cgc.cmd[3] = read_speed & 0xff;
466         cgc.cmd[4] = (write_speed >> 8) & 0xff;
467         cgc.cmd[5] = write_speed & 0xff;
468
469         if ((ret = pkt_generic_packet(pd, &cgc)))
470                 pkt_dump_sense(&cgc);
471
472         return ret;
473 }
474
475 /*
476  * Queue a bio for processing by the low-level CD device. Must be called
477  * from process context.
478  */
479 static void pkt_queue_bio(struct pktcdvd_device *pd, struct bio *bio)
480 {
481         spin_lock(&pd->iosched.lock);
482         if (bio_data_dir(bio) == READ) {
483                 pkt_add_list_last(bio, &pd->iosched.read_queue,
484                                   &pd->iosched.read_queue_tail);
485         } else {
486                 pkt_add_list_last(bio, &pd->iosched.write_queue,
487                                   &pd->iosched.write_queue_tail);
488         }
489         spin_unlock(&pd->iosched.lock);
490
491         atomic_set(&pd->iosched.attention, 1);
492         wake_up(&pd->wqueue);
493 }
494
495 /*
496  * Process the queued read/write requests. This function handles special
497  * requirements for CDRW drives:
498  * - A cache flush command must be inserted before a read request if the
499  *   previous request was a write.
500  * - Switching between reading and writing is slow, so don't do it more often
501  *   than necessary.
502  * - Optimize for throughput at the expense of latency. This means that streaming
503  *   writes will never be interrupted by a read, but if the drive has to seek
504  *   before the next write, switch to reading instead if there are any pending
505  *   read requests.
506  * - Set the read speed according to current usage pattern. When only reading
507  *   from the device, it's best to use the highest possible read speed, but
508  *   when switching often between reading and writing, it's better to have the
509  *   same read and write speeds.
510  */
511 static void pkt_iosched_process_queue(struct pktcdvd_device *pd)
512 {
513
514         if (atomic_read(&pd->iosched.attention) == 0)
515                 return;
516         atomic_set(&pd->iosched.attention, 0);
517
518         for (;;) {
519                 struct bio *bio;
520                 int reads_queued, writes_queued;
521
522                 spin_lock(&pd->iosched.lock);
523                 reads_queued = (pd->iosched.read_queue != NULL);
524                 writes_queued = (pd->iosched.write_queue != NULL);
525                 spin_unlock(&pd->iosched.lock);
526
527                 if (!reads_queued && !writes_queued)
528                         break;
529
530                 if (pd->iosched.writing) {
531                         int need_write_seek = 1;
532                         spin_lock(&pd->iosched.lock);
533                         bio = pd->iosched.write_queue;
534                         spin_unlock(&pd->iosched.lock);
535                         if (bio && (bio->bi_sector == pd->iosched.last_write))
536                                 need_write_seek = 0;
537                         if (need_write_seek && reads_queued) {
538                                 if (atomic_read(&pd->cdrw.pending_bios) > 0) {
539                                         VPRINTK("pktcdvd: write, waiting\n");
540                                         break;
541                                 }
542                                 pkt_flush_cache(pd);
543                                 pd->iosched.writing = 0;
544                         }
545                 } else {
546                         if (!reads_queued && writes_queued) {
547                                 if (atomic_read(&pd->cdrw.pending_bios) > 0) {
548                                         VPRINTK("pktcdvd: read, waiting\n");
549                                         break;
550                                 }
551                                 pd->iosched.writing = 1;
552                         }
553                 }
554
555                 spin_lock(&pd->iosched.lock);
556                 if (pd->iosched.writing) {
557                         bio = pkt_get_list_first(&pd->iosched.write_queue,
558                                                  &pd->iosched.write_queue_tail);
559                 } else {
560                         bio = pkt_get_list_first(&pd->iosched.read_queue,
561                                                  &pd->iosched.read_queue_tail);
562                 }
563                 spin_unlock(&pd->iosched.lock);
564
565                 if (!bio)
566                         continue;
567
568                 if (bio_data_dir(bio) == READ)
569                         pd->iosched.successive_reads += bio->bi_size >> 10;
570                 else {
571                         pd->iosched.successive_reads = 0;
572                         pd->iosched.last_write = bio->bi_sector + bio_sectors(bio);
573                 }
574                 if (pd->iosched.successive_reads >= HI_SPEED_SWITCH) {
575                         if (pd->read_speed == pd->write_speed) {
576                                 pd->read_speed = MAX_SPEED;
577                                 pkt_set_speed(pd, pd->write_speed, pd->read_speed);
578                         }
579                 } else {
580                         if (pd->read_speed != pd->write_speed) {
581                                 pd->read_speed = pd->write_speed;
582                                 pkt_set_speed(pd, pd->write_speed, pd->read_speed);
583                         }
584                 }
585
586                 atomic_inc(&pd->cdrw.pending_bios);
587                 generic_make_request(bio);
588         }
589 }
590
591 /*
592  * Special care is needed if the underlying block device has a small
593  * max_phys_segments value.
594  */
595 static int pkt_set_segment_merging(struct pktcdvd_device *pd, request_queue_t *q)
596 {
597         if ((pd->settings.size << 9) / CD_FRAMESIZE <= q->max_phys_segments) {
598                 /*
599                  * The cdrom device can handle one segment/frame
600                  */
601                 clear_bit(PACKET_MERGE_SEGS, &pd->flags);
602                 return 0;
603         } else if ((pd->settings.size << 9) / PAGE_SIZE <= q->max_phys_segments) {
604                 /*
605                  * We can handle this case at the expense of some extra memory
606                  * copies during write operations
607                  */
608                 set_bit(PACKET_MERGE_SEGS, &pd->flags);
609                 return 0;
610         } else {
611                 printk("pktcdvd: cdrom max_phys_segments too small\n");
612                 return -EIO;
613         }
614 }
615
616 /*
617  * Copy CD_FRAMESIZE bytes from src_bio into a destination page
618  */
619 static void pkt_copy_bio_data(struct bio *src_bio, int seg, int offs, struct page *dst_page, int dst_offs)
620 {
621         unsigned int copy_size = CD_FRAMESIZE;
622
623         while (copy_size > 0) {
624                 struct bio_vec *src_bvl = bio_iovec_idx(src_bio, seg);
625                 void *vfrom = kmap_atomic(src_bvl->bv_page, KM_USER0) +
626                         src_bvl->bv_offset + offs;
627                 void *vto = page_address(dst_page) + dst_offs;
628                 int len = min_t(int, copy_size, src_bvl->bv_len - offs);
629
630                 BUG_ON(len < 0);
631                 memcpy(vto, vfrom, len);
632                 kunmap_atomic(vfrom, KM_USER0);
633
634                 seg++;
635                 offs = 0;
636                 dst_offs += len;
637                 copy_size -= len;
638         }
639 }
640
641 /*
642  * Copy all data for this packet to pkt->pages[], so that
643  * a) The number of required segments for the write bio is minimized, which
644  *    is necessary for some scsi controllers.
645  * b) The data can be used as cache to avoid read requests if we receive a
646  *    new write request for the same zone.
647  */
648 static void pkt_make_local_copy(struct packet_data *pkt, struct page **pages, int *offsets)
649 {
650         int f, p, offs;
651
652         /* Copy all data to pkt->pages[] */
653         p = 0;
654         offs = 0;
655         for (f = 0; f < pkt->frames; f++) {
656                 if (pages[f] != pkt->pages[p]) {
657                         void *vfrom = kmap_atomic(pages[f], KM_USER0) + offsets[f];
658                         void *vto = page_address(pkt->pages[p]) + offs;
659                         memcpy(vto, vfrom, CD_FRAMESIZE);
660                         kunmap_atomic(vfrom, KM_USER0);
661                         pages[f] = pkt->pages[p];
662                         offsets[f] = offs;
663                 } else {
664                         BUG_ON(offsets[f] != offs);
665                 }
666                 offs += CD_FRAMESIZE;
667                 if (offs >= PAGE_SIZE) {
668                         offs = 0;
669                         p++;
670                 }
671         }
672 }
673
674 static int pkt_end_io_read(struct bio *bio, unsigned int bytes_done, int err)
675 {
676         struct packet_data *pkt = bio->bi_private;
677         struct pktcdvd_device *pd = pkt->pd;
678         BUG_ON(!pd);
679
680         if (bio->bi_size)
681                 return 1;
682
683         VPRINTK("pkt_end_io_read: bio=%p sec0=%llx sec=%llx err=%d\n", bio,
684                 (unsigned long long)pkt->sector, (unsigned long long)bio->bi_sector, err);
685
686         if (err)
687                 atomic_inc(&pkt->io_errors);
688         if (atomic_dec_and_test(&pkt->io_wait)) {
689                 atomic_inc(&pkt->run_sm);
690                 wake_up(&pd->wqueue);
691         }
692         pkt_bio_finished(pd);
693
694         return 0;
695 }
696
697 static int pkt_end_io_packet_write(struct bio *bio, unsigned int bytes_done, int err)
698 {
699         struct packet_data *pkt = bio->bi_private;
700         struct pktcdvd_device *pd = pkt->pd;
701         BUG_ON(!pd);
702
703         if (bio->bi_size)
704                 return 1;
705
706         VPRINTK("pkt_end_io_packet_write: id=%d, err=%d\n", pkt->id, err);
707
708         pd->stats.pkt_ended++;
709
710         pkt_bio_finished(pd);
711         atomic_dec(&pkt->io_wait);
712         atomic_inc(&pkt->run_sm);
713         wake_up(&pd->wqueue);
714         return 0;
715 }
716
717 /*
718  * Schedule reads for the holes in a packet
719  */
720 static void pkt_gather_data(struct pktcdvd_device *pd, struct packet_data *pkt)
721 {
722         int frames_read = 0;
723         struct bio *bio;
724         int f;
725         char written[PACKET_MAX_SIZE];
726
727         BUG_ON(!pkt->orig_bios);
728
729         atomic_set(&pkt->io_wait, 0);
730         atomic_set(&pkt->io_errors, 0);
731
732         /*
733          * Figure out which frames we need to read before we can write.
734          */
735         memset(written, 0, sizeof(written));
736         spin_lock(&pkt->lock);
737         for (bio = pkt->orig_bios; bio; bio = bio->bi_next) {
738                 int first_frame = (bio->bi_sector - pkt->sector) / (CD_FRAMESIZE >> 9);
739                 int num_frames = bio->bi_size / CD_FRAMESIZE;
740                 pd->stats.secs_w += num_frames * (CD_FRAMESIZE >> 9);
741                 BUG_ON(first_frame < 0);
742                 BUG_ON(first_frame + num_frames > pkt->frames);
743                 for (f = first_frame; f < first_frame + num_frames; f++)
744                         written[f] = 1;
745         }
746         spin_unlock(&pkt->lock);
747
748         if (pkt->cache_valid) {
749                 VPRINTK("pkt_gather_data: zone %llx cached\n",
750                         (unsigned long long)pkt->sector);
751                 goto out_account;
752         }
753
754         /*
755          * Schedule reads for missing parts of the packet.
756          */
757         for (f = 0; f < pkt->frames; f++) {
758                 int p, offset;
759                 if (written[f])
760                         continue;
761                 bio = pkt->r_bios[f];
762                 bio_init(bio);
763                 bio->bi_max_vecs = 1;
764                 bio->bi_sector = pkt->sector + f * (CD_FRAMESIZE >> 9);
765                 bio->bi_bdev = pd->bdev;
766                 bio->bi_end_io = pkt_end_io_read;
767                 bio->bi_private = pkt;
768
769                 p = (f * CD_FRAMESIZE) / PAGE_SIZE;
770                 offset = (f * CD_FRAMESIZE) % PAGE_SIZE;
771                 VPRINTK("pkt_gather_data: Adding frame %d, page:%p offs:%d\n",
772                         f, pkt->pages[p], offset);
773                 if (!bio_add_page(bio, pkt->pages[p], CD_FRAMESIZE, offset))
774                         BUG();
775
776                 atomic_inc(&pkt->io_wait);
777                 bio->bi_rw = READ;
778                 pkt_queue_bio(pd, bio);
779                 frames_read++;
780         }
781
782 out_account:
783         VPRINTK("pkt_gather_data: need %d frames for zone %llx\n",
784                 frames_read, (unsigned long long)pkt->sector);
785         pd->stats.pkt_started++;
786         pd->stats.secs_rg += frames_read * (CD_FRAMESIZE >> 9);
787 }
788
789 /*
790  * Find a packet matching zone, or the least recently used packet if
791  * there is no match.
792  */
793 static struct packet_data *pkt_get_packet_data(struct pktcdvd_device *pd, int zone)
794 {
795         struct packet_data *pkt;
796
797         list_for_each_entry(pkt, &pd->cdrw.pkt_free_list, list) {
798                 if (pkt->sector == zone || pkt->list.next == &pd->cdrw.pkt_free_list) {
799                         list_del_init(&pkt->list);
800                         if (pkt->sector != zone)
801                                 pkt->cache_valid = 0;
802                         return pkt;
803                 }
804         }
805         BUG();
806         return NULL;
807 }
808
809 static void pkt_put_packet_data(struct pktcdvd_device *pd, struct packet_data *pkt)
810 {
811         if (pkt->cache_valid) {
812                 list_add(&pkt->list, &pd->cdrw.pkt_free_list);
813         } else {
814                 list_add_tail(&pkt->list, &pd->cdrw.pkt_free_list);
815         }
816 }
817
818 /*
819  * recover a failed write, query for relocation if possible
820  *
821  * returns 1 if recovery is possible, or 0 if not
822  *
823  */
824 static int pkt_start_recovery(struct packet_data *pkt)
825 {
826         /*
827          * FIXME. We need help from the file system to implement
828          * recovery handling.
829          */
830         return 0;
831 #if 0
832         struct request *rq = pkt->rq;
833         struct pktcdvd_device *pd = rq->rq_disk->private_data;
834         struct block_device *pkt_bdev;
835         struct super_block *sb = NULL;
836         unsigned long old_block, new_block;
837         sector_t new_sector;
838
839         pkt_bdev = bdget(kdev_t_to_nr(pd->pkt_dev));
840         if (pkt_bdev) {
841                 sb = get_super(pkt_bdev);
842                 bdput(pkt_bdev);
843         }
844
845         if (!sb)
846                 return 0;
847
848         if (!sb->s_op || !sb->s_op->relocate_blocks)
849                 goto out;
850
851         old_block = pkt->sector / (CD_FRAMESIZE >> 9);
852         if (sb->s_op->relocate_blocks(sb, old_block, &new_block))
853                 goto out;
854
855         new_sector = new_block * (CD_FRAMESIZE >> 9);
856         pkt->sector = new_sector;
857
858         pkt->bio->bi_sector = new_sector;
859         pkt->bio->bi_next = NULL;
860         pkt->bio->bi_flags = 1 << BIO_UPTODATE;
861         pkt->bio->bi_idx = 0;
862
863         BUG_ON(pkt->bio->bi_rw != (1 << BIO_RW));
864         BUG_ON(pkt->bio->bi_vcnt != pkt->frames);
865         BUG_ON(pkt->bio->bi_size != pkt->frames * CD_FRAMESIZE);
866         BUG_ON(pkt->bio->bi_end_io != pkt_end_io_packet_write);
867         BUG_ON(pkt->bio->bi_private != pkt);
868
869         drop_super(sb);
870         return 1;
871
872 out:
873         drop_super(sb);
874         return 0;
875 #endif
876 }
877
878 static inline void pkt_set_state(struct packet_data *pkt, enum packet_data_state state)
879 {
880 #if PACKET_DEBUG > 1
881         static const char *state_name[] = {
882                 "IDLE", "WAITING", "READ_WAIT", "WRITE_WAIT", "RECOVERY", "FINISHED"
883         };
884         enum packet_data_state old_state = pkt->state;
885         VPRINTK("pkt %2d : s=%6llx %s -> %s\n", pkt->id, (unsigned long long)pkt->sector,
886                 state_name[old_state], state_name[state]);
887 #endif
888         pkt->state = state;
889 }
890
891 /*
892  * Scan the work queue to see if we can start a new packet.
893  * returns non-zero if any work was done.
894  */
895 static int pkt_handle_queue(struct pktcdvd_device *pd)
896 {
897         struct packet_data *pkt, *p;
898         struct bio *bio = NULL;
899         sector_t zone = 0; /* Suppress gcc warning */
900         struct pkt_rb_node *node, *first_node;
901         struct rb_node *n;
902
903         VPRINTK("handle_queue\n");
904
905         atomic_set(&pd->scan_queue, 0);
906
907         if (list_empty(&pd->cdrw.pkt_free_list)) {
908                 VPRINTK("handle_queue: no pkt\n");
909                 return 0;
910         }
911
912         /*
913          * Try to find a zone we are not already working on.
914          */
915         spin_lock(&pd->lock);
916         first_node = pkt_rbtree_find(pd, pd->current_sector);
917         if (!first_node) {
918                 n = rb_first(&pd->bio_queue);
919                 if (n)
920                         first_node = rb_entry(n, struct pkt_rb_node, rb_node);
921         }
922         node = first_node;
923         while (node) {
924                 bio = node->bio;
925                 zone = ZONE(bio->bi_sector, pd);
926                 list_for_each_entry(p, &pd->cdrw.pkt_active_list, list) {
927                         if (p->sector == zone) {
928                                 bio = NULL;
929                                 goto try_next_bio;
930                         }
931                 }
932                 break;
933 try_next_bio:
934                 node = pkt_rbtree_next(node);
935                 if (!node) {
936                         n = rb_first(&pd->bio_queue);
937                         if (n)
938                                 node = rb_entry(n, struct pkt_rb_node, rb_node);
939                 }
940                 if (node == first_node)
941                         node = NULL;
942         }
943         spin_unlock(&pd->lock);
944         if (!bio) {
945                 VPRINTK("handle_queue: no bio\n");
946                 return 0;
947         }
948
949         pkt = pkt_get_packet_data(pd, zone);
950
951         pd->current_sector = zone + pd->settings.size;
952         pkt->sector = zone;
953         BUG_ON(pkt->frames != pd->settings.size >> 2);
954         pkt->write_size = 0;
955
956         /*
957          * Scan work queue for bios in the same zone and link them
958          * to this packet.
959          */
960         spin_lock(&pd->lock);
961         VPRINTK("pkt_handle_queue: looking for zone %llx\n", (unsigned long long)zone);
962         while ((node = pkt_rbtree_find(pd, zone)) != NULL) {
963                 bio = node->bio;
964                 VPRINTK("pkt_handle_queue: found zone=%llx\n",
965                         (unsigned long long)ZONE(bio->bi_sector, pd));
966                 if (ZONE(bio->bi_sector, pd) != zone)
967                         break;
968                 pkt_rbtree_erase(pd, node);
969                 spin_lock(&pkt->lock);
970                 pkt_add_list_last(bio, &pkt->orig_bios, &pkt->orig_bios_tail);
971                 pkt->write_size += bio->bi_size / CD_FRAMESIZE;
972                 spin_unlock(&pkt->lock);
973         }
974         spin_unlock(&pd->lock);
975
976         pkt->sleep_time = max(PACKET_WAIT_TIME, 1);
977         pkt_set_state(pkt, PACKET_WAITING_STATE);
978         atomic_set(&pkt->run_sm, 1);
979
980         spin_lock(&pd->cdrw.active_list_lock);
981         list_add(&pkt->list, &pd->cdrw.pkt_active_list);
982         spin_unlock(&pd->cdrw.active_list_lock);
983
984         return 1;
985 }
986
987 /*
988  * Assemble a bio to write one packet and queue the bio for processing
989  * by the underlying block device.
990  */
991 static void pkt_start_write(struct pktcdvd_device *pd, struct packet_data *pkt)
992 {
993         struct bio *bio;
994         struct page *pages[PACKET_MAX_SIZE];
995         int offsets[PACKET_MAX_SIZE];
996         int f;
997         int frames_write;
998
999         for (f = 0; f < pkt->frames; f++) {
1000                 pages[f] = pkt->pages[(f * CD_FRAMESIZE) / PAGE_SIZE];
1001                 offsets[f] = (f * CD_FRAMESIZE) % PAGE_SIZE;
1002         }
1003
1004         /*
1005          * Fill-in pages[] and offsets[] with data from orig_bios.
1006          */
1007         frames_write = 0;
1008         spin_lock(&pkt->lock);
1009         for (bio = pkt->orig_bios; bio; bio = bio->bi_next) {
1010                 int segment = bio->bi_idx;
1011                 int src_offs = 0;
1012                 int first_frame = (bio->bi_sector - pkt->sector) / (CD_FRAMESIZE >> 9);
1013                 int num_frames = bio->bi_size / CD_FRAMESIZE;
1014                 BUG_ON(first_frame < 0);
1015                 BUG_ON(first_frame + num_frames > pkt->frames);
1016                 for (f = first_frame; f < first_frame + num_frames; f++) {
1017                         struct bio_vec *src_bvl = bio_iovec_idx(bio, segment);
1018
1019                         while (src_offs >= src_bvl->bv_len) {
1020                                 src_offs -= src_bvl->bv_len;
1021                                 segment++;
1022                                 BUG_ON(segment >= bio->bi_vcnt);
1023                                 src_bvl = bio_iovec_idx(bio, segment);
1024                         }
1025
1026                         if (src_bvl->bv_len - src_offs >= CD_FRAMESIZE) {
1027                                 pages[f] = src_bvl->bv_page;
1028                                 offsets[f] = src_bvl->bv_offset + src_offs;
1029                         } else {
1030                                 pkt_copy_bio_data(bio, segment, src_offs,
1031                                                   pages[f], offsets[f]);
1032                         }
1033                         src_offs += CD_FRAMESIZE;
1034                         frames_write++;
1035                 }
1036         }
1037         pkt_set_state(pkt, PACKET_WRITE_WAIT_STATE);
1038         spin_unlock(&pkt->lock);
1039
1040         VPRINTK("pkt_start_write: Writing %d frames for zone %llx\n",
1041                 frames_write, (unsigned long long)pkt->sector);
1042         BUG_ON(frames_write != pkt->write_size);
1043
1044         if (test_bit(PACKET_MERGE_SEGS, &pd->flags) || (pkt->write_size < pkt->frames)) {
1045                 pkt_make_local_copy(pkt, pages, offsets);
1046                 pkt->cache_valid = 1;
1047         } else {
1048                 pkt->cache_valid = 0;
1049         }
1050
1051         /* Start the write request */
1052         bio_init(pkt->w_bio);
1053         pkt->w_bio->bi_max_vecs = PACKET_MAX_SIZE;
1054         pkt->w_bio->bi_sector = pkt->sector;
1055         pkt->w_bio->bi_bdev = pd->bdev;
1056         pkt->w_bio->bi_end_io = pkt_end_io_packet_write;
1057         pkt->w_bio->bi_private = pkt;
1058         for (f = 0; f < pkt->frames; f++) {
1059                 if ((f + 1 < pkt->frames) && (pages[f + 1] == pages[f]) &&
1060                     (offsets[f + 1] = offsets[f] + CD_FRAMESIZE)) {
1061                         if (!bio_add_page(pkt->w_bio, pages[f], CD_FRAMESIZE * 2, offsets[f]))
1062                                 BUG();
1063                         f++;
1064                 } else {
1065                         if (!bio_add_page(pkt->w_bio, pages[f], CD_FRAMESIZE, offsets[f]))
1066                                 BUG();
1067                 }
1068         }
1069         VPRINTK("pktcdvd: vcnt=%d\n", pkt->w_bio->bi_vcnt);
1070
1071         atomic_set(&pkt->io_wait, 1);
1072         pkt->w_bio->bi_rw = WRITE;
1073         pkt_queue_bio(pd, pkt->w_bio);
1074 }
1075
1076 static void pkt_finish_packet(struct packet_data *pkt, int uptodate)
1077 {
1078         struct bio *bio, *next;
1079
1080         if (!uptodate)
1081                 pkt->cache_valid = 0;
1082
1083         /* Finish all bios corresponding to this packet */
1084         bio = pkt->orig_bios;
1085         while (bio) {
1086                 next = bio->bi_next;
1087                 bio->bi_next = NULL;
1088                 bio_endio(bio, bio->bi_size, uptodate ? 0 : -EIO);
1089                 bio = next;
1090         }
1091         pkt->orig_bios = pkt->orig_bios_tail = NULL;
1092 }
1093
1094 static void pkt_run_state_machine(struct pktcdvd_device *pd, struct packet_data *pkt)
1095 {
1096         int uptodate;
1097
1098         VPRINTK("run_state_machine: pkt %d\n", pkt->id);
1099
1100         for (;;) {
1101                 switch (pkt->state) {
1102                 case PACKET_WAITING_STATE:
1103                         if ((pkt->write_size < pkt->frames) && (pkt->sleep_time > 0))
1104                                 return;
1105
1106                         pkt->sleep_time = 0;
1107                         pkt_gather_data(pd, pkt);
1108                         pkt_set_state(pkt, PACKET_READ_WAIT_STATE);
1109                         break;
1110
1111                 case PACKET_READ_WAIT_STATE:
1112                         if (atomic_read(&pkt->io_wait) > 0)
1113                                 return;
1114
1115                         if (atomic_read(&pkt->io_errors) > 0) {
1116                                 pkt_set_state(pkt, PACKET_RECOVERY_STATE);
1117                         } else {
1118                                 pkt_start_write(pd, pkt);
1119                         }
1120                         break;
1121
1122                 case PACKET_WRITE_WAIT_STATE:
1123                         if (atomic_read(&pkt->io_wait) > 0)
1124                                 return;
1125
1126                         if (test_bit(BIO_UPTODATE, &pkt->w_bio->bi_flags)) {
1127                                 pkt_set_state(pkt, PACKET_FINISHED_STATE);
1128                         } else {
1129                                 pkt_set_state(pkt, PACKET_RECOVERY_STATE);
1130                         }
1131                         break;
1132
1133                 case PACKET_RECOVERY_STATE:
1134                         if (pkt_start_recovery(pkt)) {
1135                                 pkt_start_write(pd, pkt);
1136                         } else {
1137                                 VPRINTK("No recovery possible\n");
1138                                 pkt_set_state(pkt, PACKET_FINISHED_STATE);
1139                         }
1140                         break;
1141
1142                 case PACKET_FINISHED_STATE:
1143                         uptodate = test_bit(BIO_UPTODATE, &pkt->w_bio->bi_flags);
1144                         pkt_finish_packet(pkt, uptodate);
1145                         return;
1146
1147                 default:
1148                         BUG();
1149                         break;
1150                 }
1151         }
1152 }
1153
1154 static void pkt_handle_packets(struct pktcdvd_device *pd)
1155 {
1156         struct packet_data *pkt, *next;
1157
1158         VPRINTK("pkt_handle_packets\n");
1159
1160         /*
1161          * Run state machine for active packets
1162          */
1163         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1164                 if (atomic_read(&pkt->run_sm) > 0) {
1165                         atomic_set(&pkt->run_sm, 0);
1166                         pkt_run_state_machine(pd, pkt);
1167                 }
1168         }
1169
1170         /*
1171          * Move no longer active packets to the free list
1172          */
1173         spin_lock(&pd->cdrw.active_list_lock);
1174         list_for_each_entry_safe(pkt, next, &pd->cdrw.pkt_active_list, list) {
1175                 if (pkt->state == PACKET_FINISHED_STATE) {
1176                         list_del(&pkt->list);
1177                         pkt_put_packet_data(pd, pkt);
1178                         pkt_set_state(pkt, PACKET_IDLE_STATE);
1179                         atomic_set(&pd->scan_queue, 1);
1180                 }
1181         }
1182         spin_unlock(&pd->cdrw.active_list_lock);
1183 }
1184
1185 static void pkt_count_states(struct pktcdvd_device *pd, int *states)
1186 {
1187         struct packet_data *pkt;
1188         int i;
1189
1190         for (i = 0; i < PACKET_NUM_STATES; i++)
1191                 states[i] = 0;
1192
1193         spin_lock(&pd->cdrw.active_list_lock);
1194         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1195                 states[pkt->state]++;
1196         }
1197         spin_unlock(&pd->cdrw.active_list_lock);
1198 }
1199
1200 /*
1201  * kcdrwd is woken up when writes have been queued for one of our
1202  * registered devices
1203  */
1204 static int kcdrwd(void *foobar)
1205 {
1206         struct pktcdvd_device *pd = foobar;
1207         struct packet_data *pkt;
1208         long min_sleep_time, residue;
1209
1210         set_user_nice(current, -20);
1211
1212         for (;;) {
1213                 DECLARE_WAITQUEUE(wait, current);
1214
1215                 /*
1216                  * Wait until there is something to do
1217                  */
1218                 add_wait_queue(&pd->wqueue, &wait);
1219                 for (;;) {
1220                         set_current_state(TASK_INTERRUPTIBLE);
1221
1222                         /* Check if we need to run pkt_handle_queue */
1223                         if (atomic_read(&pd->scan_queue) > 0)
1224                                 goto work_to_do;
1225
1226                         /* Check if we need to run the state machine for some packet */
1227                         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1228                                 if (atomic_read(&pkt->run_sm) > 0)
1229                                         goto work_to_do;
1230                         }
1231
1232                         /* Check if we need to process the iosched queues */
1233                         if (atomic_read(&pd->iosched.attention) != 0)
1234                                 goto work_to_do;
1235
1236                         /* Otherwise, go to sleep */
1237                         if (PACKET_DEBUG > 1) {
1238                                 int states[PACKET_NUM_STATES];
1239                                 pkt_count_states(pd, states);
1240                                 VPRINTK("kcdrwd: i:%d ow:%d rw:%d ww:%d rec:%d fin:%d\n",
1241                                         states[0], states[1], states[2], states[3],
1242                                         states[4], states[5]);
1243                         }
1244
1245                         min_sleep_time = MAX_SCHEDULE_TIMEOUT;
1246                         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1247                                 if (pkt->sleep_time && pkt->sleep_time < min_sleep_time)
1248                                         min_sleep_time = pkt->sleep_time;
1249                         }
1250
1251                         generic_unplug_device(bdev_get_queue(pd->bdev));
1252
1253                         VPRINTK("kcdrwd: sleeping\n");
1254                         residue = schedule_timeout(min_sleep_time);
1255                         VPRINTK("kcdrwd: wake up\n");
1256
1257                         /* make swsusp happy with our thread */
1258                         try_to_freeze();
1259
1260                         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
1261                                 if (!pkt->sleep_time)
1262                                         continue;
1263                                 pkt->sleep_time -= min_sleep_time - residue;
1264                                 if (pkt->sleep_time <= 0) {
1265                                         pkt->sleep_time = 0;
1266                                         atomic_inc(&pkt->run_sm);
1267                                 }
1268                         }
1269
1270                         if (signal_pending(current)) {
1271                                 flush_signals(current);
1272                         }
1273                         if (kthread_should_stop())
1274                                 break;
1275                 }
1276 work_to_do:
1277                 set_current_state(TASK_RUNNING);
1278                 remove_wait_queue(&pd->wqueue, &wait);
1279
1280                 if (kthread_should_stop())
1281                         break;
1282
1283                 /*
1284                  * if pkt_handle_queue returns true, we can queue
1285                  * another request.
1286                  */
1287                 while (pkt_handle_queue(pd))
1288                         ;
1289
1290                 /*
1291                  * Handle packet state machine
1292                  */
1293                 pkt_handle_packets(pd);
1294
1295                 /*
1296                  * Handle iosched queues
1297                  */
1298                 pkt_iosched_process_queue(pd);
1299         }
1300
1301         return 0;
1302 }
1303
1304 static void pkt_print_settings(struct pktcdvd_device *pd)
1305 {
1306         printk("pktcdvd: %s packets, ", pd->settings.fp ? "Fixed" : "Variable");
1307         printk("%u blocks, ", pd->settings.size >> 2);
1308         printk("Mode-%c disc\n", pd->settings.block_mode == 8 ? '1' : '2');
1309 }
1310
1311 static int pkt_mode_sense(struct pktcdvd_device *pd, struct packet_command *cgc, int page_code, int page_control)
1312 {
1313         memset(cgc->cmd, 0, sizeof(cgc->cmd));
1314
1315         cgc->cmd[0] = GPCMD_MODE_SENSE_10;
1316         cgc->cmd[2] = page_code | (page_control << 6);
1317         cgc->cmd[7] = cgc->buflen >> 8;
1318         cgc->cmd[8] = cgc->buflen & 0xff;
1319         cgc->data_direction = CGC_DATA_READ;
1320         return pkt_generic_packet(pd, cgc);
1321 }
1322
1323 static int pkt_mode_select(struct pktcdvd_device *pd, struct packet_command *cgc)
1324 {
1325         memset(cgc->cmd, 0, sizeof(cgc->cmd));
1326         memset(cgc->buffer, 0, 2);
1327         cgc->cmd[0] = GPCMD_MODE_SELECT_10;
1328         cgc->cmd[1] = 0x10;             /* PF */
1329         cgc->cmd[7] = cgc->buflen >> 8;
1330         cgc->cmd[8] = cgc->buflen & 0xff;
1331         cgc->data_direction = CGC_DATA_WRITE;
1332         return pkt_generic_packet(pd, cgc);
1333 }
1334
1335 static int pkt_get_disc_info(struct pktcdvd_device *pd, disc_information *di)
1336 {
1337         struct packet_command cgc;
1338         int ret;
1339
1340         /* set up command and get the disc info */
1341         init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ);
1342         cgc.cmd[0] = GPCMD_READ_DISC_INFO;
1343         cgc.cmd[8] = cgc.buflen = 2;
1344         cgc.quiet = 1;
1345
1346         if ((ret = pkt_generic_packet(pd, &cgc)))
1347                 return ret;
1348
1349         /* not all drives have the same disc_info length, so requeue
1350          * packet with the length the drive tells us it can supply
1351          */
1352         cgc.buflen = be16_to_cpu(di->disc_information_length) +
1353                      sizeof(di->disc_information_length);
1354
1355         if (cgc.buflen > sizeof(disc_information))
1356                 cgc.buflen = sizeof(disc_information);
1357
1358         cgc.cmd[8] = cgc.buflen;
1359         return pkt_generic_packet(pd, &cgc);
1360 }
1361
1362 static int pkt_get_track_info(struct pktcdvd_device *pd, __u16 track, __u8 type, track_information *ti)
1363 {
1364         struct packet_command cgc;
1365         int ret;
1366
1367         init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ);
1368         cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO;
1369         cgc.cmd[1] = type & 3;
1370         cgc.cmd[4] = (track & 0xff00) >> 8;
1371         cgc.cmd[5] = track & 0xff;
1372         cgc.cmd[8] = 8;
1373         cgc.quiet = 1;
1374
1375         if ((ret = pkt_generic_packet(pd, &cgc)))
1376                 return ret;
1377
1378         cgc.buflen = be16_to_cpu(ti->track_information_length) +
1379                      sizeof(ti->track_information_length);
1380
1381         if (cgc.buflen > sizeof(track_information))
1382                 cgc.buflen = sizeof(track_information);
1383
1384         cgc.cmd[8] = cgc.buflen;
1385         return pkt_generic_packet(pd, &cgc);
1386 }
1387
1388 static int pkt_get_last_written(struct pktcdvd_device *pd, long *last_written)
1389 {
1390         disc_information di;
1391         track_information ti;
1392         __u32 last_track;
1393         int ret = -1;
1394
1395         if ((ret = pkt_get_disc_info(pd, &di)))
1396                 return ret;
1397
1398         last_track = (di.last_track_msb << 8) | di.last_track_lsb;
1399         if ((ret = pkt_get_track_info(pd, last_track, 1, &ti)))
1400                 return ret;
1401
1402         /* if this track is blank, try the previous. */
1403         if (ti.blank) {
1404                 last_track--;
1405                 if ((ret = pkt_get_track_info(pd, last_track, 1, &ti)))
1406                         return ret;
1407         }
1408
1409         /* if last recorded field is valid, return it. */
1410         if (ti.lra_v) {
1411                 *last_written = be32_to_cpu(ti.last_rec_address);
1412         } else {
1413                 /* make it up instead */
1414                 *last_written = be32_to_cpu(ti.track_start) +
1415                                 be32_to_cpu(ti.track_size);
1416                 if (ti.free_blocks)
1417                         *last_written -= (be32_to_cpu(ti.free_blocks) + 7);
1418         }
1419         return 0;
1420 }
1421
1422 /*
1423  * write mode select package based on pd->settings
1424  */
1425 static int pkt_set_write_settings(struct pktcdvd_device *pd)
1426 {
1427         struct packet_command cgc;
1428         struct request_sense sense;
1429         write_param_page *wp;
1430         char buffer[128];
1431         int ret, size;
1432
1433         /* doesn't apply to DVD+RW or DVD-RAM */
1434         if ((pd->mmc3_profile == 0x1a) || (pd->mmc3_profile == 0x12))
1435                 return 0;
1436
1437         memset(buffer, 0, sizeof(buffer));
1438         init_cdrom_command(&cgc, buffer, sizeof(*wp), CGC_DATA_READ);
1439         cgc.sense = &sense;
1440         if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WRITE_PARMS_PAGE, 0))) {
1441                 pkt_dump_sense(&cgc);
1442                 return ret;
1443         }
1444
1445         size = 2 + ((buffer[0] << 8) | (buffer[1] & 0xff));
1446         pd->mode_offset = (buffer[6] << 8) | (buffer[7] & 0xff);
1447         if (size > sizeof(buffer))
1448                 size = sizeof(buffer);
1449
1450         /*
1451          * now get it all
1452          */
1453         init_cdrom_command(&cgc, buffer, size, CGC_DATA_READ);
1454         cgc.sense = &sense;
1455         if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WRITE_PARMS_PAGE, 0))) {
1456                 pkt_dump_sense(&cgc);
1457                 return ret;
1458         }
1459
1460         /*
1461          * write page is offset header + block descriptor length
1462          */
1463         wp = (write_param_page *) &buffer[sizeof(struct mode_page_header) + pd->mode_offset];
1464
1465         wp->fp = pd->settings.fp;
1466         wp->track_mode = pd->settings.track_mode;
1467         wp->write_type = pd->settings.write_type;
1468         wp->data_block_type = pd->settings.block_mode;
1469
1470         wp->multi_session = 0;
1471
1472 #ifdef PACKET_USE_LS
1473         wp->link_size = 7;
1474         wp->ls_v = 1;
1475 #endif
1476
1477         if (wp->data_block_type == PACKET_BLOCK_MODE1) {
1478                 wp->session_format = 0;
1479                 wp->subhdr2 = 0x20;
1480         } else if (wp->data_block_type == PACKET_BLOCK_MODE2) {
1481                 wp->session_format = 0x20;
1482                 wp->subhdr2 = 8;
1483 #if 0
1484                 wp->mcn[0] = 0x80;
1485                 memcpy(&wp->mcn[1], PACKET_MCN, sizeof(wp->mcn) - 1);
1486 #endif
1487         } else {
1488                 /*
1489                  * paranoia
1490                  */
1491                 printk("pktcdvd: write mode wrong %d\n", wp->data_block_type);
1492                 return 1;
1493         }
1494         wp->packet_size = cpu_to_be32(pd->settings.size >> 2);
1495
1496         cgc.buflen = cgc.cmd[8] = size;
1497         if ((ret = pkt_mode_select(pd, &cgc))) {
1498                 pkt_dump_sense(&cgc);
1499                 return ret;
1500         }
1501
1502         pkt_print_settings(pd);
1503         return 0;
1504 }
1505
1506 /*
1507  * 0 -- we can write to this track, 1 -- we can't
1508  */
1509 static int pkt_good_track(track_information *ti)
1510 {
1511         /*
1512          * only good for CD-RW at the moment, not DVD-RW
1513          */
1514
1515         /*
1516          * FIXME: only for FP
1517          */
1518         if (ti->fp == 0)
1519                 return 0;
1520
1521         /*
1522          * "good" settings as per Mt Fuji.
1523          */
1524         if (ti->rt == 0 && ti->blank == 0 && ti->packet == 1)
1525                 return 0;
1526
1527         if (ti->rt == 0 && ti->blank == 1 && ti->packet == 1)
1528                 return 0;
1529
1530         if (ti->rt == 1 && ti->blank == 0 && ti->packet == 1)
1531                 return 0;
1532
1533         printk("pktcdvd: bad state %d-%d-%d\n", ti->rt, ti->blank, ti->packet);
1534         return 1;
1535 }
1536
1537 /*
1538  * 0 -- we can write to this disc, 1 -- we can't
1539  */
1540 static int pkt_good_disc(struct pktcdvd_device *pd, disc_information *di)
1541 {
1542         switch (pd->mmc3_profile) {
1543                 case 0x0a: /* CD-RW */
1544                 case 0xffff: /* MMC3 not supported */
1545                         break;
1546                 case 0x1a: /* DVD+RW */
1547                 case 0x13: /* DVD-RW */
1548                 case 0x12: /* DVD-RAM */
1549                         return 0;
1550                 default:
1551                         printk("pktcdvd: Wrong disc profile (%x)\n", pd->mmc3_profile);
1552                         return 1;
1553         }
1554
1555         /*
1556          * for disc type 0xff we should probably reserve a new track.
1557          * but i'm not sure, should we leave this to user apps? probably.
1558          */
1559         if (di->disc_type == 0xff) {
1560                 printk("pktcdvd: Unknown disc. No track?\n");
1561                 return 1;
1562         }
1563
1564         if (di->disc_type != 0x20 && di->disc_type != 0) {
1565                 printk("pktcdvd: Wrong disc type (%x)\n", di->disc_type);
1566                 return 1;
1567         }
1568
1569         if (di->erasable == 0) {
1570                 printk("pktcdvd: Disc not erasable\n");
1571                 return 1;
1572         }
1573
1574         if (di->border_status == PACKET_SESSION_RESERVED) {
1575                 printk("pktcdvd: Can't write to last track (reserved)\n");
1576                 return 1;
1577         }
1578
1579         return 0;
1580 }
1581
1582 static int pkt_probe_settings(struct pktcdvd_device *pd)
1583 {
1584         struct packet_command cgc;
1585         unsigned char buf[12];
1586         disc_information di;
1587         track_information ti;
1588         int ret, track;
1589
1590         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1591         cgc.cmd[0] = GPCMD_GET_CONFIGURATION;
1592         cgc.cmd[8] = 8;
1593         ret = pkt_generic_packet(pd, &cgc);
1594         pd->mmc3_profile = ret ? 0xffff : buf[6] << 8 | buf[7];
1595
1596         memset(&di, 0, sizeof(disc_information));
1597         memset(&ti, 0, sizeof(track_information));
1598
1599         if ((ret = pkt_get_disc_info(pd, &di))) {
1600                 printk("failed get_disc\n");
1601                 return ret;
1602         }
1603
1604         if (pkt_good_disc(pd, &di))
1605                 return -ENXIO;
1606
1607         switch (pd->mmc3_profile) {
1608                 case 0x1a: /* DVD+RW */
1609                         printk("pktcdvd: inserted media is DVD+RW\n");
1610                         break;
1611                 case 0x13: /* DVD-RW */
1612                         printk("pktcdvd: inserted media is DVD-RW\n");
1613                         break;
1614                 case 0x12: /* DVD-RAM */
1615                         printk("pktcdvd: inserted media is DVD-RAM\n");
1616                         break;
1617                 default:
1618                         printk("pktcdvd: inserted media is CD-R%s\n", di.erasable ? "W" : "");
1619                         break;
1620         }
1621         pd->type = di.erasable ? PACKET_CDRW : PACKET_CDR;
1622
1623         track = 1; /* (di.last_track_msb << 8) | di.last_track_lsb; */
1624         if ((ret = pkt_get_track_info(pd, track, 1, &ti))) {
1625                 printk("pktcdvd: failed get_track\n");
1626                 return ret;
1627         }
1628
1629         if (pkt_good_track(&ti)) {
1630                 printk("pktcdvd: can't write to this track\n");
1631                 return -ENXIO;
1632         }
1633
1634         /*
1635          * we keep packet size in 512 byte units, makes it easier to
1636          * deal with request calculations.
1637          */
1638         pd->settings.size = be32_to_cpu(ti.fixed_packet_size) << 2;
1639         if (pd->settings.size == 0) {
1640                 printk("pktcdvd: detected zero packet size!\n");
1641                 return -ENXIO;
1642         }
1643         if (pd->settings.size > PACKET_MAX_SECTORS) {
1644                 printk("pktcdvd: packet size is too big\n");
1645                 return -ENXIO;
1646         }
1647         pd->settings.fp = ti.fp;
1648         pd->offset = (be32_to_cpu(ti.track_start) << 2) & (pd->settings.size - 1);
1649
1650         if (ti.nwa_v) {
1651                 pd->nwa = be32_to_cpu(ti.next_writable);
1652                 set_bit(PACKET_NWA_VALID, &pd->flags);
1653         }
1654
1655         /*
1656          * in theory we could use lra on -RW media as well and just zero
1657          * blocks that haven't been written yet, but in practice that
1658          * is just a no-go. we'll use that for -R, naturally.
1659          */
1660         if (ti.lra_v) {
1661                 pd->lra = be32_to_cpu(ti.last_rec_address);
1662                 set_bit(PACKET_LRA_VALID, &pd->flags);
1663         } else {
1664                 pd->lra = 0xffffffff;
1665                 set_bit(PACKET_LRA_VALID, &pd->flags);
1666         }
1667
1668         /*
1669          * fine for now
1670          */
1671         pd->settings.link_loss = 7;
1672         pd->settings.write_type = 0;    /* packet */
1673         pd->settings.track_mode = ti.track_mode;
1674
1675         /*
1676          * mode1 or mode2 disc
1677          */
1678         switch (ti.data_mode) {
1679                 case PACKET_MODE1:
1680                         pd->settings.block_mode = PACKET_BLOCK_MODE1;
1681                         break;
1682                 case PACKET_MODE2:
1683                         pd->settings.block_mode = PACKET_BLOCK_MODE2;
1684                         break;
1685                 default:
1686                         printk("pktcdvd: unknown data mode\n");
1687                         return 1;
1688         }
1689         return 0;
1690 }
1691
1692 /*
1693  * enable/disable write caching on drive
1694  */
1695 static int pkt_write_caching(struct pktcdvd_device *pd, int set)
1696 {
1697         struct packet_command cgc;
1698         struct request_sense sense;
1699         unsigned char buf[64];
1700         int ret;
1701
1702         memset(buf, 0, sizeof(buf));
1703         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_READ);
1704         cgc.sense = &sense;
1705         cgc.buflen = pd->mode_offset + 12;
1706
1707         /*
1708          * caching mode page might not be there, so quiet this command
1709          */
1710         cgc.quiet = 1;
1711
1712         if ((ret = pkt_mode_sense(pd, &cgc, GPMODE_WCACHING_PAGE, 0)))
1713                 return ret;
1714
1715         buf[pd->mode_offset + 10] |= (!!set << 2);
1716
1717         cgc.buflen = cgc.cmd[8] = 2 + ((buf[0] << 8) | (buf[1] & 0xff));
1718         ret = pkt_mode_select(pd, &cgc);
1719         if (ret) {
1720                 printk("pktcdvd: write caching control failed\n");
1721                 pkt_dump_sense(&cgc);
1722         } else if (!ret && set)
1723                 printk("pktcdvd: enabled write caching on %s\n", pd->name);
1724         return ret;
1725 }
1726
1727 static int pkt_lock_door(struct pktcdvd_device *pd, int lockflag)
1728 {
1729         struct packet_command cgc;
1730
1731         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
1732         cgc.cmd[0] = GPCMD_PREVENT_ALLOW_MEDIUM_REMOVAL;
1733         cgc.cmd[4] = lockflag ? 1 : 0;
1734         return pkt_generic_packet(pd, &cgc);
1735 }
1736
1737 /*
1738  * Returns drive maximum write speed
1739  */
1740 static int pkt_get_max_speed(struct pktcdvd_device *pd, unsigned *write_speed)
1741 {
1742         struct packet_command cgc;
1743         struct request_sense sense;
1744         unsigned char buf[256+18];
1745         unsigned char *cap_buf;
1746         int ret, offset;
1747
1748         memset(buf, 0, sizeof(buf));
1749         cap_buf = &buf[sizeof(struct mode_page_header) + pd->mode_offset];
1750         init_cdrom_command(&cgc, buf, sizeof(buf), CGC_DATA_UNKNOWN);
1751         cgc.sense = &sense;
1752
1753         ret = pkt_mode_sense(pd, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
1754         if (ret) {
1755                 cgc.buflen = pd->mode_offset + cap_buf[1] + 2 +
1756                              sizeof(struct mode_page_header);
1757                 ret = pkt_mode_sense(pd, &cgc, GPMODE_CAPABILITIES_PAGE, 0);
1758                 if (ret) {
1759                         pkt_dump_sense(&cgc);
1760                         return ret;
1761                 }
1762         }
1763
1764         offset = 20;                        /* Obsoleted field, used by older drives */
1765         if (cap_buf[1] >= 28)
1766                 offset = 28;                /* Current write speed selected */
1767         if (cap_buf[1] >= 30) {
1768                 /* If the drive reports at least one "Logical Unit Write
1769                  * Speed Performance Descriptor Block", use the information
1770                  * in the first block. (contains the highest speed)
1771                  */
1772                 int num_spdb = (cap_buf[30] << 8) + cap_buf[31];
1773                 if (num_spdb > 0)
1774                         offset = 34;
1775         }
1776
1777         *write_speed = (cap_buf[offset] << 8) | cap_buf[offset + 1];
1778         return 0;
1779 }
1780
1781 /* These tables from cdrecord - I don't have orange book */
1782 /* standard speed CD-RW (1-4x) */
1783 static char clv_to_speed[16] = {
1784         /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 */
1785            0, 2, 4, 6, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1786 };
1787 /* high speed CD-RW (-10x) */
1788 static char hs_clv_to_speed[16] = {
1789         /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 */
1790            0, 2, 4, 6, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1791 };
1792 /* ultra high speed CD-RW */
1793 static char us_clv_to_speed[16] = {
1794         /* 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 */
1795            0, 2, 4, 8, 0, 0,16, 0,24,32,40,48, 0, 0, 0, 0
1796 };
1797
1798 /*
1799  * reads the maximum media speed from ATIP
1800  */
1801 static int pkt_media_speed(struct pktcdvd_device *pd, unsigned *speed)
1802 {
1803         struct packet_command cgc;
1804         struct request_sense sense;
1805         unsigned char buf[64];
1806         unsigned int size, st, sp;
1807         int ret;
1808
1809         init_cdrom_command(&cgc, buf, 2, CGC_DATA_READ);
1810         cgc.sense = &sense;
1811         cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
1812         cgc.cmd[1] = 2;
1813         cgc.cmd[2] = 4; /* READ ATIP */
1814         cgc.cmd[8] = 2;
1815         ret = pkt_generic_packet(pd, &cgc);
1816         if (ret) {
1817                 pkt_dump_sense(&cgc);
1818                 return ret;
1819         }
1820         size = ((unsigned int) buf[0]<<8) + buf[1] + 2;
1821         if (size > sizeof(buf))
1822                 size = sizeof(buf);
1823
1824         init_cdrom_command(&cgc, buf, size, CGC_DATA_READ);
1825         cgc.sense = &sense;
1826         cgc.cmd[0] = GPCMD_READ_TOC_PMA_ATIP;
1827         cgc.cmd[1] = 2;
1828         cgc.cmd[2] = 4;
1829         cgc.cmd[8] = size;
1830         ret = pkt_generic_packet(pd, &cgc);
1831         if (ret) {
1832                 pkt_dump_sense(&cgc);
1833                 return ret;
1834         }
1835
1836         if (!buf[6] & 0x40) {
1837                 printk("pktcdvd: Disc type is not CD-RW\n");
1838                 return 1;
1839         }
1840         if (!buf[6] & 0x4) {
1841                 printk("pktcdvd: A1 values on media are not valid, maybe not CDRW?\n");
1842                 return 1;
1843         }
1844
1845         st = (buf[6] >> 3) & 0x7; /* disc sub-type */
1846
1847         sp = buf[16] & 0xf; /* max speed from ATIP A1 field */
1848
1849         /* Info from cdrecord */
1850         switch (st) {
1851                 case 0: /* standard speed */
1852                         *speed = clv_to_speed[sp];
1853                         break;
1854                 case 1: /* high speed */
1855                         *speed = hs_clv_to_speed[sp];
1856                         break;
1857                 case 2: /* ultra high speed */
1858                         *speed = us_clv_to_speed[sp];
1859                         break;
1860                 default:
1861                         printk("pktcdvd: Unknown disc sub-type %d\n",st);
1862                         return 1;
1863         }
1864         if (*speed) {
1865                 printk("pktcdvd: Max. media speed: %d\n",*speed);
1866                 return 0;
1867         } else {
1868                 printk("pktcdvd: Unknown speed %d for sub-type %d\n",sp,st);
1869                 return 1;
1870         }
1871 }
1872
1873 static int pkt_perform_opc(struct pktcdvd_device *pd)
1874 {
1875         struct packet_command cgc;
1876         struct request_sense sense;
1877         int ret;
1878
1879         VPRINTK("pktcdvd: Performing OPC\n");
1880
1881         init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE);
1882         cgc.sense = &sense;
1883         cgc.timeout = 60*HZ;
1884         cgc.cmd[0] = GPCMD_SEND_OPC;
1885         cgc.cmd[1] = 1;
1886         if ((ret = pkt_generic_packet(pd, &cgc)))
1887                 pkt_dump_sense(&cgc);
1888         return ret;
1889 }
1890
1891 static int pkt_open_write(struct pktcdvd_device *pd)
1892 {
1893         int ret;
1894         unsigned int write_speed, media_write_speed, read_speed;
1895
1896         if ((ret = pkt_probe_settings(pd))) {
1897                 DPRINTK("pktcdvd: %s failed probe\n", pd->name);
1898                 return -EIO;
1899         }
1900
1901         if ((ret = pkt_set_write_settings(pd))) {
1902                 DPRINTK("pktcdvd: %s failed saving write settings\n", pd->name);
1903                 return -EIO;
1904         }
1905
1906         pkt_write_caching(pd, USE_WCACHING);
1907
1908         if ((ret = pkt_get_max_speed(pd, &write_speed)))
1909                 write_speed = 16 * 177;
1910         switch (pd->mmc3_profile) {
1911                 case 0x13: /* DVD-RW */
1912                 case 0x1a: /* DVD+RW */
1913                 case 0x12: /* DVD-RAM */
1914                         DPRINTK("pktcdvd: write speed %ukB/s\n", write_speed);
1915                         break;
1916                 default:
1917                         if ((ret = pkt_media_speed(pd, &media_write_speed)))
1918                                 media_write_speed = 16;
1919                         write_speed = min(write_speed, media_write_speed * 177);
1920                         DPRINTK("pktcdvd: write speed %ux\n", write_speed / 176);
1921                         break;
1922         }
1923         read_speed = write_speed;
1924
1925         if ((ret = pkt_set_speed(pd, write_speed, read_speed))) {
1926                 DPRINTK("pktcdvd: %s couldn't set write speed\n", pd->name);
1927                 return -EIO;
1928         }
1929         pd->write_speed = write_speed;
1930         pd->read_speed = read_speed;
1931
1932         if ((ret = pkt_perform_opc(pd))) {
1933                 DPRINTK("pktcdvd: %s Optimum Power Calibration failed\n", pd->name);
1934         }
1935
1936         return 0;
1937 }
1938
1939 /*
1940  * called at open time.
1941  */
1942 static int pkt_open_dev(struct pktcdvd_device *pd, int write)
1943 {
1944         int ret;
1945         long lba;
1946         request_queue_t *q;
1947
1948         /*
1949          * We need to re-open the cdrom device without O_NONBLOCK to be able
1950          * to read/write from/to it. It is already opened in O_NONBLOCK mode
1951          * so bdget() can't fail.
1952          */
1953         bdget(pd->bdev->bd_dev);
1954         if ((ret = blkdev_get(pd->bdev, FMODE_READ, O_RDONLY)))
1955                 goto out;
1956
1957         if ((ret = bd_claim(pd->bdev, pd)))
1958                 goto out_putdev;
1959
1960         if ((ret = pkt_get_last_written(pd, &lba))) {
1961                 printk("pktcdvd: pkt_get_last_written failed\n");
1962                 goto out_unclaim;
1963         }
1964
1965         set_capacity(pd->disk, lba << 2);
1966         set_capacity(pd->bdev->bd_disk, lba << 2);
1967         bd_set_size(pd->bdev, (loff_t)lba << 11);
1968
1969         q = bdev_get_queue(pd->bdev);
1970         if (write) {
1971                 if ((ret = pkt_open_write(pd)))
1972                         goto out_unclaim;
1973                 /*
1974                  * Some CDRW drives can not handle writes larger than one packet,
1975                  * even if the size is a multiple of the packet size.
1976                  */
1977                 spin_lock_irq(q->queue_lock);
1978                 blk_queue_max_sectors(q, pd->settings.size);
1979                 spin_unlock_irq(q->queue_lock);
1980                 set_bit(PACKET_WRITABLE, &pd->flags);
1981         } else {
1982                 pkt_set_speed(pd, MAX_SPEED, MAX_SPEED);
1983                 clear_bit(PACKET_WRITABLE, &pd->flags);
1984         }
1985
1986         if ((ret = pkt_set_segment_merging(pd, q)))
1987                 goto out_unclaim;
1988
1989         if (write) {
1990                 if (!pkt_grow_pktlist(pd, CONFIG_CDROM_PKTCDVD_BUFFERS)) {
1991                         printk("pktcdvd: not enough memory for buffers\n");
1992                         ret = -ENOMEM;
1993                         goto out_unclaim;
1994                 }
1995                 printk("pktcdvd: %lukB available on disc\n", lba << 1);
1996         }
1997
1998         return 0;
1999
2000 out_unclaim:
2001         bd_release(pd->bdev);
2002 out_putdev:
2003         blkdev_put(pd->bdev);
2004 out:
2005         return ret;
2006 }
2007
2008 /*
2009  * called when the device is closed. makes sure that the device flushes
2010  * the internal cache before we close.
2011  */
2012 static void pkt_release_dev(struct pktcdvd_device *pd, int flush)
2013 {
2014         if (flush && pkt_flush_cache(pd))
2015                 DPRINTK("pktcdvd: %s not flushing cache\n", pd->name);
2016
2017         pkt_lock_door(pd, 0);
2018
2019         pkt_set_speed(pd, MAX_SPEED, MAX_SPEED);
2020         bd_release(pd->bdev);
2021         blkdev_put(pd->bdev);
2022
2023         pkt_shrink_pktlist(pd);
2024 }
2025
2026 static struct pktcdvd_device *pkt_find_dev_from_minor(int dev_minor)
2027 {
2028         if (dev_minor >= MAX_WRITERS)
2029                 return NULL;
2030         return pkt_devs[dev_minor];
2031 }
2032
2033 static int pkt_open(struct inode *inode, struct file *file)
2034 {
2035         struct pktcdvd_device *pd = NULL;
2036         int ret;
2037
2038         VPRINTK("pktcdvd: entering open\n");
2039
2040         down(&ctl_mutex);
2041         pd = pkt_find_dev_from_minor(iminor(inode));
2042         if (!pd) {
2043                 ret = -ENODEV;
2044                 goto out;
2045         }
2046         BUG_ON(pd->refcnt < 0);
2047
2048         pd->refcnt++;
2049         if (pd->refcnt > 1) {
2050                 if ((file->f_mode & FMODE_WRITE) &&
2051                     !test_bit(PACKET_WRITABLE, &pd->flags)) {
2052                         ret = -EBUSY;
2053                         goto out_dec;
2054                 }
2055         } else {
2056                 if (pkt_open_dev(pd, file->f_mode & FMODE_WRITE)) {
2057                         ret = -EIO;
2058                         goto out_dec;
2059                 }
2060                 /*
2061                  * needed here as well, since ext2 (among others) may change
2062                  * the blocksize at mount time
2063                  */
2064                 set_blocksize(inode->i_bdev, CD_FRAMESIZE);
2065         }
2066
2067         up(&ctl_mutex);
2068         return 0;
2069
2070 out_dec:
2071         pd->refcnt--;
2072 out:
2073         VPRINTK("pktcdvd: failed open (%d)\n", ret);
2074         up(&ctl_mutex);
2075         return ret;
2076 }
2077
2078 static int pkt_close(struct inode *inode, struct file *file)
2079 {
2080         struct pktcdvd_device *pd = inode->i_bdev->bd_disk->private_data;
2081         int ret = 0;
2082
2083         down(&ctl_mutex);
2084         pd->refcnt--;
2085         BUG_ON(pd->refcnt < 0);
2086         if (pd->refcnt == 0) {
2087                 int flush = test_bit(PACKET_WRITABLE, &pd->flags);
2088                 pkt_release_dev(pd, flush);
2089         }
2090         up(&ctl_mutex);
2091         return ret;
2092 }
2093
2094
2095 static void *psd_pool_alloc(gfp_t gfp_mask, void *data)
2096 {
2097         return kmalloc(sizeof(struct packet_stacked_data), gfp_mask);
2098 }
2099
2100 static void psd_pool_free(void *ptr, void *data)
2101 {
2102         kfree(ptr);
2103 }
2104
2105 static int pkt_end_io_read_cloned(struct bio *bio, unsigned int bytes_done, int err)
2106 {
2107         struct packet_stacked_data *psd = bio->bi_private;
2108         struct pktcdvd_device *pd = psd->pd;
2109
2110         if (bio->bi_size)
2111                 return 1;
2112
2113         bio_put(bio);
2114         bio_endio(psd->bio, psd->bio->bi_size, err);
2115         mempool_free(psd, psd_pool);
2116         pkt_bio_finished(pd);
2117         return 0;
2118 }
2119
2120 static int pkt_make_request(request_queue_t *q, struct bio *bio)
2121 {
2122         struct pktcdvd_device *pd;
2123         char b[BDEVNAME_SIZE];
2124         sector_t zone;
2125         struct packet_data *pkt;
2126         int was_empty, blocked_bio;
2127         struct pkt_rb_node *node;
2128
2129         pd = q->queuedata;
2130         if (!pd) {
2131                 printk("pktcdvd: %s incorrect request queue\n", bdevname(bio->bi_bdev, b));
2132                 goto end_io;
2133         }
2134
2135         /*
2136          * Clone READ bios so we can have our own bi_end_io callback.
2137          */
2138         if (bio_data_dir(bio) == READ) {
2139                 struct bio *cloned_bio = bio_clone(bio, GFP_NOIO);
2140                 struct packet_stacked_data *psd = mempool_alloc(psd_pool, GFP_NOIO);
2141
2142                 psd->pd = pd;
2143                 psd->bio = bio;
2144                 cloned_bio->bi_bdev = pd->bdev;
2145                 cloned_bio->bi_private = psd;
2146                 cloned_bio->bi_end_io = pkt_end_io_read_cloned;
2147                 pd->stats.secs_r += bio->bi_size >> 9;
2148                 pkt_queue_bio(pd, cloned_bio);
2149                 return 0;
2150         }
2151
2152         if (!test_bit(PACKET_WRITABLE, &pd->flags)) {
2153                 printk("pktcdvd: WRITE for ro device %s (%llu)\n",
2154                         pd->name, (unsigned long long)bio->bi_sector);
2155                 goto end_io;
2156         }
2157
2158         if (!bio->bi_size || (bio->bi_size % CD_FRAMESIZE)) {
2159                 printk("pktcdvd: wrong bio size\n");
2160                 goto end_io;
2161         }
2162
2163         blk_queue_bounce(q, &bio);
2164
2165         zone = ZONE(bio->bi_sector, pd);
2166         VPRINTK("pkt_make_request: start = %6llx stop = %6llx\n",
2167                 (unsigned long long)bio->bi_sector,
2168                 (unsigned long long)(bio->bi_sector + bio_sectors(bio)));
2169
2170         /* Check if we have to split the bio */
2171         {
2172                 struct bio_pair *bp;
2173                 sector_t last_zone;
2174                 int first_sectors;
2175
2176                 last_zone = ZONE(bio->bi_sector + bio_sectors(bio) - 1, pd);
2177                 if (last_zone != zone) {
2178                         BUG_ON(last_zone != zone + pd->settings.size);
2179                         first_sectors = last_zone - bio->bi_sector;
2180                         bp = bio_split(bio, bio_split_pool, first_sectors);
2181                         BUG_ON(!bp);
2182                         pkt_make_request(q, &bp->bio1);
2183                         pkt_make_request(q, &bp->bio2);
2184                         bio_pair_release(bp);
2185                         return 0;
2186                 }
2187         }
2188
2189         /*
2190          * If we find a matching packet in state WAITING or READ_WAIT, we can
2191          * just append this bio to that packet.
2192          */
2193         spin_lock(&pd->cdrw.active_list_lock);
2194         blocked_bio = 0;
2195         list_for_each_entry(pkt, &pd->cdrw.pkt_active_list, list) {
2196                 if (pkt->sector == zone) {
2197                         spin_lock(&pkt->lock);
2198                         if ((pkt->state == PACKET_WAITING_STATE) ||
2199                             (pkt->state == PACKET_READ_WAIT_STATE)) {
2200                                 pkt_add_list_last(bio, &pkt->orig_bios,
2201                                                   &pkt->orig_bios_tail);
2202                                 pkt->write_size += bio->bi_size / CD_FRAMESIZE;
2203                                 if ((pkt->write_size >= pkt->frames) &&
2204                                     (pkt->state == PACKET_WAITING_STATE)) {
2205                                         atomic_inc(&pkt->run_sm);
2206                                         wake_up(&pd->wqueue);
2207                                 }
2208                                 spin_unlock(&pkt->lock);
2209                                 spin_unlock(&pd->cdrw.active_list_lock);
2210                                 return 0;
2211                         } else {
2212                                 blocked_bio = 1;
2213                         }
2214                         spin_unlock(&pkt->lock);
2215                 }
2216         }
2217         spin_unlock(&pd->cdrw.active_list_lock);
2218
2219         /*
2220          * No matching packet found. Store the bio in the work queue.
2221          */
2222         node = mempool_alloc(pd->rb_pool, GFP_NOIO);
2223         node->bio = bio;
2224         spin_lock(&pd->lock);
2225         BUG_ON(pd->bio_queue_size < 0);
2226         was_empty = (pd->bio_queue_size == 0);
2227         pkt_rbtree_insert(pd, node);
2228         spin_unlock(&pd->lock);
2229
2230         /*
2231          * Wake up the worker thread.
2232          */
2233         atomic_set(&pd->scan_queue, 1);
2234         if (was_empty) {
2235                 /* This wake_up is required for correct operation */
2236                 wake_up(&pd->wqueue);
2237         } else if (!list_empty(&pd->cdrw.pkt_free_list) && !blocked_bio) {
2238                 /*
2239                  * This wake up is not required for correct operation,
2240                  * but improves performance in some cases.
2241                  */
2242                 wake_up(&pd->wqueue);
2243         }
2244         return 0;
2245 end_io:
2246         bio_io_error(bio, bio->bi_size);
2247         return 0;
2248 }
2249
2250
2251
2252 static int pkt_merge_bvec(request_queue_t *q, struct bio *bio, struct bio_vec *bvec)
2253 {
2254         struct pktcdvd_device *pd = q->queuedata;
2255         sector_t zone = ZONE(bio->bi_sector, pd);
2256         int used = ((bio->bi_sector - zone) << 9) + bio->bi_size;
2257         int remaining = (pd->settings.size << 9) - used;
2258         int remaining2;
2259
2260         /*
2261          * A bio <= PAGE_SIZE must be allowed. If it crosses a packet
2262          * boundary, pkt_make_request() will split the bio.
2263          */
2264         remaining2 = PAGE_SIZE - bio->bi_size;
2265         remaining = max(remaining, remaining2);
2266
2267         BUG_ON(remaining < 0);
2268         return remaining;
2269 }
2270
2271 static void pkt_init_queue(struct pktcdvd_device *pd)
2272 {
2273         request_queue_t *q = pd->disk->queue;
2274
2275         blk_queue_make_request(q, pkt_make_request);
2276         blk_queue_hardsect_size(q, CD_FRAMESIZE);
2277         blk_queue_max_sectors(q, PACKET_MAX_SECTORS);
2278         blk_queue_merge_bvec(q, pkt_merge_bvec);
2279         q->queuedata = pd;
2280 }
2281
2282 static int pkt_seq_show(struct seq_file *m, void *p)
2283 {
2284         struct pktcdvd_device *pd = m->private;
2285         char *msg;
2286         char bdev_buf[BDEVNAME_SIZE];
2287         int states[PACKET_NUM_STATES];
2288
2289         seq_printf(m, "Writer %s mapped to %s:\n", pd->name,
2290                    bdevname(pd->bdev, bdev_buf));
2291
2292         seq_printf(m, "\nSettings:\n");
2293         seq_printf(m, "\tpacket size:\t\t%dkB\n", pd->settings.size / 2);
2294
2295         if (pd->settings.write_type == 0)
2296                 msg = "Packet";
2297         else
2298                 msg = "Unknown";
2299         seq_printf(m, "\twrite type:\t\t%s\n", msg);
2300
2301         seq_printf(m, "\tpacket type:\t\t%s\n", pd->settings.fp ? "Fixed" : "Variable");
2302         seq_printf(m, "\tlink loss:\t\t%d\n", pd->settings.link_loss);
2303
2304         seq_printf(m, "\ttrack mode:\t\t%d\n", pd->settings.track_mode);
2305
2306         if (pd->settings.block_mode == PACKET_BLOCK_MODE1)
2307                 msg = "Mode 1";
2308         else if (pd->settings.block_mode == PACKET_BLOCK_MODE2)
2309                 msg = "Mode 2";
2310         else
2311                 msg = "Unknown";
2312         seq_printf(m, "\tblock mode:\t\t%s\n", msg);
2313
2314         seq_printf(m, "\nStatistics:\n");
2315         seq_printf(m, "\tpackets started:\t%lu\n", pd->stats.pkt_started);
2316         seq_printf(m, "\tpackets ended:\t\t%lu\n", pd->stats.pkt_ended);
2317         seq_printf(m, "\twritten:\t\t%lukB\n", pd->stats.secs_w >> 1);
2318         seq_printf(m, "\tread gather:\t\t%lukB\n", pd->stats.secs_rg >> 1);
2319         seq_printf(m, "\tread:\t\t\t%lukB\n", pd->stats.secs_r >> 1);
2320
2321         seq_printf(m, "\nMisc:\n");
2322         seq_printf(m, "\treference count:\t%d\n", pd->refcnt);
2323         seq_printf(m, "\tflags:\t\t\t0x%lx\n", pd->flags);
2324         seq_printf(m, "\tread speed:\t\t%ukB/s\n", pd->read_speed);
2325         seq_printf(m, "\twrite speed:\t\t%ukB/s\n", pd->write_speed);
2326         seq_printf(m, "\tstart offset:\t\t%lu\n", pd->offset);
2327         seq_printf(m, "\tmode page offset:\t%u\n", pd->mode_offset);
2328
2329         seq_printf(m, "\nQueue state:\n");
2330         seq_printf(m, "\tbios queued:\t\t%d\n", pd->bio_queue_size);
2331         seq_printf(m, "\tbios pending:\t\t%d\n", atomic_read(&pd->cdrw.pending_bios));
2332         seq_printf(m, "\tcurrent sector:\t\t0x%llx\n", (unsigned long long)pd->current_sector);
2333
2334         pkt_count_states(pd, states);
2335         seq_printf(m, "\tstate:\t\t\ti:%d ow:%d rw:%d ww:%d rec:%d fin:%d\n",
2336                    states[0], states[1], states[2], states[3], states[4], states[5]);
2337
2338         return 0;
2339 }
2340
2341 static int pkt_seq_open(struct inode *inode, struct file *file)
2342 {
2343         return single_open(file, pkt_seq_show, PDE(inode)->data);
2344 }
2345
2346 static struct file_operations pkt_proc_fops = {
2347         .open   = pkt_seq_open,
2348         .read   = seq_read,
2349         .llseek = seq_lseek,
2350         .release = single_release
2351 };
2352
2353 static int pkt_new_dev(struct pktcdvd_device *pd, dev_t dev)
2354 {
2355         int i;
2356         int ret = 0;
2357         char b[BDEVNAME_SIZE];
2358         struct proc_dir_entry *proc;
2359         struct block_device *bdev;
2360
2361         if (pd->pkt_dev == dev) {
2362                 printk("pktcdvd: Recursive setup not allowed\n");
2363                 return -EBUSY;
2364         }
2365         for (i = 0; i < MAX_WRITERS; i++) {
2366                 struct pktcdvd_device *pd2 = pkt_devs[i];
2367                 if (!pd2)
2368                         continue;
2369                 if (pd2->bdev->bd_dev == dev) {
2370                         printk("pktcdvd: %s already setup\n", bdevname(pd2->bdev, b));
2371                         return -EBUSY;
2372                 }
2373                 if (pd2->pkt_dev == dev) {
2374                         printk("pktcdvd: Can't chain pktcdvd devices\n");
2375                         return -EBUSY;
2376                 }
2377         }
2378
2379         bdev = bdget(dev);
2380         if (!bdev)
2381                 return -ENOMEM;
2382         ret = blkdev_get(bdev, FMODE_READ, O_RDONLY | O_NONBLOCK);
2383         if (ret)
2384                 return ret;
2385
2386         /* This is safe, since we have a reference from open(). */
2387         __module_get(THIS_MODULE);
2388
2389         pd->bdev = bdev;
2390         set_blocksize(bdev, CD_FRAMESIZE);
2391
2392         pkt_init_queue(pd);
2393
2394         atomic_set(&pd->cdrw.pending_bios, 0);
2395         pd->cdrw.thread = kthread_run(kcdrwd, pd, "%s", pd->name);
2396         if (IS_ERR(pd->cdrw.thread)) {
2397                 printk("pktcdvd: can't start kernel thread\n");
2398                 ret = -ENOMEM;
2399                 goto out_mem;
2400         }
2401
2402         proc = create_proc_entry(pd->name, 0, pkt_proc);
2403         if (proc) {
2404                 proc->data = pd;
2405                 proc->proc_fops = &pkt_proc_fops;
2406         }
2407         DPRINTK("pktcdvd: writer %s mapped to %s\n", pd->name, bdevname(bdev, b));
2408         return 0;
2409
2410 out_mem:
2411         blkdev_put(bdev);
2412         /* This is safe: open() is still holding a reference. */
2413         module_put(THIS_MODULE);
2414         return ret;
2415 }
2416
2417 static int pkt_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2418 {
2419         struct pktcdvd_device *pd = inode->i_bdev->bd_disk->private_data;
2420
2421         VPRINTK("pkt_ioctl: cmd %x, dev %d:%d\n", cmd, imajor(inode), iminor(inode));
2422
2423         switch (cmd) {
2424         /*
2425          * forward selected CDROM ioctls to CD-ROM, for UDF
2426          */
2427         case CDROMMULTISESSION:
2428         case CDROMREADTOCENTRY:
2429         case CDROM_LAST_WRITTEN:
2430         case CDROM_SEND_PACKET:
2431         case SCSI_IOCTL_SEND_COMMAND:
2432                 return blkdev_ioctl(pd->bdev->bd_inode, file, cmd, arg);
2433
2434         case CDROMEJECT:
2435                 /*
2436                  * The door gets locked when the device is opened, so we
2437                  * have to unlock it or else the eject command fails.
2438                  */
2439                 pkt_lock_door(pd, 0);
2440                 return blkdev_ioctl(pd->bdev->bd_inode, file, cmd, arg);
2441
2442         default:
2443                 printk("pktcdvd: Unknown ioctl for %s (%x)\n", pd->name, cmd);
2444                 return -ENOTTY;
2445         }
2446
2447         return 0;
2448 }
2449
2450 static int pkt_media_changed(struct gendisk *disk)
2451 {
2452         struct pktcdvd_device *pd = disk->private_data;
2453         struct gendisk *attached_disk;
2454
2455         if (!pd)
2456                 return 0;
2457         if (!pd->bdev)
2458                 return 0;
2459         attached_disk = pd->bdev->bd_disk;
2460         if (!attached_disk)
2461                 return 0;
2462         return attached_disk->fops->media_changed(attached_disk);
2463 }
2464
2465 static struct block_device_operations pktcdvd_ops = {
2466         .owner =                THIS_MODULE,
2467         .open =                 pkt_open,
2468         .release =              pkt_close,
2469         .ioctl =                pkt_ioctl,
2470         .media_changed =        pkt_media_changed,
2471 };
2472
2473 /*
2474  * Set up mapping from pktcdvd device to CD-ROM device.
2475  */
2476 static int pkt_setup_dev(struct pkt_ctrl_command *ctrl_cmd)
2477 {
2478         int idx;
2479         int ret = -ENOMEM;
2480         struct pktcdvd_device *pd;
2481         struct gendisk *disk;
2482         dev_t dev = new_decode_dev(ctrl_cmd->dev);
2483
2484         for (idx = 0; idx < MAX_WRITERS; idx++)
2485                 if (!pkt_devs[idx])
2486                         break;
2487         if (idx == MAX_WRITERS) {
2488                 printk("pktcdvd: max %d writers supported\n", MAX_WRITERS);
2489                 return -EBUSY;
2490         }
2491
2492         pd = kzalloc(sizeof(struct pktcdvd_device), GFP_KERNEL);
2493         if (!pd)
2494                 return ret;
2495
2496         pd->rb_pool = mempool_create(PKT_RB_POOL_SIZE, pkt_rb_alloc, pkt_rb_free, NULL);
2497         if (!pd->rb_pool)
2498                 goto out_mem;
2499
2500         disk = alloc_disk(1);
2501         if (!disk)
2502                 goto out_mem;
2503         pd->disk = disk;
2504
2505         INIT_LIST_HEAD(&pd->cdrw.pkt_free_list);
2506         INIT_LIST_HEAD(&pd->cdrw.pkt_active_list);
2507         spin_lock_init(&pd->cdrw.active_list_lock);
2508
2509         spin_lock_init(&pd->lock);
2510         spin_lock_init(&pd->iosched.lock);
2511         sprintf(pd->name, "pktcdvd%d", idx);
2512         init_waitqueue_head(&pd->wqueue);
2513         pd->bio_queue = RB_ROOT;
2514
2515         disk->major = pkt_major;
2516         disk->first_minor = idx;
2517         disk->fops = &pktcdvd_ops;
2518         disk->flags = GENHD_FL_REMOVABLE;
2519         sprintf(disk->disk_name, "pktcdvd%d", idx);
2520         disk->private_data = pd;
2521         disk->queue = blk_alloc_queue(GFP_KERNEL);
2522         if (!disk->queue)
2523                 goto out_mem2;
2524
2525         pd->pkt_dev = MKDEV(disk->major, disk->first_minor);
2526         ret = pkt_new_dev(pd, dev);
2527         if (ret)
2528                 goto out_new_dev;
2529
2530         add_disk(disk);
2531         pkt_devs[idx] = pd;
2532         ctrl_cmd->pkt_dev = new_encode_dev(pd->pkt_dev);
2533         return 0;
2534
2535 out_new_dev:
2536         blk_put_queue(disk->queue);
2537 out_mem2:
2538         put_disk(disk);
2539 out_mem:
2540         if (pd->rb_pool)
2541                 mempool_destroy(pd->rb_pool);
2542         kfree(pd);
2543         return ret;
2544 }
2545
2546 /*
2547  * Tear down mapping from pktcdvd device to CD-ROM device.
2548  */
2549 static int pkt_remove_dev(struct pkt_ctrl_command *ctrl_cmd)
2550 {
2551         struct pktcdvd_device *pd;
2552         int idx;
2553         dev_t pkt_dev = new_decode_dev(ctrl_cmd->pkt_dev);
2554
2555         for (idx = 0; idx < MAX_WRITERS; idx++) {
2556                 pd = pkt_devs[idx];
2557                 if (pd && (pd->pkt_dev == pkt_dev))
2558                         break;
2559         }
2560         if (idx == MAX_WRITERS) {
2561                 DPRINTK("pktcdvd: dev not setup\n");
2562                 return -ENXIO;
2563         }
2564
2565         if (pd->refcnt > 0)
2566                 return -EBUSY;
2567
2568         if (!IS_ERR(pd->cdrw.thread))
2569                 kthread_stop(pd->cdrw.thread);
2570
2571         blkdev_put(pd->bdev);
2572
2573         remove_proc_entry(pd->name, pkt_proc);
2574         DPRINTK("pktcdvd: writer %s unmapped\n", pd->name);
2575
2576         del_gendisk(pd->disk);
2577         blk_put_queue(pd->disk->queue);
2578         put_disk(pd->disk);
2579
2580         pkt_devs[idx] = NULL;
2581         mempool_destroy(pd->rb_pool);
2582         kfree(pd);
2583
2584         /* This is safe: open() is still holding a reference. */
2585         module_put(THIS_MODULE);
2586         return 0;
2587 }
2588
2589 static void pkt_get_status(struct pkt_ctrl_command *ctrl_cmd)
2590 {
2591         struct pktcdvd_device *pd = pkt_find_dev_from_minor(ctrl_cmd->dev_index);
2592         if (pd) {
2593                 ctrl_cmd->dev = new_encode_dev(pd->bdev->bd_dev);
2594                 ctrl_cmd->pkt_dev = new_encode_dev(pd->pkt_dev);
2595         } else {
2596                 ctrl_cmd->dev = 0;
2597                 ctrl_cmd->pkt_dev = 0;
2598         }
2599         ctrl_cmd->num_devices = MAX_WRITERS;
2600 }
2601
2602 static int pkt_ctl_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
2603 {
2604         void __user *argp = (void __user *)arg;
2605         struct pkt_ctrl_command ctrl_cmd;
2606         int ret = 0;
2607
2608         if (cmd != PACKET_CTRL_CMD)
2609                 return -ENOTTY;
2610
2611         if (copy_from_user(&ctrl_cmd, argp, sizeof(struct pkt_ctrl_command)))
2612                 return -EFAULT;
2613
2614         switch (ctrl_cmd.command) {
2615         case PKT_CTRL_CMD_SETUP:
2616                 if (!capable(CAP_SYS_ADMIN))
2617                         return -EPERM;
2618                 down(&ctl_mutex);
2619                 ret = pkt_setup_dev(&ctrl_cmd);
2620                 up(&ctl_mutex);
2621                 break;
2622         case PKT_CTRL_CMD_TEARDOWN:
2623                 if (!capable(CAP_SYS_ADMIN))
2624                         return -EPERM;
2625                 down(&ctl_mutex);
2626                 ret = pkt_remove_dev(&ctrl_cmd);
2627                 up(&ctl_mutex);
2628                 break;
2629         case PKT_CTRL_CMD_STATUS:
2630                 down(&ctl_mutex);
2631                 pkt_get_status(&ctrl_cmd);
2632                 up(&ctl_mutex);
2633                 break;
2634         default:
2635                 return -ENOTTY;
2636         }
2637
2638         if (copy_to_user(argp, &ctrl_cmd, sizeof(struct pkt_ctrl_command)))
2639                 return -EFAULT;
2640         return ret;
2641 }
2642
2643
2644 static struct file_operations pkt_ctl_fops = {
2645         .ioctl   = pkt_ctl_ioctl,
2646         .owner   = THIS_MODULE,
2647 };
2648
2649 static struct miscdevice pkt_misc = {
2650         .minor          = MISC_DYNAMIC_MINOR,
2651         .name           = "pktcdvd",
2652         .devfs_name     = "pktcdvd/control",
2653         .fops           = &pkt_ctl_fops
2654 };
2655
2656 static int __init pkt_init(void)
2657 {
2658         int ret;
2659
2660         psd_pool = mempool_create(PSD_POOL_SIZE, psd_pool_alloc, psd_pool_free, NULL);
2661         if (!psd_pool)
2662                 return -ENOMEM;
2663
2664         ret = register_blkdev(pkt_major, "pktcdvd");
2665         if (ret < 0) {
2666                 printk("pktcdvd: Unable to register block device\n");
2667                 goto out2;
2668         }
2669         if (!pkt_major)
2670                 pkt_major = ret;
2671
2672         ret = misc_register(&pkt_misc);
2673         if (ret) {
2674                 printk("pktcdvd: Unable to register misc device\n");
2675                 goto out;
2676         }
2677
2678         init_MUTEX(&ctl_mutex);
2679
2680         pkt_proc = proc_mkdir("pktcdvd", proc_root_driver);
2681
2682         return 0;
2683
2684 out:
2685         unregister_blkdev(pkt_major, "pktcdvd");
2686 out2:
2687         mempool_destroy(psd_pool);
2688         return ret;
2689 }
2690
2691 static void __exit pkt_exit(void)
2692 {
2693         remove_proc_entry("pktcdvd", proc_root_driver);
2694         misc_deregister(&pkt_misc);
2695         unregister_blkdev(pkt_major, "pktcdvd");
2696         mempool_destroy(psd_pool);
2697 }
2698
2699 MODULE_DESCRIPTION("Packet writing layer for CD/DVD drives");
2700 MODULE_AUTHOR("Jens Axboe <axboe@suse.de>");
2701 MODULE_LICENSE("GPL");
2702
2703 module_init(pkt_init);
2704 module_exit(pkt_exit);