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