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