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