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