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/* Added by PaN */
62#include <linux/proc_fs.h>
63#include <asm/uaccess.h>
64// End PaN
65                                                                                                                             
66/* Added by PaN */
67struct print_buffer
68{
69        int len;
70        char *buf;
71};
72#define MODULE_NAME "usblp"
73#define MAX_CLASS_NAME  16
74#define MAX_MFR         16
75#define MAX_MODEL       32
76#define MAX_DESCRIPT    64
77#define MAX_STATUS_TYPE 6
78                                                                                                                             
79static struct proc_dir_entry *usblp_dir, *usblpid_file;
80struct parport_splink_device_info {
81        char class_name[MAX_CLASS_NAME];
82        char mfr[MAX_MFR];
83        char model[MAX_MODEL];
84        char description[MAX_DESCRIPT];
85};
86static char *usblp_status_type[MAX_STATUS_TYPE]={ "Lexmark", "Canon", "Hp", "Epson", "EPSON", NULL};
87static int usblp_status_maping[MAX_STATUS_TYPE][4]={ {0,0,0,0},
88                                                     {0, LP_POUTPA, LP_PERRORP, LP_PBUSY},
89                                                     {0,0,0,0},
90                                                     {0,0,0,0},
91                                                     {0,0,0,0},
92                                                     {0,0,0,0}};
93                                                                                                                             
94static struct parport_splink_device_info usblpid_info;
95struct parport_splink_device_info prn_info_tmp, *prn_info; // Added by JYWeng 20031212:
96char *strunknown="unknown"; // Added by JYWeng 20031212:
97void parseKeywords(char *str_dev_id, char *keyword1, char *keyword2, char *prn_info_data, char *usblpid_info_data);// Added by JYWeng 20031212:
98                                                                                                                             
99static ssize_t usblp_write(struct file *file, const char *buffer, size_t count, loff_t *ppos);
100static ssize_t usblp_read(struct file *file, char *buffer, size_t count, loff_t *ppos);
101static int usblp_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg);
102// END PaN
103
104/*
105 * Version Information
106 */
107#define DRIVER_VERSION "v0.13"
108#define DRIVER_AUTHOR "Michael Gee, Pavel Machek, Vojtech Pavlik, Randy Dunlap, Pete Zaitcev, David Paschal"
109#define DRIVER_DESC "USB Printer Device Class driver"
110
111#define USBLP_BUF_SIZE		8192
112#define USBLP_DEVICE_ID_SIZE	1024
113
114/****************add by JY 20031118*************************************/
115#define LPGETID                 0x0610          /* get printer's device ID */
116#define LPWRITEDATA     0x0613  /* write data to printer */
117#define LPWRITEADDR     0x0614  /* write address to printer */
118#define LPREADDATA      0x0615  /* read data from pinter */
119#define LPREADADDR      0x0616  /* read address from pinter */
120#define DEVICE_ID_SIZE  1024
121/*******************************************************/
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/* Added by PaN */
349static int proc_read_usblpid(char *page, char **start, off_t off, int count, int *eof, void *data)
350{
351        int len=0;
352                                                                                                                             
353        len=sprintf(page, "Manufacturer=%s\nModel=%s\nClass=%s\nDescription=%s\n\n",
354        usblpid_info.mfr, usblpid_info.model, usblpid_info.class_name, usblpid_info.description);
355                                                                                                                             
356        return len;
357}
358                                                                                                                             
359static int proc_get_usblpid(struct usblp *usblp)
360{
361//JYWeng 20031212: set this as global   char *strtmp, *str_dev_id, *strunknown="unknown"; // Added by PaN
362        char *strtmp, *str_dev_id; // Added by PaN: JYWeng 20031212: modified from the above
363        int i, unk = 0; // Added by PaN
364        int length, err;
365        int retval = 0;
366                                                                                                                             
367        prn_info= &prn_info_tmp; // Added by JYWeng 20031212:
368                                                                                                                             
369                                                                                                                             
370        err = usblp_get_id(usblp, 0, usblp->device_id_string, DEVICE_ID_SIZE - 1);
371                                                                                                                             
372        if (err < 0) {
373                dbg ("usblp%d: error = %d reading IEEE-1284 Device ID string",
374                        usblp->minor, err);
375                        usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
376                retval = -EIO;
377                goto done;
378        }
379                                                                                                                             
380        length = (usblp->device_id_string[0] << 8) + usblp->device_id_string[1]; /* big-endian */
381        if (length < DEVICE_ID_SIZE)
382                usblp->device_id_string[length] = '\0';
383        else
384                usblp->device_id_string[DEVICE_ID_SIZE - 1] = '\0';
385                                                                                                                             
386        dbg ("usblp%d Device ID string [%d]='%s'",
387                usblp->minor, length, &usblp->device_id_string[2]);
388        info ("usblp%d Device ID string [%d]='%s'",
389                usblp->minor, length, &usblp->device_id_string[2]);
390                                                                                                                             
391        str_dev_id = &usblp->device_id_string[2];
392#if 1//JYWeng 20031212: modified from below
393                                parseKeywords(str_dev_id, "MFG:", "MANUFACTURE:", prn_info->mfr, usblpid_info.mfr);
394                                parseKeywords(str_dev_id, "MDL:", "MODEL:", prn_info->model, usblpid_info.model);
395                                parseKeywords(str_dev_id, "CLS:", "CLASS:", prn_info->class_name, usblpid_info.class_name);
396                                                                                                                             
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                                                                                                                             
827                                parseKeywords(str_dev_id, "DES:", "DESCRIPTION:", prn_info->description, usblpid_info.description);
828#else
829                                if ( (strtmp = strstr(str_dev_id, "MFG:")) == NULL) {
830                                        if ( (strtmp = strstr(str_dev_id, "MANUFACTURE:")) == NULL) {
831                                                for (i=0; i<7; i++) {
832                                                        prn_info->mfr[i]= strunknown[i];
833                                                        usblpid_info.mfr[i] = strunknown[i];
834                                                }
835                                                prn_info->mfr[i]= '\0';
836                                                usblpid_info.mfr[i]='\0';
837                                                unk=1;
838                                        }
839                                        else
840                                                strtmp+=12;
841                                }
842                                else
843                                        strtmp+=4;
844                                                                                                                             
845                                i=0;
846                                while (unk==0 && strtmp[i] != ';') {
847                                        prn_info->mfr[i]= strtmp[i];
848                                        usblpid_info.mfr[i] = strtmp[i];
849                                        i++;
850                                }
851                                prn_info->mfr[i]= '\0';
852                                usblpid_info.mfr[i]='\0';
853                                unk=0;
854                                                                                                                             
855                                if ( (strtmp = strstr(str_dev_id, "MDL:")) == NULL) {
856                                        if ( (strtmp = strstr(str_dev_id, "MODEL:")) == NULL) {
857                                                for (i=0; i<7; i++) {
858                                                        prn_info->model[i]= strunknown[i];
859                                                        usblpid_info.model[i] = strunknown[i];
860                                                }
861                                                prn_info->model[i]= '\0';
862                                                usblpid_info.model[i]='\0';
863                                                unk=1;
864                                        }
865                                        else
866                                                strtmp+=6;
867                                }
868                                else
869                                        strtmp+=4;
870                                                                                                                             
871                                i=0;
872                                while (unk==0 && strtmp[i] != ';') {
873                                        prn_info->model[i]= strtmp[i];
874                                        usblpid_info.model[i] = strtmp[i];
875                                        i++;
876                                }
877                                prn_info->model[i]= '\0';
878                                usblpid_info.model[i]='\0';
879                                unk=0;
880                                                                                                                             
881                                if ( (strtmp = strstr(str_dev_id, "CLS:")) == NULL) {
882                                        if ( (strtmp = strstr(str_dev_id, "CLASS:")) == NULL) {
883                                                for (i=0; i<7; i++) {
884                                                        prn_info->class_name[i]= strunknown[i];
885                                                        usblpid_info.class_name[i] = strunknown[i];
886                                                }
887                                                prn_info->class_name[i]= '\0';
888                                                usblpid_info.class_name[i]='\0';
889                                                unk=1;
890                                        }
891                                        else
892                                                strtmp+=6;
893                                }
894                                else
895                                        strtmp+=4;
896                                                                                                                             
897                                i=0;
898                                while (unk==0 && strtmp[i] != ';') {
899                                        prn_info->class_name[i]= strtmp[i];
900                                        usblpid_info.class_name[i]= strtmp[i];
901                                        i++;
902                                }
903                                prn_info->class_name[i]= '\0';
904                                usblpid_info.class_name[i]='\0';
905                                unk=0;
906                                                                                                                             
907                                if ( (strtmp = strstr(str_dev_id, "DES:")) == NULL) {
908                                        if ( (strtmp = strstr(str_dev_id, "DESCRIPTION:")) == NULL) {
909                                                for (i=0; i<7; i++) {
910                                                        prn_info->description[i]= strunknown[i];
911                                                        usblpid_info.description[i] = strunknown[i];
912                                                }
913                                                prn_info->description[i]= '\0';
914                                                usblpid_info.description[i]='\0';
915                                                unk=1;
916                                        }
917                                        else
918                                                strtmp+=12;
919                                }
920                                else
921                                        strtmp+=4;
922                                                                                                                             
923                                i=0;
924                                while (unk==0 && strtmp[i] != ';') {
925                                                prn_info->description[i]= strtmp[i];
926                                                usblpid_info.description[i]= strtmp[i];
927                                                i++;
928                                }
929                                prn_info->description[i]= '\0';
930                                usblpid_info.description[i]='\0';
931#endif//JYWeng 20031212: end
932                                                                                                                             
933                                info("Parsing USBLPID...");
934                                if (copy_to_user((unsigned char *) arg,
935                                                prn_info, (unsigned long) length)) {
936                                        retval = -EFAULT;
937                                        goto done;
938                                }
939                                break;
940                                                                                                                             
941                        case LPREADDATA:
942                                up (&usblp->sem);
943                                user_buf = (struct print_buffer *)arg;
944                                retval = usblp_read(file, user_buf->buf, user_buf->len, NULL);
945                                down (&usblp->sem);
946                                break;
947                                                                                                                             
948                                                                                                                             
949                        case LPWRITEDATA:
950                                up (&usblp->sem);
951                                user_buf = (struct print_buffer *)arg;
952                                retval = usblp_write(file, user_buf->buf, user_buf->len, NULL);
953                                down (&usblp->sem);
954                                break;
955                                                                                                                             
956                        case LPRESET:
957                                usblp_reset(usblp);
958                                break;
959
960			case LPGETSTATUS:
961                                /* OLD USB Code Removed by PaN for Printer Server
962                                if (usblp_read_status(usblp, &status)) {
963                                        err("usblp%d: failed reading printer status", usblp->minor);
964                                        retval = -EIO;
965                                        goto done;
966                                }
967                                if (copy_to_user ((int *)arg, &status, 2))
968                                        retval = -EFAULT;
969                                */
970                                status = usblp_check_status(usblp, 0);
971#if 0
972                                info("start=%s", usblpid_info.mfr);
973                                for (i=0; i< MAX_STATUS_TYPE; i++) {
974                                info("compare=%s", usblp_status_type[i]);
975                                        if ( !( strcmp(usblpid_info.mfr, usblp_status_type[i]) ) )
976                                                break;
977                                }
978                                info("%d=%s", i, usblp_status_type[i]);
979                                status=usblp_status_maping[i][status];
980                                info("STATUS=%x", status);
981#endif
982                                status=0;
983                                if (copy_to_user ((int *)arg, &status, 2))
984                                        retval = -EFAULT;
985                                break;
986
987/*=================================================================== PaN for Printer Server */
988
989			default:
990				retval = -ENOTTY;
991		}
992
993done:
994	up (&usblp->sem);
995	return retval;
996}
997
998static ssize_t usblp_write(struct file *file, const char *buffer, size_t count, loff_t *ppos)
999{
1000	DECLARE_WAITQUEUE(wait, current);
1001	struct usblp *usblp = file->private_data;
1002	int timeout, err = 0, transfer_length = 0;
1003	size_t writecount = 0;
1004
1005	while (writecount < count) {
1006		if (!usblp->wcomplete) {
1007			barrier();
1008			if (file->f_flags & O_NONBLOCK) {
1009				writecount += transfer_length;
1010				return writecount ? writecount : -EAGAIN;
1011			}
1012
1013			timeout = USBLP_WRITE_TIMEOUT;
1014			add_wait_queue(&usblp->wait, &wait);
1015			while ( 1==1 ) {
1016
1017				if (signal_pending(current)) {
1018					remove_wait_queue(&usblp->wait, &wait);
1019					return writecount ? writecount : -EINTR;
1020				}
1021				set_current_state(TASK_INTERRUPTIBLE);
1022				if (timeout && !usblp->wcomplete) {
1023					timeout = schedule_timeout(timeout);
1024				} else {
1025					set_current_state(TASK_RUNNING);
1026					break;
1027				}
1028			}
1029			remove_wait_queue(&usblp->wait, &wait);
1030		}
1031
1032		down (&usblp->sem);
1033		if (!usblp->present) {
1034			up (&usblp->sem);
1035			return -ENODEV;
1036		}
1037
1038		if (usblp->writeurb->status != 0) {
1039			if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1040				if (!usblp->wcomplete)
1041					err("usblp%d: error %d writing to printer",
1042						usblp->minor, usblp->writeurb->status);
1043				err = usblp->writeurb->status;
1044			} else
1045				err = usblp_check_status(usblp, err);
1046			up (&usblp->sem);
1047
1048			/* if the fault was due to disconnect, let khubd's
1049			 * call to usblp_disconnect() grab usblp->sem ...
1050			 */
1051			return writecount;      //Added by PaN
1052//			schedule ();
1053//			continue;
1054		}
1055
1056		/* We must increment writecount here, and not at the
1057		 * end of the loop. Otherwise, the final loop iteration may
1058		 * be skipped, leading to incomplete printer output.
1059		 */
1060		writecount += transfer_length;
1061		if (writecount == count) {
1062			up (&usblp->sem);
1063			break;
1064		}
1065
1066		transfer_length = count - writecount;
1067		if(transfer_length > USBLP_BUF_SIZE) 
1068			transfer_length = USBLP_BUF_SIZE;
1069		
1070		usblp->writeurb->transfer_buffer_length = transfer_length;
1071
1072		if (copy_from_user(usblp->writeurb->transfer_buffer, 
1073				   buffer + writecount, transfer_length)) {
1074			up(&usblp->sem);
1075			return writecount ? writecount : -EFAULT;
1076		}
1077
1078		usblp->writeurb->dev = usblp->dev;
1079		usblp->wcomplete = 0;
1080		err = usb_submit_urb(usblp->writeurb);
1081		if (err) {
1082			if (err != -ENOMEM)
1083				count = -EIO;
1084			else
1085				count = writecount ? writecount : -ENOMEM;
1086			up (&usblp->sem);
1087			break;
1088		}
1089		up (&usblp->sem);
1090	}
1091
1092	return count;
1093}
1094
1095static ssize_t usblp_read(struct file *file, char *buffer, size_t count, loff_t *ppos)
1096{
1097	struct usblp *usblp = file->private_data;
1098	DECLARE_WAITQUEUE(wait, current);
1099
1100	if (!usblp->bidir)
1101		return -EINVAL;
1102
1103	down (&usblp->sem);
1104	if (!usblp->present) {
1105		count = -ENODEV;
1106		goto done;
1107	}
1108
1109	if (!usblp->rcomplete) {
1110		barrier();
1111
1112		if (file->f_flags & O_NONBLOCK) {
1113			count = -EAGAIN;
1114			goto done;
1115		}
1116
1117		add_wait_queue(&usblp->wait, &wait);
1118		while (1==1) {
1119			if (signal_pending(current)) {
1120				count = -EINTR;
1121				remove_wait_queue(&usblp->wait, &wait);
1122				goto done;
1123			}
1124			up (&usblp->sem);
1125			set_current_state(TASK_INTERRUPTIBLE);
1126			if (!usblp->rcomplete) {
1127				schedule();
1128			} else {
1129				set_current_state(TASK_RUNNING);
1130				break;
1131			}
1132			down (&usblp->sem);
1133		}
1134		remove_wait_queue(&usblp->wait, &wait);
1135	}
1136
1137	if (!usblp->present) {
1138		count = -ENODEV;
1139		goto done;
1140	}
1141
1142	if (usblp->readurb->status) {
1143		err("usblp%d: error %d reading from printer",
1144			usblp->minor, usblp->readurb->status);
1145		usblp->readurb->dev = usblp->dev;
1146 		usblp->readcount = 0;
1147		if (usb_submit_urb(usblp->readurb) < 0)
1148			dbg("error submitting urb");
1149		count = -EIO;
1150		goto done;
1151	}
1152
1153	count = count < usblp->readurb->actual_length - usblp->readcount ?
1154		count :	usblp->readurb->actual_length - usblp->readcount;
1155
1156	if (copy_to_user(buffer, usblp->readurb->transfer_buffer + usblp->readcount, count)) {
1157		count = -EFAULT;
1158		goto done;
1159	}
1160
1161	if ((usblp->readcount += count) == usblp->readurb->actual_length) {
1162		usblp->readcount = 0;
1163		usblp->readurb->dev = usblp->dev;
1164		usblp->rcomplete = 0;
1165		if (usb_submit_urb(usblp->readurb)) {
1166			count = -EIO;
1167			goto done;
1168		}
1169	}
1170
1171done:
1172	up (&usblp->sem);
1173	return count;
1174}
1175
1176/*
1177 * Checks for printers that have quirks, such as requiring unidirectional
1178 * communication but reporting bidirectional; currently some HP printers
1179 * have this flaw (HP 810, 880, 895, etc.), or needing an init string
1180 * sent at each open (like some Epsons).
1181 * Returns 1 if found, 0 if not found.
1182 *
1183 * HP recommended that we use the bidirectional interface but
1184 * don't attempt any bulk IN transfers from the IN endpoint.
1185 * Here's some more detail on the problem:
1186 * The problem is not that it isn't bidirectional though. The problem
1187 * is that if you request a device ID, or status information, while
1188 * the buffers are full, the return data will end up in the print data
1189 * buffer. For example if you make sure you never request the device ID
1190 * while you are sending print data, and you don't try to query the
1191 * printer status every couple of milliseconds, you will probably be OK.
1192 */
1193static unsigned int usblp_quirks (__u16 vendor, __u16 product)
1194{
1195	int i;
1196
1197	for (i = 0; quirk_printers[i].vendorId; i++) {
1198		if (vendor == quirk_printers[i].vendorId &&
1199		    product == quirk_printers[i].productId)
1200			return quirk_printers[i].quirks;
1201 	}
1202	return 0;
1203}
1204
1205static struct file_operations usblp_fops = {
1206	owner:		THIS_MODULE,
1207	read:		usblp_read,
1208	write:		usblp_write,
1209	poll:		usblp_poll,
1210	ioctl:		usblp_ioctl,
1211	open:		usblp_open,
1212	release:	usblp_release,
1213};
1214
1215static void *usblp_probe(struct usb_device *dev, unsigned int ifnum,
1216			 const struct usb_device_id *id)
1217{
1218	struct usblp *usblp = 0;
1219	int protocol;
1220	char name[6];
1221
1222	/* Malloc and start initializing usblp structure so we can use it
1223	 * directly. */
1224	if (!(usblp = kmalloc(sizeof(struct usblp), GFP_KERNEL))) {
1225		err("out of memory for usblp");
1226		goto abort;
1227	}
1228	memset(usblp, 0, sizeof(struct usblp));
1229	usblp->dev = dev;
1230	init_MUTEX (&usblp->sem);
1231	init_waitqueue_head(&usblp->wait);
1232	usblp->ifnum = ifnum;
1233
1234	/* Look for a free usblp_table entry. */
1235	while (usblp_table[usblp->minor]) {
1236		usblp->minor++;
1237		if (usblp->minor >= USBLP_MINORS) {
1238			err("no more free usblp devices");
1239			goto abort;
1240		}
1241	}
1242
1243	usblp->writeurb = usb_alloc_urb(0);
1244	if (!usblp->writeurb) {
1245		err("out of memory");
1246		goto abort;
1247	}
1248	usblp->readurb = usb_alloc_urb(0);
1249	if (!usblp->readurb) {
1250		err("out of memory");
1251		goto abort;
1252	}
1253
1254	/* Malloc device ID string buffer to the largest expected length,
1255	 * since we can re-query it on an ioctl and a dynamic string
1256	 * could change in length. */
1257	if (!(usblp->device_id_string = kmalloc(USBLP_DEVICE_ID_SIZE, GFP_KERNEL))) {
1258		err("out of memory for device_id_string");
1259		goto abort;
1260	}
1261
1262	usblp->writebuf = usblp->readbuf = NULL;
1263	/* Malloc write & read buffers.  We somewhat wastefully
1264	 * malloc both regardless of bidirectionality, because the
1265	 * alternate setting can be changed later via an ioctl. */
1266	if (!(usblp->writebuf = kmalloc(USBLP_BUF_SIZE, GFP_KERNEL))) {
1267		err("out of memory for write buf");
1268		goto abort;
1269	}
1270	if (!(usblp->readbuf = kmalloc(USBLP_BUF_SIZE, GFP_KERNEL))) {
1271		err("out of memory for read buf");
1272		goto abort;
1273	}
1274
1275	/* Allocate buffer for printer status */
1276	usblp->statusbuf = kmalloc(STATUS_BUF_SIZE, GFP_KERNEL);
1277	if (!usblp->statusbuf) {
1278		err("out of memory for statusbuf");
1279		goto abort;
1280	}
1281
1282	/* Lookup quirks for this printer. */
1283	usblp->quirks = usblp_quirks(
1284		dev->descriptor.idVendor,
1285		dev->descriptor.idProduct);
1286
1287	/* Analyze and pick initial alternate settings and endpoints. */
1288	protocol = usblp_select_alts(usblp);
1289	if (protocol < 0) {
1290		dbg("incompatible printer-class device 0x%4.4X/0x%4.4X",
1291			dev->descriptor.idVendor,
1292			dev->descriptor.idProduct);
1293		goto abort;
1294	}
1295
1296	/* Setup the selected alternate setting and endpoints. */
1297	if (usblp_set_protocol(usblp, protocol) < 0)
1298		goto abort;
1299
1300	/* Retrieve and store the device ID string. */
1301	usblp_cache_device_id_string(usblp);
1302
1303#ifdef DEBUG
1304	usblp_check_status(usblp, 0);
1305#endif
1306
1307	usblp_table[usblp->minor] = usblp;
1308	/* If we have devfs, create with perms=660. */
1309	sprintf(name, "lp%d", usblp->minor);
1310	usblp->devfs = devfs_register(usb_devfs_handle, name,
1311				      DEVFS_FL_DEFAULT, USB_MAJOR,
1312				      USBLP_MINOR_BASE + usblp->minor,
1313				      S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP |
1314				      S_IWGRP, &usblp_fops, NULL);
1315
1316	info("usblp%d: USB %sdirectional printer dev %d "
1317		"if %d alt %d proto %d vid 0x%4.4X pid 0x%4.4X",
1318		usblp->minor, usblp->bidir ? "Bi" : "Uni", dev->devnum,
1319		usblp->ifnum,
1320		usblp->protocol[usblp->current_protocol].alt_setting,
1321		usblp->current_protocol, usblp->dev->descriptor.idVendor,
1322		usblp->dev->descriptor.idProduct);
1323
1324	usblp->present = 1;
1325
1326        /* Added by PaN */
1327        /* create directory */
1328        usblp_dir = proc_mkdir(MODULE_NAME, NULL);
1329        if(usblp_dir == NULL) {
1330                goto outpan;
1331        }
1332        usblp_dir->owner = THIS_MODULE;
1333                                                                                                                             
1334        usblpid_file = create_proc_read_entry("usblpid", 0444, usblp_dir, proc_read_usblpid, NULL);
1335        if(usblpid_file == NULL) {
1336                remove_proc_entry(MODULE_NAME, NULL);
1337                                                                                                                             
1338                goto outpan;
1339        }
1340        usblpid_file->owner = THIS_MODULE;
1341        /* get device id */
1342        if (proc_get_usblpid(usblp) < 0)
1343                info("proc:get usblpid error!!");
1344                                                                                                                             
1345outpan:
1346        // End PaN
1347
1348
1349	return usblp;
1350
1351abort:
1352	if (usblp) {
1353		if (usblp->writebuf)
1354			kfree (usblp->writebuf);
1355		if (usblp->readbuf)
1356			kfree (usblp->readbuf);
1357		kfree(usblp->statusbuf);
1358		kfree(usblp->device_id_string);
1359		usb_free_urb(usblp->writeurb);
1360		usb_free_urb(usblp->readurb);
1361		kfree(usblp);
1362	}
1363	return NULL;
1364}
1365
1366/*
1367 * We are a "new" style driver with usb_device_id table,
1368 * but our requirements are too intricate for simple match to handle.
1369 *
1370 * The "proto_bias" option may be used to specify the preferred protocol
1371 * for all USB printers (1=7/1/1, 2=7/1/2, 3=7/1/3).  If the device
1372 * supports the preferred protocol, then we bind to it.
1373 *
1374 * The best interface for us is 7/1/2, because it is compatible
1375 * with a stream of characters. If we find it, we bind to it.
1376 *
1377 * Note that the people from hpoj.sourceforge.net need to be able to
1378 * bind to 7/1/3 (MLC/1284.4), so we provide them ioctls for this purpose.
1379 *
1380 * Failing 7/1/2, we look for 7/1/3, even though it's probably not
1381 * stream-compatible, because this matches the behaviour of the old code.
1382 *
1383 * If nothing else, we bind to 7/1/1 - the unidirectional interface.
1384 */
1385static int usblp_select_alts(struct usblp *usblp)
1386{
1387	struct usb_interface *if_alt;
1388	struct usb_interface_descriptor *ifd;
1389	struct usb_endpoint_descriptor *epd, *epwrite, *epread;
1390	int p, i, e;
1391
1392	if_alt = &usblp->dev->actconfig->interface[usblp->ifnum];
1393
1394	for (p = 0; p < USBLP_MAX_PROTOCOLS; p++)
1395		usblp->protocol[p].alt_setting = -1;
1396
1397	/* Find out what we have. */
1398	for (i = 0; i < if_alt->num_altsetting; i++) {
1399		ifd = &if_alt->altsetting[i];
1400
1401		if (ifd->bInterfaceClass != 7 || ifd->bInterfaceSubClass != 1)
1402			continue;
1403
1404		if (ifd->bInterfaceProtocol < USBLP_FIRST_PROTOCOL ||
1405		    ifd->bInterfaceProtocol > USBLP_LAST_PROTOCOL)
1406			continue;
1407
1408		/* Look for bulk OUT and IN endpoints. */
1409		epwrite = epread = 0;
1410		for (e = 0; e < ifd->bNumEndpoints; e++) {
1411			epd = &ifd->endpoint[e];
1412
1413			if ((epd->bmAttributes&USB_ENDPOINT_XFERTYPE_MASK)!=
1414			    USB_ENDPOINT_XFER_BULK)
1415				continue;
1416
1417			if (!(epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK)) {
1418				if (!epwrite) epwrite=epd;
1419
1420			} else {
1421				if (!epread) epread=epd;
1422			}
1423		}
1424
1425		/* Ignore buggy hardware without the right endpoints. */
1426		if (!epwrite || (ifd->bInterfaceProtocol > 1 && !epread))
1427			continue;
1428
1429		/* Turn off reads for 7/1/1 (unidirectional) interfaces
1430		 * and buggy bidirectional printers. */
1431		if (ifd->bInterfaceProtocol == 1) {
1432			epread = NULL;
1433		} else if (usblp->quirks & USBLP_QUIRK_BIDIR) {
1434			info("Disabling reads from problem bidirectional "
1435				"printer on usblp%d", usblp->minor);
1436			epread = NULL;
1437		}
1438
1439		usblp->protocol[ifd->bInterfaceProtocol].alt_setting = i;
1440		usblp->protocol[ifd->bInterfaceProtocol].epwrite = epwrite;
1441		usblp->protocol[ifd->bInterfaceProtocol].epread = epread;
1442	}
1443
1444	/* If our requested protocol is supported, then use it. */
1445	if (proto_bias >= USBLP_FIRST_PROTOCOL &&
1446	    proto_bias <= USBLP_LAST_PROTOCOL &&
1447	    usblp->protocol[proto_bias].alt_setting != -1)
1448		return proto_bias;
1449
1450	/* Ordering is important here. */
1451	if (usblp->protocol[2].alt_setting != -1) return 2;
1452	if (usblp->protocol[1].alt_setting != -1) return 1;
1453	if (usblp->protocol[3].alt_setting != -1) return 3;
1454
1455	/* If nothing is available, then don't bind to this device. */
1456	return -1;
1457}
1458
1459static int usblp_set_protocol(struct usblp *usblp, int protocol)
1460{
1461	int r, alts;
1462
1463	if (protocol < USBLP_FIRST_PROTOCOL || protocol > USBLP_LAST_PROTOCOL)
1464		return -EINVAL;
1465
1466	alts = usblp->protocol[protocol].alt_setting;
1467	if (alts < 0) return -EINVAL;
1468	r = usb_set_interface(usblp->dev, usblp->ifnum, alts);
1469	if (r < 0) {
1470		err("can't set desired altsetting %d on interface %d",
1471			alts, usblp->ifnum);
1472		return r;
1473	}
1474
1475	usb_fill_bulk_urb(usblp->writeurb, usblp->dev,
1476		usb_sndbulkpipe(usblp->dev,
1477		  usblp->protocol[protocol].epwrite->bEndpointAddress),
1478		usblp->writebuf, 0,
1479		usblp_bulk_write, usblp);
1480
1481	usblp->bidir = (usblp->protocol[protocol].epread != 0);
1482	if (usblp->bidir)
1483		usb_fill_bulk_urb(usblp->readurb, usblp->dev,
1484			usb_rcvbulkpipe(usblp->dev,
1485			  usblp->protocol[protocol].epread->bEndpointAddress),
1486			usblp->readbuf, USBLP_BUF_SIZE,
1487			usblp_bulk_read, usblp);
1488
1489	usblp->current_protocol = protocol;
1490	dbg("usblp%d set protocol %d", usblp->minor, protocol);
1491	return 0;
1492}
1493
1494/* Retrieves and caches device ID string.
1495 * Returns length, including length bytes but not null terminator.
1496 * On error, returns a negative errno value. */
1497static int usblp_cache_device_id_string(struct usblp *usblp)
1498{
1499	int err, length;
1500
1501	err = usblp_get_id(usblp, 0, usblp->device_id_string, USBLP_DEVICE_ID_SIZE - 1);
1502	if (err < 0) {
1503		dbg("usblp%d: error = %d reading IEEE-1284 Device ID string",
1504			usblp->minor, err);
1505		usblp->device_id_string[0] = usblp->device_id_string[1] = '\0';
1506		return -EIO;
1507	}
1508
1509	/* First two bytes are length in big-endian.
1510	 * They count themselves, and we copy them into
1511	 * the user's buffer. */
1512	length = (usblp->device_id_string[0] << 8) + usblp->device_id_string[1];
1513	if (length < 2)
1514		length = 2;
1515	else if (length >= USBLP_DEVICE_ID_SIZE)
1516		length = USBLP_DEVICE_ID_SIZE - 1;
1517	usblp->device_id_string[length] = '\0';
1518
1519	dbg("usblp%d Device ID string [len=%d]=\"%s\"",
1520		usblp->minor, length, &usblp->device_id_string[2]);
1521
1522	return length;
1523}
1524
1525static void usblp_disconnect(struct usb_device *dev, void *ptr)
1526{
1527	struct usblp *usblp = ptr;
1528
1529	if (!usblp || !usblp->dev) {
1530		err("bogus disconnect");
1531		BUG ();
1532	}
1533
1534	down (&usblp->sem);
1535	lock_kernel();
1536	usblp->present = 0;
1537
1538	usblp_unlink_urbs(usblp);
1539
1540	if (!usblp->used)
1541		usblp_cleanup (usblp);
1542	else 	/* cleanup later, on release */
1543		up (&usblp->sem);
1544	unlock_kernel();
1545}
1546
1547static struct usb_device_id usblp_ids [] = {
1548	{ USB_DEVICE_INFO(7, 1, 1) },
1549	{ USB_DEVICE_INFO(7, 1, 2) },
1550	{ USB_DEVICE_INFO(7, 1, 3) },
1551	{ USB_INTERFACE_INFO(7, 1, 1) },
1552	{ USB_INTERFACE_INFO(7, 1, 2) },
1553	{ USB_INTERFACE_INFO(7, 1, 3) },
1554	{ }						/* Terminating entry */
1555};
1556
1557MODULE_DEVICE_TABLE (usb, usblp_ids);
1558
1559static struct usb_driver usblp_driver = {
1560	name:		"usblp",
1561	probe:		usblp_probe,
1562	disconnect:	usblp_disconnect,
1563	fops:		&usblp_fops,
1564	minor:		USBLP_MINOR_BASE,
1565	id_table:	usblp_ids,
1566};
1567
1568static int __init usblp_init(void)
1569{
1570	if (usb_register(&usblp_driver))
1571		return -1;
1572	info(DRIVER_VERSION ": " DRIVER_DESC);
1573	return 0;
1574}
1575
1576static void __exit usblp_exit(void)
1577{
1578	usb_deregister(&usblp_driver);
1579}
1580
1581module_init(usblp_init);
1582module_exit(usblp_exit);
1583
1584MODULE_AUTHOR( DRIVER_AUTHOR );
1585MODULE_DESCRIPTION( DRIVER_DESC );
1586MODULE_PARM(proto_bias, "i");
1587MODULE_PARM_DESC(proto_bias, "Favourite protocol number");
1588MODULE_LICENSE("GPL");
1589