1/*
2 * printer.c  Version 0.11
3 *
4 * Copyright (c) 1999 Michael Gee	<michael@linuxspecific.com>
5 * Copyright (c) 1999 Pavel Machek	<pavel@suse.cz>
6 * Copyright (c) 2000 Randy Dunlap	<randy.dunlap@intel.com>
7 * Copyright (c) 2000 Vojtech Pavlik	<vojtech@suse.cz>
8 # Copyright (c) 2001 Pete Zaitcev	<zaitcev@redhat.com>
9 # Copyright (c) 2001 David Paschal	<paschal@rcsis.com>
10 *
11 * USB Printer Device Class driver for USB printers and printer cables
12 *
13 * Sponsored by SuSE
14 *
15 * ChangeLog:
16 *	v0.1 - thorough cleaning, URBification, almost a rewrite
17 *	v0.2 - some more cleanups
18 *	v0.3 - cleaner again, waitqueue fixes
19 *	v0.4 - fixes in unidirectional mode
20 *	v0.5 - add DEVICE_ID string support
21 *	v0.6 - never time out
22 *	v0.7 - fixed bulk-IN read and poll (David Paschal)
23 *	v0.8 - add devfs support
24 *	v0.9 - fix unplug-while-open paths
25 *	v0.10- remove sleep_on, fix error on oom (oliver@neukum.org)
26 *	v0.11 - add proto_bias option (Pete Zaitcev)
27 *	v0.12 - add hpoj.sourceforge.net ioctls (David Paschal)
28 *	v0.13 - alloc space for statusbuf (<status> not on stack);
29 *		use usb_buffer_alloc() for read buf & write buf;
30 */
31
32/*
33 * This program is free software; you can redistribute it and/or modify
34 * it under the terms of the GNU General Public License as published by
35 * the Free Software Foundation; either version 2 of the License, or
36 * (at your option) any later version.
37 *
38 * This program is distributed in the hope that it will be useful,
39 * but WITHOUT ANY WARRANTY; without even the implied warranty of
40 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
41 * GNU General Public License for more details.
42 *
43 * You should have received a copy of the GNU General Public License
44 * along with this program; if not, write to the Free Software
45 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
46 */
47
48#include <linux/module.h>
49#include <linux/kernel.h>
50#include <linux/sched.h>
51#include <linux/smp_lock.h>
52#include <linux/signal.h>
53#include <linux/poll.h>
54#include <linux/init.h>
55#include <linux/slab.h>
56#include <linux/lp.h>
57#include <linux/devfs_fs_kernel.h>
58#undef DEBUG
59#include <linux/usb.h>
60
61
62/* Added by PaN */
63#include <linux/proc_fs.h>
64#include <asm/uaccess.h>
65// End PaN
66
67/* Added by PaN */
68struct print_buffer
69{
70	int len;
71	char *buf;
72};
73#define MODULE_NAME "usblp"
74#define MAX_CLASS_NAME  16
75#define MAX_MFR         16
76#define MAX_MODEL       32
77#define MAX_DESCRIPT    64
78#define MAX_STATUS_TYPE 6
79
80static struct proc_dir_entry *usblp_dir, *usblpid_file;
81struct parport_splink_device_info {
82	char class_name[MAX_CLASS_NAME];
83	char mfr[MAX_MFR];
84	char model[MAX_MODEL];
85	char description[MAX_DESCRIPT];
86};
87static char *usblp_status_type[MAX_STATUS_TYPE]={ "Lexmark", "Canon", "Hp", "Epson", "EPSON", NULL};
88static int usblp_status_maping[MAX_STATUS_TYPE][4]={ {0,0,0,0},
89				       		     {0, LP_POUTPA, LP_PERRORP, LP_PBUSY},
90				       		     {0,0,0,0},
91				       		     {0,0,0,0},
92				       		     {0,0,0,0},
93				       		     {0,0,0,0}};
94
95static struct parport_splink_device_info usblpid_info;
96struct parport_splink_device_info prn_info_tmp, *prn_info; // Added by JYWeng 20031212:
97char *strunknown="unknown"; // Added by JYWeng 20031212:
98void parseKeywords(char *str_dev_id, char *keyword1, char *keyword2, char *prn_info_data, char *usblpid_info_data);// Added by JYWeng 20031212:
99
100static ssize_t usblp_write(struct file *file, const char *buffer, size_t count, loff_t *ppos);
101static ssize_t usblp_read(struct file *file, char *buffer, size_t count, loff_t *ppos);
102static int usblp_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg);
103// END PaN
104
105/*
106 * Version Information
107 */
108#define DRIVER_VERSION "v0.13"
109#define DRIVER_AUTHOR "Michael Gee, Pavel Machek, Vojtech Pavlik, Randy Dunlap, Pete Zaitcev, David Paschal"
110#define DRIVER_DESC "USB Printer Device Class driver"
111
112#define USBLP_BUF_SIZE		8192
113#define USBLP_DEVICE_ID_SIZE	1024
114
115/****************add by JY 20031118*************************************/
116#define LPGETID                 0x0610		/* get printer's device ID */
117#define LPWRITEDATA     0x0613  /* write data to printer */
118#define LPWRITEADDR     0x0614  /* write address to printer */
119#define LPREADDATA      0x0615  /* read data from pinter */
120#define LPREADADDR      0x0616  /* read address from pinter */
121#define DEVICE_ID_SIZE	1024
122/*******************************************************/
123
124/* ioctls: */
125#define LPGETSTATUS		0x060b		/* same as in drivers/char/lp.c */
126#define IOCNR_GET_DEVICE_ID		1
127#define IOCNR_GET_PROTOCOLS		2
128#define IOCNR_SET_PROTOCOL		3
129#define IOCNR_HP_SET_CHANNEL		4
130#define IOCNR_GET_BUS_ADDRESS		5
131#define IOCNR_GET_VID_PID		6
132/* Get device_id string: */
133#define LPIOC_GET_DEVICE_ID(len) _IOC(_IOC_READ, 'P', IOCNR_GET_DEVICE_ID, len)
134/* The following ioctls were added for http://hpoj.sourceforge.net: */
135/* Get two-int array:
136 * [0]=current protocol (1=7/1/1, 2=7/1/2, 3=7/1/3),
137 * [1]=supported protocol mask (mask&(1<<n)!=0 means 7/1/n supported): */
138#define LPIOC_GET_PROTOCOLS(len) _IOC(_IOC_READ, 'P', IOCNR_GET_PROTOCOLS, len)
139/* Set protocol (arg: 1=7/1/1, 2=7/1/2, 3=7/1/3): */
140#define LPIOC_SET_PROTOCOL _IOC(_IOC_WRITE, 'P', IOCNR_SET_PROTOCOL, 0)
141/* Set channel number (HP Vendor-specific command): */
142#define LPIOC_HP_SET_CHANNEL _IOC(_IOC_WRITE, 'P', IOCNR_HP_SET_CHANNEL, 0)
143/* Get two-int array: [0]=bus number, [1]=device address: */
144#define LPIOC_GET_BUS_ADDRESS(len) _IOC(_IOC_READ, 'P', IOCNR_GET_BUS_ADDRESS, len)
145/* Get two-int array: [0]=vendor ID, [1]=product ID: */
146#define LPIOC_GET_VID_PID(len) _IOC(_IOC_READ, 'P', IOCNR_GET_VID_PID, len)
147
148/*
149 * A DEVICE_ID string may include the printer's serial number.
150 * It should end with a semi-colon (';').
151 * An example from an HP 970C DeskJet printer is (this is one long string,
152 * with the serial number changed):
153MFG:HEWLETT-PACKARD;MDL:DESKJET 970C;CMD:MLC,PCL,PML;CLASS:PRINTER;DESCRIPTION:Hewlett-Packard DeskJet 970C;SERN:US970CSEPROF;VSTATUS:$HB0$NC0,ff,DN,IDLE,CUT,K1,C0,DP,NR,KP000,CP027;VP:0800,FL,B0;VJ:                    ;
154 */
155
156/*
157 * USB Printer Requests
158 */
159
160#define USBLP_REQ_GET_ID			0x00
161#define USBLP_REQ_GET_STATUS			0x01
162#define USBLP_REQ_RESET				0x02
163#define USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST	0x00	/* HP Vendor-specific */
164
165#define USBLP_MINORS		16
166#define USBLP_MINOR_BASE	0
167
168#define USBLP_WRITE_TIMEOUT	(5*HZ)			/* 5 seconds */
169
170#define USBLP_FIRST_PROTOCOL	1
171#define USBLP_LAST_PROTOCOL	3
172#define USBLP_MAX_PROTOCOLS	(USBLP_LAST_PROTOCOL+1)
173
174/*
175 * some arbitrary status buffer size;
176 * need a status buffer that is allocated via kmalloc(), not on stack
177 */
178#define STATUS_BUF_SIZE		8
179
180struct usblp {
181	struct usb_device 	*dev;			/* USB device */
182	devfs_handle_t		devfs;			/* devfs device */
183	struct semaphore	sem;			/* locks this struct, especially "dev" */
184	char			*writebuf;		/* write transfer_buffer */
185	char			*readbuf;		/* read transfer_buffer */
186	char			*statusbuf;		/* status transfer_buffer */
187	struct urb		*readurb, *writeurb;	/* The urbs */
188	wait_queue_head_t	wait;			/* Zzzzz ... */
189	int			readcount;		/* Counter for reads */
190	int			ifnum;			/* Interface number */
191	/* Alternate-setting numbers and endpoints for each protocol
192	 * (7/1/{index=1,2,3}) that the device supports: */
193	struct {
194		int				alt_setting;
195		struct usb_endpoint_descriptor	*epwrite;
196		struct usb_endpoint_descriptor	*epread;
197	}			protocol[USBLP_MAX_PROTOCOLS];
198	int			current_protocol;
199	int			minor;			/* minor number of device */
200	int			wcomplete;		/* writing is completed */
201	int			rcomplete;		/* reading is completed */
202	unsigned int		quirks;			/* quirks flags */
203	unsigned char		used;			/* True if open */
204	unsigned char		present;		/* True if not disconnected */
205	unsigned char		bidir;			/* interface is bidirectional */
206	unsigned char		*device_id_string;	/* IEEE 1284 DEVICE ID string (ptr) */
207							/* first 2 bytes are (big-endian) length */
208};
209
210#ifdef DEBUG
211static void usblp_dump(struct usblp *usblp) {
212	int p;
213
214	dbg("usblp=0x%p", usblp);
215	dbg("dev=0x%p", usblp->dev);
216	dbg("present=%d", usblp->present);
217	dbg("readbuf=0x%p", usblp->readbuf);
218	dbg("writebuf=0x%p", usblp->writebuf);
219	dbg("readurb=0x%p", usblp->readurb);
220	dbg("writeurb=0x%p", usblp->writeurb);
221	dbg("readcount=%d", usblp->readcount);
222	dbg("ifnum=%d", usblp->ifnum);
223    for (p = USBLP_FIRST_PROTOCOL; p <= USBLP_LAST_PROTOCOL; p++) {
224	dbg("protocol[%d].alt_setting=%d", p, usblp->protocol[p].alt_setting);
225	dbg("protocol[%d].epwrite=%p", p, usblp->protocol[p].epwrite);
226	dbg("protocol[%d].epread=%p", p, usblp->protocol[p].epread);
227    }
228	dbg("current_protocol=%d", usblp->current_protocol);
229	dbg("minor=%d", usblp->minor);
230	dbg("wcomplete=%d", usblp->wcomplete);
231	dbg("rcomplete=%d", usblp->rcomplete);
232	dbg("quirks=%d", usblp->quirks);
233	dbg("used=%d", usblp->used);
234	dbg("bidir=%d", usblp->bidir);
235	dbg("device_id_string=\"%s\"",
236		usblp->device_id_string ?
237			usblp->device_id_string + 2 :
238			(unsigned char *)"(null)");
239}
240#endif
241
242extern devfs_handle_t usb_devfs_handle;			/* /dev/usb dir. */
243
244static struct usblp *usblp_table[USBLP_MINORS];
245
246/* Quirks: various printer quirks are handled by this table & its flags. */
247
248struct quirk_printer_struct {
249	__u16 vendorId;
250	__u16 productId;
251	unsigned int quirks;
252};
253
254#define USBLP_QUIRK_BIDIR	0x1	/* reports bidir but requires unidirectional mode (no INs/reads) */
255#define USBLP_QUIRK_USB_INIT	0x2	/* needs vendor USB init string */
256
257static struct quirk_printer_struct quirk_printers[] = {
258	{ 0x03f0, 0x0004, USBLP_QUIRK_BIDIR }, /* HP DeskJet 895C */
259	{ 0x03f0, 0x0104, USBLP_QUIRK_BIDIR }, /* HP DeskJet 880C */
260	{ 0x03f0, 0x0204, USBLP_QUIRK_BIDIR }, /* HP DeskJet 815C */
261	{ 0x03f0, 0x0304, USBLP_QUIRK_BIDIR }, /* HP DeskJet 810C/812C */
262	{ 0x03f0, 0x0404, USBLP_QUIRK_BIDIR }, /* HP DeskJet 830C */
263	{ 0x03f0, 0x0504, USBLP_QUIRK_BIDIR }, /* HP DeskJet 885C */
264	{ 0x03f0, 0x0604, USBLP_QUIRK_BIDIR }, /* HP DeskJet 840C */
265	{ 0x03f0, 0x0804, USBLP_QUIRK_BIDIR }, /* HP DeskJet 816C */
266	{ 0x03f0, 0x1104, USBLP_QUIRK_BIDIR }, /* HP Deskjet 959C */
267	{ 0x0409, 0xefbe, USBLP_QUIRK_BIDIR }, /* NEC Picty900 (HP OEM) */
268	{ 0x0409, 0xbef4, USBLP_QUIRK_BIDIR }, /* NEC Picty760 (HP OEM) */
269	{ 0x0409, 0xf0be, USBLP_QUIRK_BIDIR }, /* NEC Picty920 (HP OEM) */
270	{ 0x0409, 0xf1be, USBLP_QUIRK_BIDIR }, /* NEC Picty800 (HP OEM) */
271	{ 0, 0 }
272};
273
274static int usblp_select_alts(struct usblp *usblp);
275static int usblp_set_protocol(struct usblp *usblp, int protocol);
276static int usblp_cache_device_id_string(struct usblp *usblp);
277
278
279/*
280 * Functions for usblp control messages.
281 */
282
283static int usblp_ctrl_msg(struct usblp *usblp, int request, int type, int dir, int recip, int value, void *buf, int len)
284{
285	int retval = usb_control_msg(usblp->dev,
286		dir ? usb_rcvctrlpipe(usblp->dev, 0) : usb_sndctrlpipe(usblp->dev, 0),
287		request, type | dir | recip, value, usblp->ifnum, buf, len, USBLP_WRITE_TIMEOUT);
288	dbg("usblp_control_msg: rq: 0x%02x dir: %d recip: %d value: %d len: %#x result: %d",
289		request, !!dir, recip, value, len, retval);
290	return retval < 0 ? retval : 0;
291}
292
293#define usblp_read_status(usblp, status)\
294	usblp_ctrl_msg(usblp, USBLP_REQ_GET_STATUS, USB_TYPE_CLASS, USB_DIR_IN, USB_RECIP_INTERFACE, 0, status, 1)
295#define usblp_get_id(usblp, config, id, maxlen)\
296	usblp_ctrl_msg(usblp, USBLP_REQ_GET_ID, USB_TYPE_CLASS, USB_DIR_IN, USB_RECIP_INTERFACE, config, id, maxlen)
297#define usblp_reset(usblp)\
298	usblp_ctrl_msg(usblp, USBLP_REQ_RESET, USB_TYPE_CLASS, USB_DIR_OUT, USB_RECIP_OTHER, 0, NULL, 0)
299
300#define usblp_hp_channel_change_request(usblp, channel, buffer) \
301	usblp_ctrl_msg(usblp, USBLP_REQ_HP_CHANNEL_CHANGE_REQUEST, USB_TYPE_VENDOR, USB_DIR_IN, USB_RECIP_INTERFACE, channel, buffer, 1)
302
303/*
304 * See the description for usblp_select_alts() below for the usage
305 * explanation.  Look into your /proc/bus/usb/devices and dmesg in
306 * case of any trouble.
307 */
308static int proto_bias = -1;
309
310/*
311 * URB callback.
312 */
313
314static void usblp_bulk_read(struct urb *urb)
315{
316	struct usblp *usblp = urb->context;
317
318	if (!usblp || !usblp->dev || !usblp->used || !usblp->present)
319		return;
320
321	if (unlikely(urb->status))
322		warn("usblp%d: nonzero read/write bulk status received: %d",
323			usblp->minor, urb->status);
324	usblp->rcomplete = 1;
325	wake_up_interruptible(&usblp->wait);
326}
327
328static void usblp_bulk_write(struct urb *urb)
329{
330	struct usblp *usblp = urb->context;
331
332	if (!usblp || !usblp->dev || !usblp->used || !usblp->present)
333		return;
334
335	if (unlikely(urb->status))
336		warn("usblp%d: nonzero read/write bulk status received: %d",
337			usblp->minor, urb->status);
338	usblp->wcomplete = 1;
339	wake_up_interruptible(&usblp->wait);
340}
341
342/*
343 * Get and print printer errors.
344 */
345
346static char *usblp_messages[] = { "ok", "out of paper", "off-line", "on fire" };
347
348
349/* Added by PaN */
350static int proc_read_usblpid(char *page, char **start, off_t off, int count, int *eof, void *data)
351{
352	int len=0;
353
354	len=sprintf(page, "Manufacturer=%s\nModel=%s\nClass=%s\nDescription=%s\n\n",
355	usblpid_info.mfr, usblpid_info.model, usblpid_info.class_name, usblpid_info.description);
356
357	return len;
358}
359
360static int proc_get_usblpid(struct usblp *usblp)
361{
362//JYWeng 20031212: set this as global	char *strtmp, *str_dev_id, *strunknown="unknown"; // Added by PaN
363	char *strtmp, *str_dev_id; // Added by PaN: JYWeng 20031212: modified from the above
364	int i, unk = 0; // Added by PaN
365	int length, err;
366	int retval = 0;
367
368	prn_info= &prn_info_tmp; // Added by JYWeng 20031212:
369
370
371	err = usblp_get_id(usblp, 0, usblp->device_id_string, DEVICE_ID_SIZE - 1);
372
373	if (err < 0) {
374		dbg ("usblp%d: error = %d reading IEEE-1284 Device ID string",
375			usblp->minor, err);
376			usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
377		retval = -EIO;
378		goto done;
379	}
380
381	length = (usblp->device_id_string[0] << 8) + usblp->device_id_string[1]; /* big-endian */
382	if (length < DEVICE_ID_SIZE)
383		usblp->device_id_string[length] = '\0';
384	else
385		usblp->device_id_string[DEVICE_ID_SIZE - 1] = '\0';
386
387	dbg ("usblp%d Device ID string [%d]='%s'",
388		usblp->minor, length, &usblp->device_id_string[2]);
389	info ("usblp%d Device ID string [%d]='%s'",
390		usblp->minor, length, &usblp->device_id_string[2]);
391
392	str_dev_id = &usblp->device_id_string[2];
393#if 1//JYWeng 20031212: modified from below
394				parseKeywords(str_dev_id, "MFG:", "MANUFACTURE:", prn_info->mfr, usblpid_info.mfr);
395				parseKeywords(str_dev_id, "MDL:", "MODEL:", prn_info->model, usblpid_info.model);
396				parseKeywords(str_dev_id, "CLS:", "CLASS:", prn_info->class_name, usblpid_info.class_name);
397				parseKeywords(str_dev_id, "DES:", "DESCRIPTION:", prn_info->description, usblpid_info.description);
398#else
399	if ( (strtmp = strstr(str_dev_id, "MFG:")) == NULL) {
400		if ( (strtmp = strstr(str_dev_id, "MANUFACTURE:")) == NULL) {
401			for (i=0; i<7; i++) {
402				usblpid_info.mfr[i] = strunknown[i];
403			}
404			usblpid_info.mfr[i]='\0';
405			unk=1;
406		}
407		else
408			strtmp+=12;
409	}
410	else
411		strtmp+=4;
412
413	i=0;
414	while (unk && strtmp[i] != ';') {
415		usblpid_info.mfr[i] = strtmp[i];
416		i++;
417	}
418	usblpid_info.mfr[i]='\0';
419	unk=0;
420
421	if ( (strtmp = strstr(str_dev_id, "MDL:")) == NULL) {
422		if ( (strtmp = strstr(str_dev_id, "MODEL:")) == NULL) {
423			for (i=0; i<7; i++) {
424				usblpid_info.model[i] = strunknown[i];
425			}
426			usblpid_info.model[i]='\0';
427			unk=1;
428		}
429		else
430			strtmp+=6;
431		}
432	else
433		strtmp+=4;
434
435	i=0;
436	while (unk==0 && strtmp[i] != ';') {
437		usblpid_info.model[i] = strtmp[i];
438		i++;
439	}
440	usblpid_info.model[i]='\0';
441	unk=0;
442
443	if ( (strtmp = strstr(str_dev_id, "CLS:")) == NULL) {
444		if ( (strtmp = strstr(str_dev_id, "CLASS:")) == NULL) {
445			for (i=0; i<7; i++) {
446				usblpid_info.class_name[i] = strunknown[i];
447			}
448			usblpid_info.class_name[i]='\0';
449			unk=1;
450		}
451		else
452			strtmp+=6;
453	}
454	else
455		strtmp+=4;
456
457	i=0;
458	while (unk==0 && strtmp[i] != ';') {
459		usblpid_info.class_name[i]= strtmp[i];
460		i++;
461	}
462	usblpid_info.class_name[i]='\0';
463	unk=0;
464
465	if ( (strtmp = strstr(str_dev_id, "DES:")) == NULL) {
466		if ( (strtmp = strstr(str_dev_id, "DESCRIPTION:")) == NULL) {
467			for (i=0; i<7; i++) {
468				usblpid_info.description[i] = strunknown[i];
469			}
470			usblpid_info.description[i]='\0';
471			unk=1;
472		}
473		else
474			strtmp+=12;
475	}
476	else
477		strtmp+=4;
478
479	i=0;
480	while (unk==0 && strtmp[i] != ';') {
481			usblpid_info.description[i]= strtmp[i];
482			i++;
483	}
484	usblpid_info.description[i]='\0';
485#endif//JYWeng 20031212: end
486
487done:
488	return retval;
489
490}
491// End PaN
492
493
494static int usblp_check_status(struct usblp *usblp, int err)
495{
496	unsigned char status, newerr = 0;
497	int error;
498
499	error = usblp_read_status (usblp, usblp->statusbuf);
500	if (error < 0) {
501		err("usblp%d: error %d reading printer status",
502			usblp->minor, error);
503		return 0;
504	}
505
506	status = *usblp->statusbuf;
507
508	if (~status & LP_PERRORP)
509		newerr = 3;
510	if (status & LP_POUTPA)
511		newerr = 1;
512	if (~status & LP_PSELECD)
513		newerr = 2;
514
515	if (newerr != err)
516		info("usblp%d: %s", usblp->minor, usblp_messages[newerr]);
517
518	return newerr;
519}
520
521/*
522 * File op functions.
523 */
524
525static int usblp_open(struct inode *inode, struct file *file)
526{
527	int minor = MINOR(inode->i_rdev) - USBLP_MINOR_BASE;
528	struct usblp *usblp;
529	int retval;
530	unsigned int arg = NULL, ioctl_retval; //Added by PaN
531
532	if (minor < 0 || minor >= USBLP_MINORS)
533		return -ENODEV;
534
535	lock_kernel();
536	usblp  = usblp_table[minor];
537
538	retval = -ENODEV;
539	if (!usblp || !usblp->dev || !usblp->present)
540		goto out;
541
542	retval = -EBUSY;
543	if (usblp->used)
544		goto out;
545
546	/*
547	 * TODO: need to implement LP_ABORTOPEN + O_NONBLOCK as in drivers/char/lp.c ???
548	 * This is #if 0-ed because we *don't* want to fail an open
549	 * just because the printer is off-line.
550	 */
551#if 0
552	if ((retval = usblp_check_status(usblp, 0))) {
553		retval = retval > 1 ? -EIO : -ENOSPC;
554		goto out;
555	}
556#else
557	retval = 0;
558#endif
559
560	usblp->used = 1;
561	file->private_data = usblp;
562
563	usblp->writeurb->transfer_buffer_length = 0;
564	usblp->wcomplete = 1; /* we begin writeable */
565	usblp->rcomplete = 0;
566
567	if (usblp->bidir) {
568		usblp->readcount = 0;
569		usblp->readurb->dev = usblp->dev;
570		if (usb_submit_urb(usblp->readurb) < 0) {
571			retval = -EIO;
572			usblp->used = 0;
573			file->private_data = NULL;
574		}
575	}
576
577	/* Added by PaN */
578	if ((ioctl_retval=usblp_ioctl(inode, file, LPGETID, arg)) <0)
579	{
580		// Update device id failed
581	}
582out:
583	unlock_kernel();
584	return retval;
585}
586
587static void usblp_cleanup (struct usblp *usblp)
588{
589	devfs_unregister (usblp->devfs);
590	usblp_table [usblp->minor] = NULL;
591	//info("usblp%d: removed", usblp->minor);
592
593	/* Added by PaN */
594	remove_proc_entry("usblpid", usblp_dir);
595	remove_proc_entry(MODULE_NAME, NULL);
596	/* End PaN */
597
598	kfree (usblp->writebuf);
599	kfree (usblp->readbuf);
600	kfree (usblp->device_id_string);
601	kfree (usblp->statusbuf);
602	usb_free_urb(usblp->writeurb);
603	usb_free_urb(usblp->readurb);
604	kfree (usblp);
605}
606
607static void usblp_unlink_urbs(struct usblp *usblp)
608{
609	usb_unlink_urb(usblp->writeurb);
610	if (usblp->bidir)
611		usb_unlink_urb(usblp->readurb);
612}
613
614static int usblp_release(struct inode *inode, struct file *file)
615{
616	struct usblp *usblp = file->private_data;
617
618	down (&usblp->sem);
619	lock_kernel();
620	usblp->used = 0;
621	if (usblp->present) {
622		usblp_unlink_urbs(usblp);
623		up(&usblp->sem);
624	} else 		/* finish cleanup from disconnect */
625		usblp_cleanup (usblp);
626	unlock_kernel();
627	return 0;
628}
629
630/* No kernel lock - fine */
631static unsigned int usblp_poll(struct file *file, struct poll_table_struct *wait)
632{
633	struct usblp *usblp = file->private_data;
634	poll_wait(file, &usblp->wait, wait);
635 	return ((!usblp->bidir || !usblp->rcomplete) ? 0 : POLLIN  | POLLRDNORM)
636 			       | (!usblp->wcomplete ? 0 : POLLOUT | POLLWRNORM);
637}
638
639static int usblp_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
640{
641	struct usblp *usblp = file->private_data;
642//JYWeng 20031212: set this as global	struct parport_splink_device_info prn_info_tmp, *prn_info; // Added by PaN
643	struct print_buffer user_buf_tmp, *user_buf; // Added by PaN
644//JYWeng 20031212: set this as global	char *strtmp, *str_dev_id, *strunknown="unknown"; // Added by PaN
645	char *strtmp, *str_dev_id; // Added by PaN: JYWeng 20031212: modified from the above
646	//int i, unk=0; // Added by PaN
647	int unk=0; // Added by PaN ---remove declaration of i for i is declared below: JY
648	int length, err, i;
649	unsigned char newChannel;
650	int status;
651	int twoints[2];
652	int retval = 0;
653
654	down (&usblp->sem);
655	if (!usblp->present) {
656		retval = -ENODEV;
657		goto done;
658	}
659
660	if (_IOC_TYPE(cmd) == 'P')	/* new-style ioctl number */
661
662		switch (_IOC_NR(cmd)) {
663
664			case IOCNR_GET_DEVICE_ID: /* get the DEVICE_ID string */
665				if (_IOC_DIR(cmd) != _IOC_READ) {
666					retval = -EINVAL;
667					goto done;
668				}
669
670				length = usblp_cache_device_id_string(usblp);
671				if (length < 0) {
672					retval = length;
673					goto done;
674				}
675				if (length > _IOC_SIZE(cmd))
676					length = _IOC_SIZE(cmd); /* truncate */
677
678				if (copy_to_user((unsigned char *) arg,
679						usblp->device_id_string,
680						(unsigned long) length)) {
681					retval = -EFAULT;
682					goto done;
683				}
684
685				break;
686
687			case IOCNR_GET_PROTOCOLS:
688				if (_IOC_DIR(cmd) != _IOC_READ ||
689				    _IOC_SIZE(cmd) < sizeof(twoints)) {
690					retval = -EINVAL;
691					goto done;
692				}
693
694				twoints[0] = usblp->current_protocol;
695				twoints[1] = 0;
696				for (i = USBLP_FIRST_PROTOCOL;
697				     i <= USBLP_LAST_PROTOCOL; i++) {
698					if (usblp->protocol[i].alt_setting >= 0)
699						twoints[1] |= (1<<i);
700				}
701
702				if (copy_to_user((unsigned char *)arg,
703						(unsigned char *)twoints,
704						sizeof(twoints))) {
705					retval = -EFAULT;
706					goto done;
707				}
708
709				break;
710
711			case IOCNR_SET_PROTOCOL:
712				if (_IOC_DIR(cmd) != _IOC_WRITE) {
713					retval = -EINVAL;
714					goto done;
715				}
716
717#ifdef DEBUG
718				if (arg == -10) {
719					usblp_dump(usblp);
720					break;
721				}
722#endif
723
724				usblp_unlink_urbs(usblp);
725				retval = usblp_set_protocol(usblp, arg);
726				if (retval < 0) {
727					usblp_set_protocol(usblp,
728						usblp->current_protocol);
729				}
730				break;
731
732			case IOCNR_HP_SET_CHANNEL:
733				if (_IOC_DIR(cmd) != _IOC_WRITE ||
734				    usblp->dev->descriptor.idVendor != 0x03F0 ||
735				    usblp->quirks & USBLP_QUIRK_BIDIR) {
736					retval = -EINVAL;
737					goto done;
738				}
739
740				err = usblp_hp_channel_change_request(usblp,
741					arg, &newChannel);
742				if (err < 0) {
743					err("usblp%d: error = %d setting "
744						"HP channel",
745						usblp->minor, err);
746					retval = -EIO;
747					goto done;
748				}
749
750				dbg("usblp%d requested/got HP channel %ld/%d",
751					usblp->minor, arg, newChannel);
752				break;
753
754			case IOCNR_GET_BUS_ADDRESS:
755				if (_IOC_DIR(cmd) != _IOC_READ ||
756				    _IOC_SIZE(cmd) < sizeof(twoints)) {
757					retval = -EINVAL;
758					goto done;
759				}
760
761				twoints[0] = usblp->dev->bus->busnum;
762				twoints[1] = usblp->dev->devnum;
763				if (copy_to_user((unsigned char *)arg,
764						(unsigned char *)twoints,
765						sizeof(twoints))) {
766					retval = -EFAULT;
767					goto done;
768				}
769
770				dbg("usblp%d is bus=%d, device=%d",
771					usblp->minor, twoints[0], twoints[1]);
772				break;
773
774			case IOCNR_GET_VID_PID:
775				if (_IOC_DIR(cmd) != _IOC_READ ||
776				    _IOC_SIZE(cmd) < sizeof(twoints)) {
777					retval = -EINVAL;
778					goto done;
779				}
780
781				twoints[0] = usblp->dev->descriptor.idVendor;
782				twoints[1] = usblp->dev->descriptor.idProduct;
783				if (copy_to_user((unsigned char *)arg,
784						(unsigned char *)twoints,
785						sizeof(twoints))) {
786					retval = -EFAULT;
787					goto done;
788				}
789
790				dbg("usblp%d is VID=0x%4.4X, PID=0x%4.4X",
791					usblp->minor, twoints[0], twoints[1]);
792				break;
793
794			default:
795				retval = -ENOTTY;
796		}
797	else	/* old-style ioctl value */
798		switch (cmd) {
799			/*=================================================================================== PaN */
800			case LPGETID: /* get the DEVICE_ID string */
801				err = usblp_get_id(usblp, 0, usblp->device_id_string, DEVICE_ID_SIZE - 1);
802				if (err < 0) {
803					dbg ("usblp%d: error = %d reading IEEE-1284 Device ID string",
804						usblp->minor, err);
805					usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
806					retval = -EIO;
807					goto done;
808				}
809
810				length = (usblp->device_id_string[0] << 8) + usblp->device_id_string[1]; /* big-endian */
811				if (length < DEVICE_ID_SIZE)
812					usblp->device_id_string[length] = '\0';
813				else
814					usblp->device_id_string[DEVICE_ID_SIZE - 1] = '\0';
815
816				dbg ("usblp%d Device ID string [%d/max %d]='%s'",
817					usblp->minor, length, cmd, &usblp->device_id_string[2]);
818				info ("usblp%d Device ID string [%d/max %d]='%s'",
819					usblp->minor, length, cmd, &usblp->device_id_string[2]);
820
821				str_dev_id = &usblp->device_id_string[2];
822#if 1//JYWeng 20031212: modified from below
823				parseKeywords(str_dev_id, "MFG:", "MANUFACTURE:", prn_info->mfr, usblpid_info.mfr);
824				parseKeywords(str_dev_id, "MDL:", "MODEL:", prn_info->model, usblpid_info.model);
825				parseKeywords(str_dev_id, "CLS:", "CLASS:", prn_info->class_name, usblpid_info.class_name);
826				parseKeywords(str_dev_id, "DES:", "DESCRIPTION:", prn_info->description, usblpid_info.description);
827#else
828				if ( (strtmp = strstr(str_dev_id, "MFG:")) == NULL) {
829					if ( (strtmp = strstr(str_dev_id, "MANUFACTURE:")) == NULL) {
830						for (i=0; i<7; i++) {
831							prn_info->mfr[i]= strunknown[i];
832							usblpid_info.mfr[i] = strunknown[i];
833						}
834						prn_info->mfr[i]= '\0';
835						usblpid_info.mfr[i]='\0';
836						unk=1;
837					}
838					else
839						strtmp+=12;
840				}
841				else
842					strtmp+=4;
843
844				i=0;
845				while (unk==0 && strtmp[i] != ';') {
846					prn_info->mfr[i]= strtmp[i];
847					usblpid_info.mfr[i] = strtmp[i];
848					i++;
849				}
850				prn_info->mfr[i]= '\0';
851				usblpid_info.mfr[i]='\0';
852				unk=0;
853
854				if ( (strtmp = strstr(str_dev_id, "MDL:")) == NULL) {
855					if ( (strtmp = strstr(str_dev_id, "MODEL:")) == NULL) {
856						for (i=0; i<7; i++) {
857							prn_info->model[i]= strunknown[i];
858							usblpid_info.model[i] = strunknown[i];
859						}
860						prn_info->model[i]= '\0';
861						usblpid_info.model[i]='\0';
862						unk=1;
863					}
864					else
865						strtmp+=6;
866				}
867				else
868					strtmp+=4;
869
870				i=0;
871				while (unk==0 && strtmp[i] != ';') {
872					prn_info->model[i]= strtmp[i];
873					usblpid_info.model[i] = strtmp[i];
874					i++;
875				}
876				prn_info->model[i]= '\0';
877				usblpid_info.model[i]='\0';
878				unk=0;
879
880				if ( (strtmp = strstr(str_dev_id, "CLS:")) == NULL) {
881					if ( (strtmp = strstr(str_dev_id, "CLASS:")) == NULL) {
882						for (i=0; i<7; i++) {
883							prn_info->class_name[i]= strunknown[i];
884							usblpid_info.class_name[i] = strunknown[i];
885						}
886						prn_info->class_name[i]= '\0';
887						usblpid_info.class_name[i]='\0';
888						unk=1;
889					}
890					else
891						strtmp+=6;
892				}
893				else
894					strtmp+=4;
895
896				i=0;
897				while (unk==0 && strtmp[i] != ';') {
898					prn_info->class_name[i]= strtmp[i];
899					usblpid_info.class_name[i]= strtmp[i];
900					i++;
901				}
902				prn_info->class_name[i]= '\0';
903				usblpid_info.class_name[i]='\0';
904				unk=0;
905
906				if ( (strtmp = strstr(str_dev_id, "DES:")) == NULL) {
907					if ( (strtmp = strstr(str_dev_id, "DESCRIPTION:")) == NULL) {
908						for (i=0; i<7; i++) {
909							prn_info->description[i]= strunknown[i];
910							usblpid_info.description[i] = strunknown[i];
911						}
912						prn_info->description[i]= '\0';
913						usblpid_info.description[i]='\0';
914						unk=1;
915					}
916					else
917						strtmp+=12;
918				}
919				else
920					strtmp+=4;
921
922				i=0;
923				while (unk==0 && strtmp[i] != ';') {
924						prn_info->description[i]= strtmp[i];
925						usblpid_info.description[i]= strtmp[i];
926						i++;
927				}
928				prn_info->description[i]= '\0';
929				usblpid_info.description[i]='\0';
930#endif//JYWeng 20031212: end
931
932				info("Parsing USBLPID...");
933				if (copy_to_user((unsigned char *) arg,
934						prn_info, (unsigned long) length)) {
935					retval = -EFAULT;
936					goto done;
937				}
938				break;
939
940			case LPREADDATA:
941			        up (&usblp->sem);
942				user_buf = (struct print_buffer *)arg;
943				retval = usblp_read(file, user_buf->buf, user_buf->len, NULL);
944				down (&usblp->sem);
945	                        break;
946
947
948			case LPWRITEDATA:
949			        up (&usblp->sem);
950				user_buf = (struct print_buffer *)arg;
951				retval = usblp_write(file, user_buf->buf, user_buf->len, NULL);
952				down (&usblp->sem);
953	                        break;
954
955			case LPRESET:
956                                usblp_reset(usblp);
957				break;
958
959			case LPGETSTATUS:
960				/* OLD USB Code Removed by PaN for Printer Server
961				if (usblp_read_status(usblp, &status)) {
962					err("usblp%d: failed reading printer status", usblp->minor);
963					retval = -EIO;
964					goto done;
965				}
966				if (copy_to_user ((int *)arg, &status, 2))
967					retval = -EFAULT;
968				*/
969                                status = usblp_check_status(usblp, 0);
970#if 0
971				info("start=%s", usblpid_info.mfr);
972				for (i=0; i< MAX_STATUS_TYPE; i++) {
973				info("compare=%s", usblp_status_type[i]);
974					if ( !( strcmp(usblpid_info.mfr, usblp_status_type[i]) ) )
975						break;
976				}
977				info("%d=%s", i, usblp_status_type[i]);
978				status=usblp_status_maping[i][status];
979				info("STATUS=%x", status);
980#endif
981				status=0;
982				if (copy_to_user ((int *)arg, &status, 2))
983					retval = -EFAULT;
984				break;
985
986/*=================================================================== PaN for Printer Server */
987
988/* Marked by JY 20031118*/
989#if 0
990			case LPGETSTATUS:
991				if (usblp_read_status(usblp, &lpstatus)) {
992					err("usblp%d: failed reading printer status", usblp->minor);
993					retval = -EIO;
994					goto done;
995				}
996				status = lpstatus;
997				if (copy_to_user ((int *)arg, &status, sizeof(int)))
998					retval = -EFAULT;
999				break;
1000#endif
1001/* Marked by JY 20031118*/
1002			default:
1003				retval = -ENOTTY;
1004		}
1005
1006done:
1007	up (&usblp->sem);
1008	return retval;
1009}
1010
1011/*********************************************************
1012** JYWeng 20031212: parsing the information of printers **
1013*********************************************************/
1014void parseKeywords(char *str_dev_id, char *keyword1, char *keyword2, char *prn_info_data, char *usblpid_info_data)
1015{
1016	char *strtmp;
1017	int i, unk = 0;
1018
1019	if ( (strtmp = strstr(str_dev_id, keyword1)) == NULL) {
1020		if ( (strtmp = strstr(str_dev_id, keyword2)) == NULL) {
1021			for (i=0; i<7; i++) {
1022				prn_info_data[i]= strunknown[i];
1023				usblpid_info_data[i] = strunknown[i];
1024			}
1025			prn_info_data[i]= '\0';
1026			usblpid_info_data[i]='\0';
1027			unk=1;
1028
1029			return;
1030		}
1031		else
1032			strtmp+=strlen(keyword2);
1033	}
1034	else
1035		strtmp+=strlen(keyword1);
1036
1037	i=0;
1038	while (unk==0 && strtmp[i] && strtmp[i] != ';') {
1039		prn_info_data[i]= strtmp[i];
1040		usblpid_info_data[i] = strtmp[i];
1041		i++;
1042	}
1043	prn_info_data[i]= '\0';
1044	usblpid_info_data[i]='\0';
1045
1046	return;
1047}
1048
1049static ssize_t usblp_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
1050{
1051	DECLARE_WAITQUEUE(wait, current);
1052	struct usblp *usblp = file->private_data;
1053	int timeout, err = 0;
1054	size_t writecount = 0;
1055
1056	while (writecount < count) {
1057		if (!usblp->wcomplete) {
1058			barrier();
1059			if (file->f_flags & O_NONBLOCK)
1060				return -EAGAIN;
1061
1062			timeout = USBLP_WRITE_TIMEOUT;
1063			add_wait_queue(&usblp->wait, &wait);
1064			while ( 1==1 ) {
1065
1066				if (signal_pending(current)) {
1067					remove_wait_queue(&usblp->wait, &wait);
1068					return writecount ? writecount : -EINTR;
1069				}
1070				set_current_state(TASK_INTERRUPTIBLE);
1071				if (timeout && !usblp->wcomplete) {
1072					timeout = schedule_timeout(timeout);
1073				} else {
1074					set_current_state(TASK_RUNNING);
1075					break;
1076				}
1077			}
1078			remove_wait_queue(&usblp->wait, &wait);
1079		}
1080
1081		down (&usblp->sem);
1082		if (!usblp->present) {
1083			up (&usblp->sem);
1084			return -ENODEV;
1085		}
1086
1087		if (usblp->writeurb->status != 0) {
1088			if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1089				if (!usblp->wcomplete)
1090					err("usblp%d: error %d writing to printer",
1091						usblp->minor, usblp->writeurb->status);
1092				err = usblp->writeurb->status;
1093			} else
1094				err = usblp_check_status(usblp, err);
1095			up (&usblp->sem);
1096
1097			/* if the fault was due to disconnect, let khubd's
1098			 * call to usblp_disconnect() grab usblp->sem ...
1099			 */
1100			return writecount; 	//Added by PaN
1101			//schedule (); 		//Removed by PaN
1102			//continue;
1103		}
1104
1105		writecount += usblp->writeurb->transfer_buffer_length;
1106		usblp->writeurb->transfer_buffer_length = 0;
1107
1108		if (writecount == count) {
1109			up (&usblp->sem);
1110			break;
1111		}
1112
1113		usblp->writeurb->transfer_buffer_length = (count - writecount) < USBLP_BUF_SIZE ?
1114							  (count - writecount) : USBLP_BUF_SIZE;
1115
1116		if (copy_from_user(usblp->writeurb->transfer_buffer, buffer + writecount,
1117				usblp->writeurb->transfer_buffer_length)) {
1118			up(&usblp->sem);
1119			return writecount ? writecount : -EFAULT;
1120		}
1121
1122		usblp->writeurb->dev = usblp->dev;
1123		usblp->wcomplete = 0;
1124		if (usb_submit_urb(usblp->writeurb)) {
1125			count = -EIO;
1126			up (&usblp->sem);
1127			break;
1128		}
1129		up (&usblp->sem);
1130	}
1131
1132	return count;
1133}
1134
1135static ssize_t usblp_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
1136{
1137	struct usblp *usblp = file->private_data;
1138	DECLARE_WAITQUEUE(wait, current);
1139
1140	if (!usblp->bidir)
1141		return -EINVAL;
1142
1143	down (&usblp->sem);
1144	if (!usblp->present) {
1145		count = -ENODEV;
1146		goto done;
1147	}
1148
1149	if (!usblp->rcomplete) {
1150		barrier();
1151
1152		if (file->f_flags & O_NONBLOCK) {
1153			count = -EAGAIN;
1154			goto done;
1155		}
1156
1157		add_wait_queue(&usblp->wait, &wait);
1158		while (1==1) {
1159			if (signal_pending(current)) {
1160				count = -EINTR;
1161				remove_wait_queue(&usblp->wait, &wait);
1162				goto done;
1163			}
1164			up (&usblp->sem);
1165			set_current_state(TASK_INTERRUPTIBLE);
1166			if (!usblp->rcomplete) {
1167				schedule();
1168			} else {
1169				set_current_state(TASK_RUNNING);
1170				break;
1171			}
1172			down (&usblp->sem);
1173		}
1174		remove_wait_queue(&usblp->wait, &wait);
1175	}
1176
1177	if (!usblp->present) {
1178		count = -ENODEV;
1179		goto done;
1180	}
1181
1182	if (usblp->readurb->status) {
1183		err("usblp%d: error %d reading from printer",
1184			usblp->minor, usblp->readurb->status);
1185		usblp->readurb->dev = usblp->dev;
1186 		usblp->readcount = 0;
1187		if (usb_submit_urb(usblp->readurb) < 0)
1188			dbg("error submitting urb");
1189		count = -EIO;
1190		goto done;
1191	}
1192
1193	count = count < usblp->readurb->actual_length - usblp->readcount ?
1194		count :	usblp->readurb->actual_length - usblp->readcount;
1195
1196	if (copy_to_user(buffer, usblp->readurb->transfer_buffer + usblp->readcount, count)) {
1197		count = -EFAULT;
1198		goto done;
1199	}
1200
1201	if ((usblp->readcount += count) == usblp->readurb->actual_length) {
1202		usblp->readcount = 0;
1203		usblp->readurb->dev = usblp->dev;
1204		usblp->rcomplete = 0;
1205		if (usb_submit_urb(usblp->readurb)) {
1206			count = -EIO;
1207			goto done;
1208		}
1209	}
1210
1211done:
1212	up (&usblp->sem);
1213	return count;
1214}
1215
1216/*
1217 * Checks for printers that have quirks, such as requiring unidirectional
1218 * communication but reporting bidirectional; currently some HP printers
1219 * have this flaw (HP 810, 880, 895, etc.), or needing an init string
1220 * sent at each open (like some Epsons).
1221 * Returns 1 if found, 0 if not found.
1222 *
1223 * HP recommended that we use the bidirectional interface but
1224 * don't attempt any bulk IN transfers from the IN endpoint.
1225 * Here's some more detail on the problem:
1226 * The problem is not that it isn't bidirectional though. The problem
1227 * is that if you request a device ID, or status information, while
1228 * the buffers are full, the return data will end up in the print data
1229 * buffer. For example if you make sure you never request the device ID
1230 * while you are sending print data, and you don't try to query the
1231 * printer status every couple of milliseconds, you will probably be OK.
1232 */
1233static unsigned int usblp_quirks (__u16 vendor, __u16 product)
1234{
1235	int i;
1236
1237	for (i = 0; quirk_printers[i].vendorId; i++) {
1238		if (vendor == quirk_printers[i].vendorId &&
1239		    product == quirk_printers[i].productId)
1240			return quirk_printers[i].quirks;
1241 	}
1242	return 0;
1243}
1244
1245static struct file_operations usblp_fops = {
1246	owner:		THIS_MODULE,
1247	read:		usblp_read,
1248	write:		usblp_write,
1249	poll:		usblp_poll,
1250	ioctl:		usblp_ioctl,
1251	open:		usblp_open,
1252	release:	usblp_release,
1253};
1254
1255static void *usblp_probe(struct usb_device *dev, unsigned int ifnum,
1256			 const struct usb_device_id *id)
1257{
1258	struct usblp *usblp = 0;
1259	int protocol;
1260	char name[6];
1261
1262	/* Malloc and start initializing usblp structure so we can use it
1263	 * directly. */
1264	if (!(usblp = kmalloc(sizeof(struct usblp), GFP_KERNEL))) {
1265		err("out of memory for usblp");
1266		goto abort;
1267	}
1268	memset(usblp, 0, sizeof(struct usblp));
1269	usblp->dev = dev;
1270	init_MUTEX (&usblp->sem);
1271	init_waitqueue_head(&usblp->wait);
1272	usblp->ifnum = ifnum;
1273
1274	/* Look for a free usblp_table entry. */
1275	while (usblp_table[usblp->minor]) {
1276		usblp->minor++;
1277		if (usblp->minor >= USBLP_MINORS) {
1278			err("no more free usblp devices");
1279			goto abort;
1280		}
1281	}
1282
1283	usblp->writeurb = usb_alloc_urb(0);
1284	if (!usblp->writeurb) {
1285		err("out of memory");
1286		goto abort;
1287	}
1288	usblp->readurb = usb_alloc_urb(0);
1289	if (!usblp->readurb) {
1290		err("out of memory");
1291		goto abort;
1292	}
1293
1294	/* Malloc device ID string buffer to the largest expected length,
1295	 * since we can re-query it on an ioctl and a dynamic string
1296	 * could change in length. */
1297	if (!(usblp->device_id_string = kmalloc(USBLP_DEVICE_ID_SIZE, GFP_KERNEL))) {
1298		err("out of memory for device_id_string");
1299		goto abort;
1300	}
1301
1302	usblp->writebuf = usblp->readbuf = NULL;
1303	/* Malloc write & read buffers.  We somewhat wastefully
1304	 * malloc both regardless of bidirectionality, because the
1305	 * alternate setting can be changed later via an ioctl. */
1306	if (!(usblp->writebuf = kmalloc(USBLP_BUF_SIZE, GFP_KERNEL))) {
1307		err("out of memory for write buf");
1308		goto abort;
1309	}
1310	if (!(usblp->readbuf = kmalloc(USBLP_BUF_SIZE, GFP_KERNEL))) {
1311		err("out of memory for read buf");
1312		goto abort;
1313	}
1314
1315	/* Allocate buffer for printer status */
1316	usblp->statusbuf = kmalloc(STATUS_BUF_SIZE, GFP_KERNEL);
1317	if (!usblp->statusbuf) {
1318		err("out of memory for statusbuf");
1319		goto abort;
1320	}
1321
1322	/* Lookup quirks for this printer. */
1323	usblp->quirks = usblp_quirks(
1324		dev->descriptor.idVendor,
1325		dev->descriptor.idProduct);
1326
1327	/* Analyze and pick initial alternate settings and endpoints. */
1328	protocol = usblp_select_alts(usblp);
1329	if (protocol < 0) {
1330		dbg("incompatible printer-class device 0x%4.4X/0x%4.4X",
1331			dev->descriptor.idVendor,
1332			dev->descriptor.idProduct);
1333		goto abort;
1334	}
1335
1336	/* Setup the selected alternate setting and endpoints. */
1337	if (usblp_set_protocol(usblp, protocol) < 0)
1338		goto abort;
1339
1340	/* Retrieve and store the device ID string. */
1341	usblp_cache_device_id_string(usblp);
1342
1343#ifdef DEBUG
1344	usblp_check_status(usblp, 0);
1345#endif
1346
1347	usblp_table[usblp->minor] = usblp;
1348	/* If we have devfs, create with perms=660. */
1349	sprintf(name, "lp%d", usblp->minor);
1350	usblp->devfs = devfs_register(usb_devfs_handle, name,
1351				      DEVFS_FL_DEFAULT, USB_MAJOR,
1352				      USBLP_MINOR_BASE + usblp->minor,
1353				      S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP |
1354				      S_IWGRP, &usblp_fops, NULL);
1355
1356	info("usblp%d: USB %sdirectional printer dev %d "
1357		"if %d alt %d proto %d vid 0x%4.4X pid 0x%4.4X",
1358		usblp->minor, usblp->bidir ? "Bi" : "Uni", dev->devnum,
1359		usblp->ifnum,
1360		usblp->protocol[usblp->current_protocol].alt_setting,
1361		usblp->current_protocol, usblp->dev->descriptor.idVendor,
1362		usblp->dev->descriptor.idProduct);
1363
1364	usblp->present = 1;
1365
1366	/* Added by PaN */
1367	/* create directory */
1368	usblp_dir = proc_mkdir(MODULE_NAME, NULL);
1369	if(usblp_dir == NULL) {
1370	        goto outpan;
1371	}
1372        usblp_dir->owner = THIS_MODULE;
1373
1374	usblpid_file = create_proc_read_entry("usblpid", 0444, usblp_dir, proc_read_usblpid, NULL);
1375	if(usblpid_file == NULL) {
1376		remove_proc_entry(MODULE_NAME, NULL);
1377
1378		goto outpan;
1379	}
1380        usblpid_file->owner = THIS_MODULE;
1381	/* get device id */
1382	if (proc_get_usblpid(usblp) < 0)
1383		info("proc:get usblpid error!!");
1384
1385outpan:
1386	// End PaN
1387
1388
1389	return usblp;
1390
1391abort:
1392	if (usblp) {
1393		if (usblp->writebuf)
1394			kfree (usblp->writebuf);
1395		if (usblp->readbuf)
1396			kfree (usblp->readbuf);
1397		kfree(usblp->statusbuf);
1398		kfree(usblp->device_id_string);
1399		usb_free_urb(usblp->writeurb);
1400		usb_free_urb(usblp->readurb);
1401		kfree(usblp);
1402	}
1403	return NULL;
1404}
1405
1406/*
1407 * We are a "new" style driver with usb_device_id table,
1408 * but our requirements are too intricate for simple match to handle.
1409 *
1410 * The "proto_bias" option may be used to specify the preferred protocol
1411 * for all USB printers (1=7/1/1, 2=7/1/2, 3=7/1/3).  If the device
1412 * supports the preferred protocol, then we bind to it.
1413 *
1414 * The best interface for us is 7/1/2, because it is compatible
1415 * with a stream of characters. If we find it, we bind to it.
1416 *
1417 * Note that the people from hpoj.sourceforge.net need to be able to
1418 * bind to 7/1/3 (MLC/1284.4), so we provide them ioctls for this purpose.
1419 *
1420 * Failing 7/1/2, we look for 7/1/3, even though it's probably not
1421 * stream-compatible, because this matches the behaviour of the old code.
1422 *
1423 * If nothing else, we bind to 7/1/1 - the unidirectional interface.
1424 */
1425static int usblp_select_alts(struct usblp *usblp)
1426{
1427	struct usb_interface *if_alt;
1428	struct usb_interface_descriptor *ifd;
1429	struct usb_endpoint_descriptor *epd, *epwrite, *epread;
1430	int p, i, e;
1431
1432	if_alt = &usblp->dev->actconfig->interface[usblp->ifnum];
1433
1434	for (p = 0; p < USBLP_MAX_PROTOCOLS; p++)
1435		usblp->protocol[p].alt_setting = -1;
1436
1437	/* Find out what we have. */
1438	for (i = 0; i < if_alt->num_altsetting; i++) {
1439		ifd = &if_alt->altsetting[i];
1440
1441		if (ifd->bInterfaceClass != 7 || ifd->bInterfaceSubClass != 1)
1442			continue;
1443
1444		if (ifd->bInterfaceProtocol < USBLP_FIRST_PROTOCOL ||
1445		    ifd->bInterfaceProtocol > USBLP_LAST_PROTOCOL)
1446			continue;
1447
1448		/* Look for bulk OUT and IN endpoints. */
1449		epwrite = epread = 0;
1450		for (e = 0; e < ifd->bNumEndpoints; e++) {
1451			epd = &ifd->endpoint[e];
1452
1453			if ((epd->bmAttributes&USB_ENDPOINT_XFERTYPE_MASK)!=
1454			    USB_ENDPOINT_XFER_BULK)
1455				continue;
1456
1457			if (!(epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK)) {
1458				if (!epwrite) epwrite=epd;
1459
1460			} else {
1461				if (!epread) epread=epd;
1462			}
1463		}
1464
1465		/* Ignore buggy hardware without the right endpoints. */
1466		if (!epwrite || (ifd->bInterfaceProtocol > 1 && !epread))
1467			continue;
1468
1469		/* Turn off reads for 7/1/1 (unidirectional) interfaces
1470		 * and buggy bidirectional printers. */
1471		if (ifd->bInterfaceProtocol == 1) {
1472			epread = NULL;
1473		} else if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1474			info("Disabling reads from problem bidirectional "
1475				"printer on usblp%d", usblp->minor);
1476			epread = NULL;
1477		}
1478
1479		usblp->protocol[ifd->bInterfaceProtocol].alt_setting = i;
1480		usblp->protocol[ifd->bInterfaceProtocol].epwrite = epwrite;
1481		usblp->protocol[ifd->bInterfaceProtocol].epread = epread;
1482	}
1483
1484	/* If our requested protocol is supported, then use it. */
1485	if (proto_bias >= USBLP_FIRST_PROTOCOL &&
1486	    proto_bias <= USBLP_LAST_PROTOCOL &&
1487	    usblp->protocol[proto_bias].alt_setting != -1)
1488		return proto_bias;
1489
1490	/* Ordering is important here. */
1491	if (usblp->protocol[2].alt_setting != -1) return 2;
1492	if (usblp->protocol[1].alt_setting != -1) return 1;
1493	if (usblp->protocol[3].alt_setting != -1) return 3;
1494
1495	/* If nothing is available, then don't bind to this device. */
1496	return -1;
1497}
1498
1499static int usblp_set_protocol(struct usblp *usblp, int protocol)
1500{
1501	int r, alts;
1502
1503	if (protocol < USBLP_FIRST_PROTOCOL || protocol > USBLP_LAST_PROTOCOL)
1504		return -EINVAL;
1505
1506	alts = usblp->protocol[protocol].alt_setting;
1507	if (alts < 0) return -EINVAL;
1508	r = usb_set_interface(usblp->dev, usblp->ifnum, alts);
1509	if (r < 0) {
1510		err("can't set desired altsetting %d on interface %d",
1511			alts, usblp->ifnum);
1512		return r;
1513	}
1514
1515	usb_fill_bulk_urb(usblp->writeurb, usblp->dev,
1516		usb_sndbulkpipe(usblp->dev,
1517		  usblp->protocol[protocol].epwrite->bEndpointAddress),
1518		usblp->writebuf, 0,
1519		usblp_bulk_write, usblp);
1520
1521	usblp->bidir = (usblp->protocol[protocol].epread != 0);
1522	if (usblp->bidir)
1523		usb_fill_bulk_urb(usblp->readurb, usblp->dev,
1524			usb_rcvbulkpipe(usblp->dev,
1525			  usblp->protocol[protocol].epread->bEndpointAddress),
1526			usblp->readbuf, USBLP_BUF_SIZE,
1527			usblp_bulk_read, usblp);
1528
1529	usblp->current_protocol = protocol;
1530	dbg("usblp%d set protocol %d", usblp->minor, protocol);
1531	return 0;
1532}
1533
1534/* Retrieves and caches device ID string.
1535 * Returns length, including length bytes but not null terminator.
1536 * On error, returns a negative errno value. */
1537static int usblp_cache_device_id_string(struct usblp *usblp)
1538{
1539	int err, length;
1540
1541	err = usblp_get_id(usblp, 0, usblp->device_id_string, USBLP_DEVICE_ID_SIZE - 1);
1542	if (err < 0) {
1543		dbg("usblp%d: error = %d reading IEEE-1284 Device ID string",
1544			usblp->minor, err);
1545		usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
1546		return -EIO;
1547	}
1548
1549	/* First two bytes are length in big-endian.
1550	 * They count themselves, and we copy them into
1551	 * the user's buffer. */
1552	length = (usblp->device_id_string[0] << 8) + usblp->device_id_string[1];
1553	if (length < 2)
1554		length = 2;
1555	else if (length >= USBLP_DEVICE_ID_SIZE)
1556		length = USBLP_DEVICE_ID_SIZE - 1;
1557	usblp->device_id_string[length] = '\0';
1558
1559	dbg("usblp%d Device ID string [len=%d]=\"%s\"",
1560		usblp->minor, length, &usblp->device_id_string[2]);
1561
1562	return length;
1563}
1564
1565static void usblp_disconnect(struct usb_device *dev, void *ptr)
1566{
1567	struct usblp *usblp = ptr;
1568
1569	if (!usblp || !usblp->dev) {
1570		err("bogus disconnect");
1571		BUG ();
1572	}
1573
1574	down (&usblp->sem);
1575	lock_kernel();
1576	usblp->present = 0;
1577
1578	usblp_unlink_urbs(usblp);
1579
1580	if (!usblp->used)
1581		usblp_cleanup (usblp);
1582	else 	/* cleanup later, on release */
1583		up (&usblp->sem);
1584	unlock_kernel();
1585}
1586
1587static struct usb_device_id usblp_ids [] = {
1588	{ USB_DEVICE_INFO(7, 1, 1) },
1589	{ USB_DEVICE_INFO(7, 1, 2) },
1590	{ USB_DEVICE_INFO(7, 1, 3) },
1591	{ USB_INTERFACE_INFO(7, 1, 1) },
1592	{ USB_INTERFACE_INFO(7, 1, 2) },
1593	{ USB_INTERFACE_INFO(7, 1, 3) },
1594	{ }						/* Terminating entry */
1595};
1596
1597MODULE_DEVICE_TABLE (usb, usblp_ids);
1598
1599static struct usb_driver usblp_driver = {
1600	name:		"usblp",
1601	probe:		usblp_probe,
1602	disconnect:	usblp_disconnect,
1603	fops:		&usblp_fops,
1604	minor:		USBLP_MINOR_BASE,
1605	id_table:	usblp_ids,
1606};
1607
1608static int __init usblp_init(void)
1609{
1610	if (usb_register(&usblp_driver))
1611		return -1;
1612	info(DRIVER_VERSION ": " DRIVER_DESC);
1613	return 0;
1614}
1615
1616static void __exit usblp_exit(void)
1617{
1618	usb_deregister(&usblp_driver);
1619}
1620
1621module_init(usblp_init);
1622module_exit(usblp_exit);
1623
1624MODULE_AUTHOR( DRIVER_AUTHOR );
1625MODULE_DESCRIPTION( DRIVER_DESC );
1626MODULE_PARM(proto_bias, "i");
1627MODULE_PARM_DESC(proto_bias, "Favourite protocol number");
1628MODULE_LICENSE("GPL");
1629