1 /* sane - Scanner Access Now Easy.
2    Copyright (C) 1997 Geoffrey T. Dairiki
3    This file is part of the SANE package.
4 
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9 
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14 
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 
18    As a special exception, the authors of SANE give permission for
19    additional uses of the libraries contained in this release of SANE.
20 
21    The exception is that, if you link a SANE library with other files
22    to produce an executable, this does not by itself cause the
23    resulting executable to be covered by the GNU General Public
24    License.  Your use of that executable is in no way restricted on
25    account of linking the SANE library code into it.
26 
27    This exception does not, however, invalidate any other reasons why
28    the executable file might be covered by the GNU General Public
29    License.
30 
31    If you submit changes to SANE to the maintainers to be included in
32    a subsequent release, you agree by submitting the changes that
33    those changes may be distributed with this exception intact.
34 
35    If you write modifications of your own for SANE, it is your choice
36    whether to permit this exception to apply to your modifications.
37    If you do not wish that, delete this exception notice.
38 
39    This file is part of a SANE backend for HP Scanners supporting
40    HP Scanner Control Language (SCL).
41 */
42 
43 /*
44    Revision 1.15  2008/03/28 14:37:36  kitno-guest
45    add usleep to improve usb performance, from jim a t meyering d o t net
46 
47    Revision 1.14  2004-10-04 18:09:05  kig-guest
48    Rename global function hp_init_openfd to sanei_hp_init_openfd
49 
50    Revision 1.13  2004/03/27 13:52:39  kig-guest
51    Keep USB-connection open (was problem with Linux 2.6.x)
52 
53    Revision 1.12  2003/10/09 19:34:57  kig-guest
54    Redo when TEST UNIT READY failed
55    Redo when read returns with 0 bytes (non-SCSI only)
56 */
57 
58 /*
59 #define STUBS
60 extern int sanei_debug_hp;*/
61 #define DEBUG_DECLARE_ONLY
62 #include "../include/sane/config.h"
63 #include "../include/lalloca.h"		/* Must be first */
64 
65 #ifdef HAVE_UNISTD_H
66 # include <unistd.h>
67 #endif
68 #include <stdlib.h>
69 #include <ctype.h>
70 #include <stdio.h>
71 #include <string.h>
72 #include <errno.h>
73 #include "../include/lassert.h"
74 #include <signal.h>
75 #include <sys/types.h>
76 #include <sys/stat.h>
77 #include <fcntl.h>
78 #include "../include/sane/sanei_scsi.h"
79 #include "../include/sane/sanei_usb.h"
80 #include "../include/sane/sanei_pio.h"
81 
82 #include "hp.h"
83 
84 #include "../include/sane/sanei_backend.h"
85 
86 #include "hp-option.h"
87 #include "hp-scsi.h"
88 #include "hp-scl.h"
89 #include "hp-device.h"
90 
91 #define HP_SCSI_INQ_LEN		(36)
92 #define HP_SCSI_CMD_LEN		(6)
93 #define HP_SCSI_BUFSIZ	(HP_SCSI_MAX_WRITE + HP_SCSI_CMD_LEN)
94 
95 #define HP_MAX_OPEN_FD 16
96 static struct hp_open_fd_s  /* structure to save info about open file descriptor */
97 {
98     char *devname;
99     HpConnect connect;
100     int fd;
101 } asHpOpenFd[HP_MAX_OPEN_FD];
102 
103 
104 /*
105  *
106  */
107 struct hp_scsi_s
108 {
109     int		fd;
110     char      * devname;
111 
112     /* Output buffering */
113     hp_byte_t	buf[HP_SCSI_BUFSIZ];
114     hp_byte_t *	bufp;
115 
116     hp_byte_t	inq_data[HP_SCSI_INQ_LEN];
117 };
118 
119 #define HP_TMP_BUF_SIZE (1024*4)
120 #define HP_WR_BUF_SIZE (1024*4)
121 
122 typedef struct
123 {
124   HpProcessData procdata;
125 
126   int outfd;
127   const unsigned char *map;
128 
129   unsigned char *image_buf; /* Buffer to store complete image (if req.) */
130   unsigned char *image_ptr;
131   int image_buf_size;
132 
133   unsigned char *tmp_buf; /* Buffer for scan data to get even number of bytes */
134   int tmp_buf_size;
135   int tmp_buf_len;
136 
137   unsigned char wr_buf[HP_WR_BUF_SIZE];
138   unsigned char *wr_ptr;
139   int wr_buf_size;
140   int wr_left;
141 } PROCDATA_HANDLE;
142 
143 
144 /* Initialize structure where we remember out open file descriptors */
145 void
sanei_hp_init_openfdnull146 sanei_hp_init_openfd ()
147 {int iCount;
148  memset (asHpOpenFd, 0, sizeof (asHpOpenFd));
149 
150  for (iCount = 0; iCount < HP_MAX_OPEN_FD; iCount++)
151      asHpOpenFd[iCount].fd = -1;
152 }
153 
154 
155 /* Look if the device is still open */
156 static SANE_Status
hp_GetOpenDevice(const char *devname, HpConnect connect, int *pfd)157 hp_GetOpenDevice (const char *devname, HpConnect connect, int *pfd)
158 
159 {int iCount;
160 
161  for (iCount = 0; iCount < HP_MAX_OPEN_FD; iCount++)
162      {
163      if (!asHpOpenFd[iCount].devname) continue;
164      if (   (strcmp (asHpOpenFd[iCount].devname, devname) == 0)
165          && (asHpOpenFd[iCount].connect == connect) )
166          {
167          if (pfd) *pfd = asHpOpenFd[iCount].fd;
168          DBG(3, "hp_GetOpenDevice: device %s is open with fd=%d\n", devname,
169              asHpOpenFd[iCount].fd);
170          return SANE_STATUS_GOOD;
171          }
172      }
173  DBG(3, "hp_GetOpenDevice: device %s not open\n", devname);
174  return SANE_STATUS_INVAL;
175 }
176 
177 /* Add an open file descriptor. This also decides */
178 /* if we keep a connection open or not. */
179 static SANE_Status
hp_AddOpenDevice(const char *devname, HpConnect connect, int fd)180 hp_AddOpenDevice (const char *devname, HpConnect connect, int fd)
181 
182 {int iCount, iKeepOpen;
183  static int iInitKeepFlags = 1;
184 
185  /* The default values which connections to keep open or not */
186  static int iKeepOpenSCSI = 0;
187  static int iKeepOpenUSB = 1;
188  static int iKeepOpenDevice = 0;
189  static int iKeepOpenPIO = 0;
190 
191  if (iInitKeepFlags) /* Change the defaults by environment */
192      {char *eptr;
193 
194      iInitKeepFlags = 0;
195 
196      eptr = getenv ("SANE_HP_KEEPOPEN_SCSI");
197      if ( (eptr != NULL) && ((*eptr == '0') || (*eptr == '1')) )
198          iKeepOpenSCSI = (*eptr == '1');
199 
200      eptr = getenv ("SANE_HP_KEEPOPEN_USB");
201      if ( (eptr != NULL) && ((*eptr == '0') || (*eptr == '1')) )
202          iKeepOpenUSB = (*eptr == '1');
203 
204      eptr = getenv ("SANE_HP_KEEPOPEN_DEVICE");
205      if ( (eptr != NULL) && ((*eptr == '0') || (*eptr == '1')) )
206          iKeepOpenDevice = (*eptr == '1');
207 
208      eptr = getenv ("SANE_HP_KEEPOPEN_PIO");
209      if ( (eptr != NULL) && ((*eptr == '0') || (*eptr == '1')) )
210          iKeepOpenPIO = (*eptr == '1');
211      }
212 
213  /* Look if we should keep it open or not */
214  iKeepOpen = 0;
215  switch (connect)
216      {
217      case HP_CONNECT_SCSI: iKeepOpen = iKeepOpenSCSI;
218                            break;
219      case HP_CONNECT_PIO : iKeepOpen = iKeepOpenPIO;
220                            break;
221      case HP_CONNECT_USB : iKeepOpen = iKeepOpenUSB;
222                            break;
223      case HP_CONNECT_DEVICE : iKeepOpen = iKeepOpenDevice;
224                            break;
225      case HP_CONNECT_RESERVE:
226                            break;
227      }
228  if (!iKeepOpen)
229      {
230      DBG(3, "hp_AddOpenDevice: %s should not be kept open\n", devname);
231      return SANE_STATUS_INVAL;
232      }
233 
234  for (iCount = 0; iCount < HP_MAX_OPEN_FD; iCount++)
235      {
236      if (!asHpOpenFd[iCount].devname)  /* Is this entry free ? */
237          {
238          asHpOpenFd[iCount].devname = sanei_hp_strdup (devname);
239          if (!asHpOpenFd[iCount].devname) return SANE_STATUS_NO_MEM;
240          DBG(3, "hp_AddOpenDevice: added device %s with fd=%d\n", devname, fd);
241          asHpOpenFd[iCount].connect = connect;
242          asHpOpenFd[iCount].fd = fd;
243          return SANE_STATUS_GOOD;
244          }
245      }
246  DBG(3, "hp_AddOpenDevice: %s not added\n", devname);
247  return SANE_STATUS_NO_MEM;
248 }
249 
250 
251 /* Check if we have remembered an open file descriptor */
252 static SANE_Status
hp_IsOpenFd(int fd, HpConnect connect)253 hp_IsOpenFd (int fd, HpConnect connect)
254 
255 {int iCount;
256 
257  for (iCount = 0; iCount < HP_MAX_OPEN_FD; iCount++)
258      {
259      if (   (asHpOpenFd[iCount].devname != NULL)
260          && (asHpOpenFd[iCount].fd == fd)
261          && (asHpOpenFd[iCount].connect == connect) )
262          {
263          DBG(3, "hp_IsOpenFd: %d is open\n", fd);
264          return SANE_STATUS_GOOD;
265          }
266      }
267  DBG(3, "hp_IsOpenFd: %d not open\n", fd);
268  return SANE_STATUS_INVAL;
269 }
270 
271 
272 static SANE_Status
hp_RemoveOpenFd(int fd, HpConnect connect)273 hp_RemoveOpenFd (int fd, HpConnect connect)
274 
275 {int iCount;
276 
277  for (iCount = 0; iCount < HP_MAX_OPEN_FD; iCount++)
278      {
279      if (   (asHpOpenFd[iCount].devname != NULL)
280          && (asHpOpenFd[iCount].fd == fd)
281          && (asHpOpenFd[iCount].connect == connect) )
282          {
283          sanei_hp_free (asHpOpenFd[iCount].devname);
284          asHpOpenFd[iCount].devname = NULL;
285          DBG(3, "hp_RemoveOpenFd: removed %d\n", asHpOpenFd[iCount].fd);
286          asHpOpenFd[iCount].fd = -1;
287          return SANE_STATUS_GOOD;
288          }
289      }
290  DBG(3, "hp_RemoveOpenFd: %d not removed\n", fd);
291  return SANE_STATUS_INVAL;
292 }
293 
294 
295 static SANE_Status
hp_nonscsi_write(HpScsi this, hp_byte_t *data, size_t len, HpConnect connect)296 hp_nonscsi_write (HpScsi this, hp_byte_t *data, size_t len, HpConnect connect)
297 
298 {int n = -1;
299  size_t loc_len;
300  SANE_Status status = SANE_STATUS_GOOD;
301 
302  if (len <= 0) return SANE_STATUS_GOOD;
303 
304  switch (connect)
305  {
306    case HP_CONNECT_DEVICE:   /* direct device-io */
307      n = write (this->fd, data, len);
308      break;
309 
310    case HP_CONNECT_PIO:      /* Use sanepio interface */
311      n = sanei_pio_write (this->fd, data, len);
312      break;
313 
314    case HP_CONNECT_USB:      /* Not supported */
315      loc_len = len;
316      status = sanei_usb_write_bulk ((SANE_Int)this->fd, data, &loc_len);
317      n = loc_len;
318      break;
319 
320    case HP_CONNECT_RESERVE:
321      n = -1;
322      break;
323 
324    default:
325      n = -1;
326      break;
327  }
328 
329  if (n == 0) return SANE_STATUS_EOF;
330  else if (n < 0) return SANE_STATUS_IO_ERROR;
331 
332  return status;
333 }
334 
335 static SANE_Status
hp_nonscsi_read(HpScsi this, hp_byte_t *data, size_t *len, HpConnect connect, int __sane_unused__ isResponse)336 hp_nonscsi_read (HpScsi this, hp_byte_t *data, size_t *len, HpConnect connect,
337   int __sane_unused__ isResponse)
338 
339 {int n = -1;
340  static int retries = -1;
341  size_t save_len = *len;
342  SANE_Status status = SANE_STATUS_GOOD;
343 
344  if (*len <= 0) return SANE_STATUS_GOOD;
345 
346  if (retries < 0)  /* Read environment */
347  {char *eptr = getenv ("SANE_HP_RDREDO");
348 
349    retries = 1;       /* Set default value */
350    if (eptr != NULL)
351    {
352      if (sscanf (eptr, "%d", &retries) != 1) retries = 1; /* Restore default */
353      else if (retries < 0) retries = 0; /* Allow no retries here */
354    }
355  }
356 
357  for (;;) /* Retry on EOF */
358  {
359    switch (connect)
360    {
361      case HP_CONNECT_DEVICE:
362        n = read (this->fd, data, *len);
363        break;
364 
365      case HP_CONNECT_PIO:
366        n = sanei_pio_read (this->fd, data, *len);
367        break;
368 
369      case HP_CONNECT_USB:
370        status = sanei_usb_read_bulk((SANE_Int)this->fd, (SANE_Byte *)data, len);
371        n = *len;
372        break;
373 
374      case HP_CONNECT_RESERVE:
375        n = -1;
376        break;
377 
378      default:
379        n = -1;
380        break;
381    }
382    if ((n != 0) || (retries <= 0)) break;
383    retries--;
384    usleep (100*1000);  /* sleep 0.1 seconds */
385    *len = save_len;    /* Restore value */
386  }
387 
388  if (n == 0) return SANE_STATUS_EOF;
389  else if (n < 0) return SANE_STATUS_IO_ERROR;
390 
391  *len = n;
392  return status;
393 }
394 
395 static SANE_Status
hp_nonscsi_open(const char *devname, int *fd, HpConnect connect)396 hp_nonscsi_open (const char *devname, int *fd, HpConnect connect)
397 
398 {int lfd, flags;
399  SANE_Int dn;
400  SANE_Status status = SANE_STATUS_INVAL;
401 
402 #ifdef _O_RDWR
403  flags = _O_RDWR;
404 #else
405  flags = O_RDWR;
406 #endif
407 #ifdef _O_EXCL
408  flags |= _O_EXCL;
409 #else
410  flags |= O_EXCL;
411 #endif
412 #ifdef _O_BINARY
413  flags |= _O_BINARY;
414 #endif
415 #ifdef O_BINARY
416  flags |= O_BINARY;
417 #endif
418 
419  switch (connect)
420  {
421    case HP_CONNECT_DEVICE:
422      lfd = open (devname, flags);
423      if (lfd < 0)
424      {
425         DBG(1, "hp_nonscsi_open: open device %s failed (%s)\n", devname,
426             strerror (errno) );
427        status = (errno == EACCES) ? SANE_STATUS_ACCESS_DENIED : SANE_STATUS_INVAL;
428      }
429      else
430        status = SANE_STATUS_GOOD;
431      break;
432 
433    case HP_CONNECT_PIO:
434      status = sanei_pio_open (devname, &lfd);
435      break;
436 
437    case HP_CONNECT_USB:
438      DBG(17, "hp_nonscsi_open: open usb with \"%s\"\n", devname);
439      status = sanei_usb_open (devname, &dn);
440      lfd = (int)dn;
441      break;
442 
443    case HP_CONNECT_RESERVE:
444      status = SANE_STATUS_INVAL;
445      break;
446 
447    default:
448      status = SANE_STATUS_INVAL;
449      break;
450  }
451 
452  if (status != SANE_STATUS_GOOD)
453  {
454     DBG(1, "hp_nonscsi_open: open device %s failed\n", devname);
455  }
456  else
457  {
458     DBG(17,"hp_nonscsi_open: device %s opened, fd=%d\n", devname, lfd);
459  }
460 
461  if (fd) *fd = lfd;
462 
463  return status;
464 }
465 
466 static void
hp_nonscsi_close(int fd, HpConnect connect)467 hp_nonscsi_close (int fd, HpConnect connect)
468 
469 {
470  switch (connect)
471  {
472    case HP_CONNECT_DEVICE:
473      close (fd);
474      break;
475 
476    case HP_CONNECT_PIO:
477      sanei_pio_close (fd);
478      break;
479 
480    case HP_CONNECT_USB:
481      sanei_usb_close (fd);
482      break;
483 
484    case HP_CONNECT_RESERVE:
485      break;
486 
487    default:
488      break;
489  }
490  DBG(17,"hp_nonscsi_close: closed fd=%d\n", fd);
491 }
492 
493 SANE_Status
sanei_hp_nonscsi_new(HpScsi * newp, const char * devname, HpConnect connect)494 sanei_hp_nonscsi_new (HpScsi * newp, const char * devname, HpConnect connect)
495 {
496  HpScsi new;
497  SANE_Status status;
498  int iAlreadyOpen = 0;
499 
500   new = sanei_hp_allocz(sizeof(*new));
501   if (!new)
502     return SANE_STATUS_NO_MEM;
503 
504   /* Is the device already open ? */
505   if ( hp_GetOpenDevice (devname, connect, &new->fd) == SANE_STATUS_GOOD )
506   {
507     iAlreadyOpen = 1;
508   }
509   else
510   {
511     status = hp_nonscsi_open(devname, &new->fd, connect);
512     if (FAILED(status))
513     {
514       DBG(1, "nonscsi_new: open failed (%s)\n", sane_strstatus(status));
515       sanei_hp_free(new);
516       return SANE_STATUS_IO_ERROR;
517     }
518   }
519 
520   /* For SCSI-devices we would have the inquire command here */
521   memcpy (new->inq_data, "\003zzzzzzzHP      ------          R000",
522           sizeof (new->inq_data));
523 
524   new->bufp = new->buf + HP_SCSI_CMD_LEN;
525   new->devname = sanei_hp_alloc ( strlen ( devname ) + 1 );
526   if ( new->devname ) strcpy (new->devname, devname);
527 
528   *newp = new;
529 
530   /* Remember the open device */
531   if (!iAlreadyOpen) hp_AddOpenDevice (devname, connect, new->fd);
532 
533   return SANE_STATUS_GOOD;
534 }
535 
536 static void
hp_scsi_close(HpScsi this, int completely)537 hp_scsi_close (HpScsi this, int completely)
538 {HpConnect connect;
539 
540  DBG(3, "scsi_close: closing fd %ld\n", (long)this->fd);
541 
542  connect = sanei_hp_scsi_get_connect (this);
543 
544  if (!completely)  /* May we keep the device open ? */
545  {
546    if ( hp_IsOpenFd (this->fd, connect) == SANE_STATUS_GOOD )
547    {
548      DBG(3, "scsi_close: not closing. Keep open\n");
549      return;
550    }
551 
552  }
553  assert(this->fd >= 0);
554 
555  if (connect != HP_CONNECT_SCSI)
556    hp_nonscsi_close (this->fd, connect);
557  else
558    sanei_scsi_close (this->fd);
559 
560  DBG(3,"scsi_close: really closed\n");
561 
562  /* Remove a remembered open device */
563  hp_RemoveOpenFd (this->fd, connect);
564 }
565 
566 
567 SANE_Status
sanei_hp_scsi_new(HpScsi * newp, const char * devname)568 sanei_hp_scsi_new (HpScsi * newp, const char * devname)
569 {
570   static hp_byte_t inq_cmd[] = { 0x12, 0, 0, 0, HP_SCSI_INQ_LEN, 0};
571   static hp_byte_t tur_cmd[] = { 0x00, 0, 0, 0, 0, 0};
572   size_t	inq_len		= HP_SCSI_INQ_LEN;
573   HpScsi	new;
574   HpConnect     connect;
575   SANE_Status	status;
576   int iAlreadyOpen = 0;
577 
578   connect = sanei_hp_get_connect (devname);
579 
580   if (connect != HP_CONNECT_SCSI)
581     return sanei_hp_nonscsi_new (newp, devname, connect);
582 
583   new = sanei_hp_allocz(sizeof(*new));
584   if (!new)
585       return SANE_STATUS_NO_MEM;
586 
587   /* Is the device still open ? */
588   if ( hp_GetOpenDevice (devname, connect, &new->fd) == SANE_STATUS_GOOD )
589   {
590     iAlreadyOpen = 1;
591   }
592   else
593   {
594     status = sanei_scsi_open(devname, &new->fd, 0, 0);
595     if (FAILED(status))
596       {
597         DBG(1, "scsi_new: open failed (%s)\n", sane_strstatus(status));
598         sanei_hp_free(new);
599         return SANE_STATUS_IO_ERROR;
600       }
601   }
602 
603   DBG(3, "scsi_inquire: sending INQUIRE\n");
604   status = sanei_scsi_cmd(new->fd, inq_cmd, 6, new->inq_data, &inq_len);
605   if (FAILED(status))
606     {
607       DBG(1, "scsi_inquire: inquiry failed: %s\n", sane_strstatus(status));
608       sanei_scsi_close(new->fd);
609       sanei_hp_free(new);
610       return status;
611     }
612 
613   {char vendor[9], model[17], rev[5];
614    memset (vendor, 0, sizeof (vendor));
615    memset (model, 0, sizeof (model));
616    memset (rev, 0, sizeof (rev));
617    memcpy (vendor, new->inq_data + 8, 8);
618    memcpy (model, new->inq_data + 16, 16);
619    memcpy (rev, new->inq_data + 32, 4);
620 
621    DBG(3, "vendor=%s, model=%s, rev=%s\n", vendor, model, rev);
622   }
623 
624   DBG(3, "scsi_new: sending TEST_UNIT_READY\n");
625   status = sanei_scsi_cmd(new->fd, tur_cmd, 6, 0, 0);
626   if (FAILED(status))
627     {
628       DBG(1, "hp_scsi_open: test unit ready failed (%s)\n",
629 	  sane_strstatus(status));
630       usleep (500*1000); /* Wait 0.5 seconds */
631       DBG(3, "scsi_new: sending TEST_UNIT_READY second time\n");
632       status = sanei_scsi_cmd(new->fd, tur_cmd, 6, 0, 0);
633     }
634 
635   if (FAILED(status))
636     {
637       DBG(1, "hp_scsi_open: test unit ready failed (%s)\n",
638 	  sane_strstatus(status));
639 
640       sanei_scsi_close(new->fd);
641       sanei_hp_free(new);
642       return status; /* Fix problem with non-scanner devices */
643     }
644 
645   new->bufp = new->buf + HP_SCSI_CMD_LEN;
646   new->devname = sanei_hp_alloc ( strlen ( devname ) + 1 );
647   if ( new->devname ) strcpy (new->devname, devname);
648 
649   *newp = new;
650 
651   /* Remember the open device */
652   if (!iAlreadyOpen) hp_AddOpenDevice (devname, connect, new->fd);
653 
654   return SANE_STATUS_GOOD;
655 }
656 
657 
658 
659 /* The "completely" parameter was added for OfficeJet support.
660  * For JetDirect connections, closing and re-opening the scan
661  * channel is very time consuming.  Also, the OfficeJet G85
662  * unloads a loaded document in the ADF when the scan channel
663  * gets closed.  The solution is to "completely" destroy the
664  * connection, including closing and deallocating the PTAL
665  * channel, when initially probing the device in hp-device.c,
666  * but leave it open while the frontend is actually using the
667  * device (from hp-handle.c), and "completely" destroy it when
668  * the frontend closes its handle. */
669 void
sanei_hp_scsi_destroy(HpScsi this,int completely)670 sanei_hp_scsi_destroy (HpScsi this,int completely)
671 {
672   /* Moved to hp_scsi_close():
673    * assert(this->fd >= 0);
674    * DBG(3, "scsi_close: closing fd %d\n", this->fd);
675    */
676 
677   hp_scsi_close (this, completely);
678   if ( this->devname ) sanei_hp_free (this->devname);
679   sanei_hp_free(this);
680 }
681 
682 hp_byte_t *
sanei_hp_scsi_inq(HpScsi this)683 sanei_hp_scsi_inq (HpScsi this)
684 {
685   return this->inq_data;
686 }
687 
688 const char *
sanei_hp_scsi_vendor(HpScsi this)689 sanei_hp_scsi_vendor (HpScsi this)
690 {
691   static char buf[9];
692   memcpy(buf, sanei_hp_scsi_inq(this) + 8, 8);
693   buf[8] = '\0';
694   return buf;
695 }
696 
697 const char *
sanei_hp_scsi_model(HpScsi this)698 sanei_hp_scsi_model (HpScsi this)
699 {
700 
701   static char buf[17];
702   memcpy(buf, sanei_hp_scsi_inq(this) + 16, 16);
703   buf[16] = '\0';
704   return buf;
705 }
706 
707 const char *
sanei_hp_scsi_devicename(HpScsi this)708 sanei_hp_scsi_devicename (HpScsi this)
709 {
710   return this->devname;
711 }
712 
713 hp_bool_t
sanei_hp_is_active_xpa(HpScsi scsi)714 sanei_hp_is_active_xpa (HpScsi scsi)
715 {HpDeviceInfo *info;
716  int model_num;
717 
718  info = sanei_hp_device_info_get ( sanei_hp_scsi_devicename  (scsi) );
719  if (info->active_xpa < 0)
720  {
721    model_num = sanei_hp_get_max_model (scsi);
722    info->active_xpa = (model_num >= 17);
723    DBG(5,"sanei_hp_is_active_xpa: model=%d, active_xpa=%d\n",
724        model_num, info->active_xpa);
725  }
726  return info->active_xpa;
727 }
728 
729 int
sanei_hp_get_max_model(HpScsi scsi)730 sanei_hp_get_max_model (HpScsi scsi)
731 
732 {HpDeviceInfo *info;
733 
734  info = sanei_hp_device_info_get ( sanei_hp_scsi_devicename  (scsi) );
735  if (info->max_model < 0)
736  {enum hp_device_compat_e compat;
737   int model_num;
738 
739    if ( sanei_hp_device_probe_model ( &compat, scsi, &model_num, 0)
740             == SANE_STATUS_GOOD )
741      info->max_model = model_num;
742  }
743  return info->max_model;
744 }
745 
746 
747 int
sanei_hp_is_flatbed_adf(HpScsi scsi)748 sanei_hp_is_flatbed_adf (HpScsi scsi)
749 
750 {int model = sanei_hp_get_max_model (scsi);
751 
752  return ((model == 2) || (model == 4) || (model == 5) || (model == 8));
753 }
754 
755 
756 HpConnect
sanei_hp_get_connect(const char *devname)757 sanei_hp_get_connect (const char *devname)
758 
759 {const HpDeviceInfo *info;
760  HpConnect connect = HP_CONNECT_SCSI;
761  int got_connect_type = 0;
762 
763  info = sanei_hp_device_info_get (devname);
764  if (!info)
765  {
766    DBG(1, "sanei_hp_get_connect: Could not get info for %s. Assume SCSI\n",
767        devname);
768    connect = HP_CONNECT_SCSI;
769  }
770  else
771  if ( !(info->config_is_up) )
772  {
773    DBG(1, "sanei_hp_get_connect: Config not initialized for %s. Assume SCSI\n",
774        devname);
775    connect = HP_CONNECT_SCSI;
776  }
777  else
778  {
779    connect = info->config.connect;
780    got_connect_type = info->config.got_connect_type;
781  }
782 
783  /* Beware of using a USB-device as a SCSI-device (not 100% perfect) */
784  if ((connect == HP_CONNECT_SCSI) && !got_connect_type)
785  {int maybe_usb;
786 
787    maybe_usb = (   strstr (devname, "usb")
788                 || strstr (devname, "uscanner")
789                 || strstr (devname, "ugen"));
790    if (maybe_usb)
791    {static int print_warning = 1;
792 
793      if (print_warning)
794      {
795        print_warning = 0;
796        DBG(1,"sanei_hp_get_connect: WARNING\n");
797        DBG(1,"  Device %s assumed to be SCSI, but device name\n",devname);
798        DBG(1,"  looks like USB. Will continue with USB.\n");
799        DBG(1,"  If you really want it as SCSI, add the following\n");
800        DBG(1,"  to your file .../etc/sane.d/hp.conf:\n");
801        DBG(1,"    %s\n", devname);
802        DBG(1,"      option connect-scsi\n");
803        DBG(1,"  The same warning applies to other device names containing\n");
804        DBG(1,"  \"usb\", \"uscanner\" or \"ugen\".\n");
805      }
806      connect = HP_CONNECT_DEVICE;
807    }
808  }
809  return connect;
810 }
811 
812 HpConnect
sanei_hp_scsi_get_connect(HpScsi this)813 sanei_hp_scsi_get_connect (HpScsi this)
814 
815 {
816  return sanei_hp_get_connect (sanei_hp_scsi_devicename (this));
817 }
818 
819 
820 static SANE_Status
hp_scsi_flush(HpScsi this)821 hp_scsi_flush (HpScsi this)
822 {
823   hp_byte_t *	data	= this->buf + HP_SCSI_CMD_LEN;
824   size_t 	len 	= this->bufp - data;
825   HpConnect     connect;
826 
827   assert(len < HP_SCSI_MAX_WRITE);
828   if (len == 0)
829       return SANE_STATUS_GOOD;
830 
831   this->bufp = this->buf;
832 
833   DBG(16, "scsi_flush: writing %lu bytes:\n", (unsigned long) len);
834   DBGDUMP(16, data, len);
835 
836   *this->bufp++ = 0x0A;
837   *this->bufp++ = 0;
838   *this->bufp++ = len >> 16;
839   *this->bufp++ = len >> 8;
840   *this->bufp++ = len;
841   *this->bufp++ = 0;
842 
843   connect = sanei_hp_scsi_get_connect (this);
844   if (connect == HP_CONNECT_SCSI)
845     return sanei_scsi_cmd (this->fd, this->buf, HP_SCSI_CMD_LEN + len, 0, 0);
846   else
847     return hp_nonscsi_write (this, this->buf+HP_SCSI_CMD_LEN, len, connect);
848 }
849 
850 static size_t
hp_scsi_room(HpScsi this)851 hp_scsi_room (HpScsi this)
852 {
853   return this->buf + HP_SCSI_BUFSIZ - this->bufp;
854 }
855 
856 static SANE_Status
hp_scsi_need(HpScsi this, size_t need)857 hp_scsi_need (HpScsi this, size_t need)
858 {
859   assert(need < HP_SCSI_MAX_WRITE);
860 
861   if (need > hp_scsi_room(this))
862       RETURN_IF_FAIL( hp_scsi_flush(this) );
863 
864   return SANE_STATUS_GOOD;
865 }
866 
867 static SANE_Status
hp_scsi_write(HpScsi this, const void *data, size_t len)868 hp_scsi_write (HpScsi this, const void *data, size_t len)
869 {
870   if ( len < HP_SCSI_MAX_WRITE )
871     {
872       RETURN_IF_FAIL( hp_scsi_need(this, len) );
873       memcpy(this->bufp, data, len);
874       this->bufp += len;
875     }
876   else
877     {size_t maxwrite = HP_SCSI_MAX_WRITE - 16;
878      const char *c_data = (const char *)data;
879 
880       while ( len > 0 )
881         {
882           if ( maxwrite > len ) maxwrite = len;
883           RETURN_IF_FAIL( hp_scsi_write(this, c_data, maxwrite) );
884           c_data += maxwrite;
885           len -= maxwrite;
886         }
887     }
888   return SANE_STATUS_GOOD;
889 }
890 
891 static SANE_Status
hp_scsi_scl(HpScsi this, HpScl scl, int val)892 hp_scsi_scl(HpScsi this, HpScl scl, int val)
893 {
894   char	group	= tolower(SCL_GROUP_CHAR(scl));
895   char	param	= toupper(SCL_PARAM_CHAR(scl));
896   int	count;
897 
898   assert(IS_SCL_CONTROL(scl) || IS_SCL_COMMAND(scl));
899   assert(isprint(group) && isprint(param));
900 
901   RETURN_IF_FAIL( hp_scsi_need(this, 10) );
902 
903   /* Don't try to optimize SCL-commands like using <ESC>*a1b0c5T */
904   /* Some scanners have problems with it (e.g. HP Photosmart Photoscanner */
905   /* with window position/extent, resolution) */
906   count = sprintf((char *)this->bufp, "\033*%c%d%c", group, val, param);
907   this->bufp += count;
908 
909   assert(count > 0 && this->bufp < this->buf + HP_SCSI_BUFSIZ);
910 
911   return hp_scsi_flush(this);
912 }
913 
914 /* Read it bytewise */
915 static SANE_Status
hp_scsi_read_slow(HpScsi this, void * dest, size_t *len)916 hp_scsi_read_slow (HpScsi this, void * dest, size_t *len)
917 {static hp_byte_t read_cmd[6] = { 0x08, 0, 0, 0, 0, 0 };
918  size_t leftover = *len;
919  SANE_Status status = SANE_STATUS_GOOD;
920  unsigned char *start_dest = (unsigned char *)dest;
921  unsigned char *next_dest = start_dest;
922 
923  DBG(16, "hp_scsi_read_slow: Start reading %d bytes bytewise\n", (int)*len);
924 
925  while (leftover > 0)  /* Until we got all the bytes */
926  {size_t one = 1;
927 
928    read_cmd[2] = 0;
929    read_cmd[3] = 0;
930    read_cmd[4] = 1;   /* Read one byte */
931 
932    status = sanei_scsi_cmd (this->fd, read_cmd, sizeof(read_cmd),
933                             next_dest, &one);
934    if ((status != SANE_STATUS_GOOD) || (one != 1))
935    {
936      DBG(250,"hp_scsi_read_slow: Reading byte %d: status=%s, len=%d\n",
937          (int)(next_dest-start_dest), sane_strstatus(status), (int)one);
938    }
939 
940    if (status != SANE_STATUS_GOOD) break;  /* Finish on error */
941 
942    next_dest++;
943    leftover--;
944  }
945 
946  *len = next_dest-start_dest; /* This is the number of bytes we got */
947 
948  DBG(16, "hp_scsi_read_slow: Got %d bytes\n", (int)*len);
949 
950  if ((status != SANE_STATUS_GOOD) && (*len > 0))
951  {
952    DBG(16, "We got some data. Ignore the error \"%s\"\n",
953        sane_strstatus(status));
954    status = SANE_STATUS_GOOD;
955  }
956  return status;
957 }
958 
959 /* The OfficeJets tend to return inquiry responses containing array
960  * data in two packets.  The added "isResponse" parameter tells
961  * whether we should keep reading until we get
962  * a well-formed response.  Naturally, this parameter would be zero
963  * when reading scan data. */
964 static SANE_Status
hp_scsi_read(HpScsi this, void * dest, size_t *len, int isResponse)965 hp_scsi_read (HpScsi this, void * dest, size_t *len, int isResponse)
966 {
967   HpConnect connect;
968 
969   RETURN_IF_FAIL( hp_scsi_flush(this) );
970 
971   connect = sanei_hp_scsi_get_connect (this);
972   if (connect == HP_CONNECT_SCSI)
973   {int read_bytewise = 0;
974 
975     if (*len <= 32)   /* Is it a candidate for reading bytewise ? */
976     {const HpDeviceInfo *info;
977 
978       info = sanei_hp_device_info_get (sanei_hp_scsi_devicename (this));
979       if ((info != NULL) && (info->config_is_up) && info->config.dumb_read)
980         read_bytewise = 1;
981     }
982 
983     if ( ! read_bytewise )
984     {static hp_byte_t read_cmd[6] = { 0x08, 0, 0, 0, 0, 0 };
985       read_cmd[2] = *len >> 16;
986       read_cmd[3] = *len >> 8;
987       read_cmd[4] = *len;
988 
989       RETURN_IF_FAIL( sanei_scsi_cmd (this->fd, read_cmd,
990                                       sizeof(read_cmd), dest, len) );
991     }
992     else
993     {
994       RETURN_IF_FAIL (hp_scsi_read_slow (this, dest, len));
995     }
996   }
997   else
998   {
999     RETURN_IF_FAIL( hp_nonscsi_read (this, dest, len, connect, isResponse) );
1000   }
1001   DBG(16, "scsi_read:  %lu bytes:\n", (unsigned long) *len);
1002   DBGDUMP(16, dest, *len);
1003   return SANE_STATUS_GOOD;
1004 }
1005 
1006 
1007 static int signal_caught = 0;
1008 
1009 static void
signal_catcher(int sig)1010 signal_catcher (int sig)
1011 {
1012   DBG(1,"signal_catcher(sig=%d): old signal_caught=%d\n",sig,signal_caught);
1013   if (!signal_caught)
1014       signal_caught = sig;
1015 }
1016 
1017 static void
hp_data_map(register const unsigned char *map, register int count, register unsigned char *data)1018 hp_data_map (register const unsigned char *map, register int count,
1019              register unsigned char *data)
1020 {
1021   if (count <= 0) return;
1022   while (count--)
1023   {
1024     *data = map[*data];
1025     data++;
1026   }
1027 }
1028 
1029 static const unsigned char *
hp_get_simulation_map(const char *devname, const HpDeviceInfo *info)1030 hp_get_simulation_map (const char *devname, const HpDeviceInfo *info)
1031 {
1032  hp_bool_t     sim_gamma, sim_brightness, sim_contrast;
1033  int           k, ind;
1034  const unsigned char *map = NULL;
1035  static unsigned char map8x8[256];
1036 
1037   sim_gamma = info->simulate.gamma_simulate;
1038   sim_brightness = sanei_hp_device_simulate_get (devname, SCL_BRIGHTNESS);
1039   sim_contrast = sanei_hp_device_simulate_get (devname, SCL_CONTRAST);
1040 
1041   if ( sim_gamma )
1042   {
1043     map = &(info->simulate.gamma_map[0]);
1044   }
1045   else if ( sim_brightness && sim_contrast )
1046   {
1047     for (k = 0; k < 256; k++)
1048     {
1049       ind = info->simulate.contrast_map[k];
1050       map8x8[k] = info->simulate.brightness_map[ind];
1051     }
1052     map = &(map8x8[0]);
1053   }
1054   else if ( sim_brightness )
1055     map = &(info->simulate.brightness_map[0]);
1056   else if ( sim_contrast )
1057     map = &(info->simulate.contrast_map[0]);
1058 
1059   return map;
1060 }
1061 
1062 
1063 /* Check the native byte order on the local machine */
1064 static hp_bool_t
is_lowbyte_first_byteorder(void)1065 is_lowbyte_first_byteorder (void)
1066 
1067 {unsigned short testvar = 1;
1068  unsigned char *testptr = (unsigned char *)&testvar;
1069 
1070  if (sizeof (unsigned short) == 2)
1071    return (testptr[0] == 1);
1072  else if (sizeof (unsigned short) == 4)
1073    return ((testptr[0] == 1) || (testptr[2] == 1));
1074  else
1075    return (   (testptr[0] == 1) || (testptr[2] == 1)
1076            || (testptr[4] == 1) || (testptr[6] == 1));
1077 }
1078 
1079 /* The SANE standard defines that 2-byte data must use the full 16 bit range.
1080  * Byte order returned by the backend must be native byte order.
1081  * Scaling to 16 bit and byte order is achieved by hp_scale_to_16bit.
1082  * for >8 bits data, take the two data bytes and scale their content
1083  * to the full 16 bit range, using
1084  *     scaled = unscaled << (newlen - oldlen) +
1085  *              unscaled >> (oldlen - (newlen - oldlen)),
1086  * with newlen=16 and oldlen the original bit depth.
1087  */
1088 static void
hp_scale_to_16bit(int count, register unsigned char *data, int depth, hp_bool_t invert)1089 hp_scale_to_16bit(int count, register unsigned char *data, int depth,
1090                   hp_bool_t invert)
1091 {
1092     register unsigned int tmp;
1093     register unsigned int mask;
1094     register hp_bool_t lowbyte_first = is_lowbyte_first_byteorder ();
1095     unsigned int shift1 = 16 - depth;
1096     unsigned int shift2 = 2*depth - 16;
1097     int k;
1098 
1099     if (count <= 0) return;
1100 
1101     mask = 1;
1102     for (k = 1; k < depth; k++) mask |= (1 << k);
1103 
1104     if (lowbyte_first)
1105     {
1106       while (count--) {
1107          tmp = ((((unsigned int)data[0])<<8) | ((unsigned int)data[1])) & mask;
1108          tmp = (tmp << shift1) + (tmp >> shift2);
1109          if (invert) tmp = ~tmp;
1110          *data++ = tmp & 255U;
1111          *data++ = (tmp >> 8) & 255U;
1112       }
1113     }
1114     else  /* Highbyte first */
1115     {
1116       while (count--) {
1117          tmp = ((((unsigned int)data[0])<<8) | ((unsigned int)data[1])) & mask;
1118          tmp = (tmp << shift1) + (tmp >> shift2);
1119          if (invert) tmp = ~tmp;
1120          *data++ = (tmp >> 8) & 255U;
1121          *data++ = tmp & 255U;
1122       }
1123     }
1124 }
1125 
1126 
1127 static void
hp_scale_to_8bit(int count, register unsigned char *data, int depth, hp_bool_t invert)1128 hp_scale_to_8bit(int count, register unsigned char *data, int depth,
1129                  hp_bool_t invert)
1130 {
1131     register unsigned int tmp, mask;
1132     register hp_bool_t lowbyte_first = is_lowbyte_first_byteorder ();
1133     unsigned int shift1 = depth-8;
1134     int k;
1135     unsigned char *dataout = data;
1136 
1137     if ((count <= 0) || (shift1 <= 0)) return;
1138 
1139     mask = 1;
1140     for (k = 1; k < depth; k++) mask |= (1 << k);
1141 
1142     if (lowbyte_first)
1143     {
1144       while (count--) {
1145          tmp = ((((unsigned int)data[0])<<8) | ((unsigned int)data[1])) & mask;
1146          tmp >>= shift1;
1147          if (invert) tmp = ~tmp;
1148          *(dataout++) = tmp & 255U;
1149          data += 2;
1150       }
1151     }
1152     else  /* Highbyte first */
1153     {
1154       while (count--) {
1155          tmp = ((((unsigned int)data[0])<<8) | ((unsigned int)data[1])) & mask;
1156          tmp >>= shift1;
1157          if (invert) tmp = ~tmp;
1158          *(dataout++) = tmp & 255U;
1159          data += 2;
1160       }
1161     }
1162 }
1163 
1164 static void
hp_soft_invert(int count, register unsigned char *data)1165 hp_soft_invert(int count, register unsigned char *data) {
1166 	while (count>0) {
1167 		*data = ~(*data);
1168 		data++;
1169 		count--;
1170 	}
1171 }
1172 
1173 static PROCDATA_HANDLE *
process_data_init(HpProcessData *procdata, const unsigned char *map, int outfd, hp_bool_t use_imgbuf)1174 process_data_init (HpProcessData *procdata, const unsigned char *map,
1175                    int outfd, hp_bool_t use_imgbuf)
1176 
1177 {PROCDATA_HANDLE *ph = sanei_hp_alloc (sizeof (PROCDATA_HANDLE));
1178  int tsz;
1179 
1180  if (ph == NULL) return NULL;
1181 
1182  memset (ph, 0, sizeof (*ph));
1183  memcpy (&(ph->procdata), procdata, sizeof (*procdata));
1184  procdata = &(ph->procdata);
1185 
1186  tsz = (HP_TMP_BUF_SIZE <= 0) ? procdata->bytes_per_line : HP_TMP_BUF_SIZE;
1187  ph->tmp_buf = sanei_hp_alloc (tsz);
1188  if (ph->tmp_buf == NULL)
1189  {
1190    sanei_hp_free (ph);
1191    return NULL;
1192  }
1193  ph->tmp_buf_size = tsz;
1194  ph->tmp_buf_len = 0;
1195 
1196  ph->map = map;
1197  ph->outfd = outfd;
1198 
1199  if ( procdata->mirror_vertical || use_imgbuf)
1200  {
1201    tsz = procdata->lines*procdata->bytes_per_line;
1202    if (procdata->out8) tsz /= 2;
1203    ph->image_ptr = ph->image_buf = sanei_hp_alloc (tsz);
1204    if ( !ph->image_buf )
1205    {
1206      procdata->mirror_vertical = 0;
1207      ph->image_buf_size = 0;
1208      DBG(1, "process_scanline_init: Not enough memory to mirror image\n");
1209    }
1210    else
1211      ph->image_buf_size = tsz;
1212  }
1213 
1214  ph->wr_ptr = ph->wr_buf;
1215  ph->wr_buf_size = ph->wr_left = sizeof (ph->wr_buf);
1216 
1217  return ph;
1218 }
1219 
1220 
1221 static SANE_Status
process_data_write(PROCDATA_HANDLE *ph, unsigned char *data, int nbytes)1222 process_data_write (PROCDATA_HANDLE *ph, unsigned char *data, int nbytes)
1223 
1224 {int ncopy;
1225 
1226  if (ph == NULL) return SANE_STATUS_INVAL;
1227 
1228  /* Fill up write buffer */
1229  ncopy = ph->wr_left;
1230  if (ncopy > nbytes) ncopy = nbytes;
1231 
1232  memcpy (ph->wr_ptr, data, ncopy);
1233  ph->wr_ptr += ncopy;
1234  ph->wr_left -= ncopy;
1235  data += ncopy;
1236  nbytes -= ncopy;
1237 
1238  if ( ph->wr_left > 0 )  /* Did not fill up the write buffer ? Finished */
1239    return SANE_STATUS_GOOD;
1240 
1241  DBG(12, "process_data_write: write %d bytes\n", ph->wr_buf_size);
1242  /* Don't write data if we got a signal in the meantime */
1243  if (   signal_caught
1244      || (write (ph->outfd, ph->wr_buf, ph->wr_buf_size) != ph->wr_buf_size))
1245  {
1246    DBG(1, "process_data_write: write failed: %s\n",
1247        signal_caught ? "signal caught" : strerror(errno));
1248    return SANE_STATUS_IO_ERROR;
1249  }
1250  ph->wr_ptr = ph->wr_buf;
1251  ph->wr_left = ph->wr_buf_size;
1252 
1253  /* For large amount of data write it from data-buffer */
1254  while ( nbytes > ph->wr_buf_size )
1255  {
1256    if (   signal_caught
1257        || (write (ph->outfd, data, ph->wr_buf_size) != ph->wr_buf_size))
1258    {
1259      DBG(1, "process_data_write: write failed: %s\n",
1260          signal_caught ? "signal caught" : strerror(errno));
1261      return SANE_STATUS_IO_ERROR;
1262    }
1263    nbytes -= ph->wr_buf_size;
1264    data += ph->wr_buf_size;
1265  }
1266 
1267  if ( nbytes > 0 ) /* Something left ? Save it to (empty) write buffer */
1268  {
1269    memcpy (ph->wr_ptr, data, nbytes);
1270    ph->wr_ptr += nbytes;
1271    ph->wr_left -= nbytes;
1272  }
1273  return SANE_STATUS_GOOD;
1274 }
1275 
1276 static SANE_Status
process_scanline(PROCDATA_HANDLE *ph, unsigned char *linebuf, int bytes_per_line)1277 process_scanline (PROCDATA_HANDLE *ph, unsigned char *linebuf,
1278                   int bytes_per_line)
1279 
1280 {int out_bytes_per_line = bytes_per_line;
1281  HpProcessData *procdata;
1282 
1283  if (ph == NULL) return SANE_STATUS_INVAL;
1284  procdata = &(ph->procdata);
1285 
1286  if ( ph->map )
1287    hp_data_map (ph->map, bytes_per_line, linebuf);
1288 
1289  if (procdata->bits_per_channel > 8)
1290  {
1291    if (procdata->out8)
1292    {
1293      hp_scale_to_8bit( bytes_per_line/2, linebuf,
1294                        procdata->bits_per_channel,
1295                        procdata->invert);
1296      out_bytes_per_line /= 2;
1297    }
1298    else
1299    {
1300      hp_scale_to_16bit( bytes_per_line/2, linebuf,
1301                         procdata->bits_per_channel,
1302                         procdata->invert);
1303    }
1304  } else if (procdata->invert) {
1305    hp_soft_invert(bytes_per_line,linebuf);
1306  }
1307 
1308  if ( ph->image_buf )
1309  {
1310    DBG(5, "process_scanline: save in memory\n");
1311 
1312    if (    ph->image_ptr+out_bytes_per_line-1
1313         <= ph->image_buf+ph->image_buf_size-1 )
1314    {
1315      memcpy(ph->image_ptr, linebuf, out_bytes_per_line);
1316      ph->image_ptr += out_bytes_per_line;
1317    }
1318    else
1319    {
1320      DBG(1, "process_scanline: would exceed image buffer\n");
1321    }
1322  }
1323  else /* Save scanlines in a bigger buffer. */
1324  {    /* Otherwise we will get performance problems */
1325 
1326    RETURN_IF_FAIL ( process_data_write (ph, linebuf, out_bytes_per_line) );
1327  }
1328  return SANE_STATUS_GOOD;
1329 }
1330 
1331 
1332 static SANE_Status
process_data(PROCDATA_HANDLE *ph, unsigned char *read_ptr, int nread)1333 process_data (PROCDATA_HANDLE *ph, unsigned char *read_ptr, int nread)
1334 
1335 {int bytes_left;
1336 
1337  if (nread <= 0) return SANE_STATUS_GOOD;
1338 
1339  if (ph == NULL) return SANE_STATUS_INVAL;
1340 
1341  if ( ph->tmp_buf_len > 0 )  /* Something left ? */
1342  {
1343    bytes_left = ph->tmp_buf_size - ph->tmp_buf_len;
1344    if (nread < bytes_left)  /* All to buffer ? */
1345    {
1346      memcpy (ph->tmp_buf+ph->tmp_buf_len, read_ptr, nread);
1347      ph->tmp_buf_len += nread;
1348      return SANE_STATUS_GOOD;
1349    }
1350    memcpy (ph->tmp_buf+ph->tmp_buf_len, read_ptr, bytes_left);
1351    read_ptr += bytes_left;
1352    nread -= bytes_left;
1353    RETURN_IF_FAIL ( process_scanline (ph, ph->tmp_buf, ph->tmp_buf_size) );
1354    ph->tmp_buf_len = 0;
1355  }
1356  while (nread > 0)
1357  {
1358    if (nread >= ph->tmp_buf_size)
1359    {
1360      RETURN_IF_FAIL ( process_scanline (ph, read_ptr, ph->tmp_buf_size) );
1361      read_ptr += ph->tmp_buf_size;
1362      nread -= ph->tmp_buf_size;
1363    }
1364    else
1365    {
1366      memcpy (ph->tmp_buf, read_ptr, nread);
1367      ph->tmp_buf_len = nread;
1368      nread = 0;
1369    }
1370  }
1371  return SANE_STATUS_GOOD;
1372 }
1373 
1374 
1375 static SANE_Status
process_data_flush(PROCDATA_HANDLE *ph)1376 process_data_flush (PROCDATA_HANDLE *ph)
1377 
1378 {SANE_Status status = SANE_STATUS_GOOD;
1379  HpProcessData *procdata;
1380  unsigned char *image_data;
1381  size_t image_len;
1382  int num_lines, bytes_per_line;
1383  int nbytes;
1384 
1385  if (ph == NULL) return SANE_STATUS_INVAL;
1386 
1387  if ( ph->tmp_buf_len > 0 )
1388    process_scanline (ph, ph->tmp_buf, ph->tmp_buf_len);
1389 
1390  if ( ph->wr_left != ph->wr_buf_size ) /* Something in write buffer ? */
1391  {
1392    nbytes = ph->wr_buf_size - ph->wr_left;
1393    if ( signal_caught || (write (ph->outfd, ph->wr_buf, nbytes) != nbytes))
1394    {
1395      DBG(1, "process_data_flush: write failed: %s\n",
1396          signal_caught ? "signal caught" : strerror(errno));
1397      return SANE_STATUS_IO_ERROR;
1398    }
1399    ph->wr_ptr = ph->wr_buf;
1400    ph->wr_left = ph->wr_buf_size;
1401  }
1402 
1403  procdata = &(ph->procdata);
1404  if ( ph->image_buf )
1405  {
1406    bytes_per_line = procdata->bytes_per_line;
1407    if (procdata->out8) bytes_per_line /= 2;
1408    image_len = (size_t) (ph->image_ptr - ph->image_buf);
1409    num_lines = ((int)(image_len + bytes_per_line-1)) / bytes_per_line;
1410 
1411    DBG(3, "process_data_finish: write %d bytes from memory...\n",
1412        (int)image_len);
1413 
1414    if ( procdata->mirror_vertical )
1415    {
1416      image_data = ph->image_buf + (num_lines-1) * bytes_per_line;
1417      while (num_lines > 0 )
1418      {
1419        if (   signal_caught
1420            || (write(ph->outfd, image_data, bytes_per_line) != bytes_per_line))
1421        {
1422          DBG(1,"process_data_finish: write from memory failed: %s\n",
1423              signal_caught ? "signal caught" : strerror(errno));
1424          status = SANE_STATUS_IO_ERROR;
1425          break;
1426        }
1427        num_lines--;
1428        image_data -= bytes_per_line;
1429      }
1430    }
1431    else
1432    {
1433      image_data = ph->image_buf;
1434      while (num_lines > 0 )
1435      {
1436        if (   signal_caught
1437            || (write(ph->outfd, image_data, bytes_per_line) != bytes_per_line))
1438        {
1439          DBG(1,"process_data_finish: write from memory failed: %s\n",
1440              signal_caught ? "signal caught" : strerror(errno));
1441          status = SANE_STATUS_IO_ERROR;
1442          break;
1443        }
1444        num_lines--;
1445        image_data += bytes_per_line;
1446      }
1447    }
1448  }
1449  return status;
1450 }
1451 
1452 
1453 static void
process_data_finish(PROCDATA_HANDLE *ph)1454 process_data_finish (PROCDATA_HANDLE *ph)
1455 
1456 {
1457  DBG(12, "process_data_finish called\n");
1458 
1459  if (ph == NULL) return;
1460 
1461  if (ph->image_buf != NULL) sanei_hp_free (ph->image_buf);
1462 
1463  sanei_hp_free (ph->tmp_buf);
1464  sanei_hp_free (ph);
1465 }
1466 
1467 
1468 SANE_Status
sanei_hp_scsi_pipeout(HpScsi this, int outfd, HpProcessData *procdata)1469 sanei_hp_scsi_pipeout (HpScsi this, int outfd, HpProcessData *procdata)
1470 {
1471   /* We will catch these signals, and rethrow them after cleaning up,
1472    * anything not in this list, we will ignore. */
1473   static int kill_sig[] = {
1474       SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGPIPE, SIGALRM, SIGTERM,
1475       SIGUSR1, SIGUSR2, SIGBUS,
1476 #ifdef SIGSTKFLT
1477       SIGSTKFLT,
1478 #endif
1479 #ifdef SIGIO
1480       SIGIO,
1481 #else
1482 # ifdef SIGPOLL
1483       SIGPOLL,
1484 # endif
1485 #endif
1486 #ifdef SIGXCPU
1487       SIGXCPU,
1488 #endif
1489 #ifdef SIGXFSZ
1490       SIGXFSZ,
1491 #endif
1492 #ifdef SIGVTALRM
1493       SIGVTALRM,
1494 #endif
1495 #ifdef SIGPWR
1496       SIGPWR,
1497 #endif
1498   };
1499 #define HP_NSIGS (sizeof(kill_sig)/sizeof(kill_sig[0]))
1500   struct SIGACTION old_handler[HP_NSIGS];
1501   struct SIGACTION sa;
1502   sigset_t	old_set, sig_set;
1503   int		i;
1504   int           bits_per_channel = procdata->bits_per_channel;
1505 
1506 #define HP_PIPEBUF	32768
1507   SANE_Status	status	= SANE_STATUS_GOOD;
1508   struct {
1509       size_t	len;
1510       void *	id;
1511       hp_byte_t	cmd[6];
1512       hp_byte_t	data[HP_PIPEBUF];
1513   } 	buf[2], *req = NULL;
1514 
1515   int		reqs_completed = 0;
1516   int		reqs_issued = 0;
1517   char          *image_buf = 0;
1518   char          *read_buf = 0;
1519   const HpDeviceInfo *info;
1520   const char    *devname = sanei_hp_scsi_devicename (this);
1521   int           enable_requests = 1;
1522   int           enable_image_buffering = 0;
1523   const unsigned char *map = NULL;
1524   HpConnect     connect;
1525   PROCDATA_HANDLE *ph = NULL;
1526   size_t count = procdata->lines * procdata->bytes_per_line;
1527 
1528   RETURN_IF_FAIL( hp_scsi_flush(this) );
1529 
1530   connect = sanei_hp_get_connect (devname);
1531   info = sanei_hp_device_info_get (devname);
1532 
1533   assert (info);
1534 
1535   if ( info->config_is_up )
1536   {
1537     enable_requests = info->config.use_scsi_request;
1538     enable_image_buffering = info->config.use_image_buffering;
1539   }
1540   else
1541   {
1542     enable_requests = 0;
1543   }
1544 
1545   if (connect != HP_CONNECT_SCSI)
1546     enable_requests = 0;
1547 
1548   /* Currently we can only simulate 8 bits mapping */
1549   if (bits_per_channel == 8)
1550     map = hp_get_simulation_map (devname, info);
1551 
1552   sigfillset(&sig_set);
1553   sigprocmask(SIG_BLOCK, &sig_set, &old_set);
1554 
1555   memset(&sa, 0, sizeof(sa));
1556   sa.sa_handler = signal_catcher;
1557   sigfillset(&sa.sa_mask);
1558 
1559   sigemptyset(&sig_set);
1560   for (i = 0; i < (int)(HP_NSIGS); i++)
1561     {
1562       sigaction(kill_sig[i], &sa, &old_handler[i]);
1563       sigaddset(&sig_set, kill_sig[i]);
1564     }
1565   signal_caught = 0;
1566   sigprocmask(SIG_UNBLOCK, &sig_set, 0);
1567 
1568   /* Wait for front button push ? */
1569   if ( procdata->startscan )
1570   {
1571     for (;;)
1572     {int val = 0;
1573 
1574        if (signal_caught) goto quit;
1575        sanei_hp_scl_inquire (this, SCL_FRONT_BUTTON, &val, 0, 0);
1576        if (val) break;
1577        usleep ((unsigned long)333*1000); /* Wait 1/3 second */
1578     }
1579     status = sanei_hp_scl_startScan (this, procdata->startscan);
1580     if (status != SANE_STATUS_GOOD )
1581     {
1582       DBG(1, "do_read: Error starting scan in reader process\n");
1583       goto quit;
1584     }
1585   }
1586   ph = process_data_init (procdata, map, outfd, enable_image_buffering);
1587 
1588   if ( ph == NULL )
1589   {
1590     DBG(1, "do_read: Error with process_data_init()\n");
1591     goto quit;
1592   }
1593 
1594   DBG(1, "do_read: Start reading data from scanner\n");
1595 
1596   if (enable_requests)   /* Issue SCSI-requests ? */
1597   {
1598     while (count > 0 || reqs_completed < reqs_issued)
1599     {
1600       while (count > 0 && reqs_issued < reqs_completed + 2)
1601 	{
1602 	  req = buf + (reqs_issued++ % 2);
1603 
1604 	  req->len = HP_PIPEBUF;
1605 	  if (count < req->len)
1606 	      req->len = count;
1607 	  count -= req->len;
1608 
1609 	  req->cmd[0] = 0x08;
1610 	  req->cmd[1] = 0;
1611 	  req->cmd[2] = req->len >> 16;
1612 	  req->cmd[3] = req->len >> 8;
1613 	  req->cmd[4] = req->len;
1614 	  req->cmd[5] = 0;
1615 
1616 	  DBG(3, "do_read: entering request to read %lu bytes\n",
1617 	      (unsigned long) req->len);
1618 
1619 	  status = sanei_scsi_req_enter(this->fd, req->cmd, 6,
1620 				      req->data, &req->len, &req->id);
1621 	  if (status != SANE_STATUS_GOOD)
1622 	    {
1623 	      DBG(1, "do_read: Error from scsi_req_enter: %s\n",
1624 		  sane_strstatus(status));
1625 	      goto quit;
1626 	    }
1627 	  if (signal_caught)
1628 	      goto quit;
1629 	}
1630 
1631       if (signal_caught)
1632 	  goto quit;
1633 
1634       assert(reqs_completed < reqs_issued);
1635       req = buf + (reqs_completed++ % 2);
1636 
1637       DBG(3, "do_read: waiting for data\n");
1638       status = sanei_scsi_req_wait(req->id);
1639       if (status != SANE_STATUS_GOOD)
1640 	{
1641 	  DBG(1, "do_read: Error from scsi_req_wait: %s\n",
1642 	      sane_strstatus(status));
1643 	  goto quit;
1644 	}
1645       if (signal_caught)
1646 	  goto quit;
1647 
1648       status = process_data (ph, (unsigned char *)req->data, (int)req->len);
1649       if ( status != SANE_STATUS_GOOD )
1650       {
1651         DBG(1,"do_read: Error in process_data\n");
1652         goto quit;
1653       }
1654     }
1655   }
1656   else  /* Read directly */
1657   {
1658     read_buf = sanei_hp_alloc ( HP_PIPEBUF );
1659     if (!read_buf)
1660     {
1661       DBG(1, "do_read: not enough memory for read buffer\n");
1662       goto quit;
1663     }
1664 
1665     while (count > 0)
1666     {size_t nread;
1667 
1668       if (signal_caught)
1669 	  goto quit;
1670 
1671       DBG(5, "do_read: %lu bytes left to read\n", (unsigned long)count);
1672 
1673       nread = HP_PIPEBUF;
1674       if (nread > count) nread = count;
1675 
1676       DBG(3, "do_read: try to read data (%lu bytes)\n", (unsigned long)nread);
1677 
1678       status = hp_scsi_read (this, read_buf, &nread, 0);
1679       if (status != SANE_STATUS_GOOD)
1680       {
1681         DBG(1, "do_read: Error from scsi_read: %s\n",sane_strstatus(status));
1682         goto quit;
1683       }
1684 
1685       DBG(3, "do_read: got %lu bytes\n", (unsigned long)nread);
1686 
1687       if (nread <= 0)
1688       {
1689         DBG(1, "do_read: Nothing read\n");
1690         continue;
1691       }
1692 
1693       status = process_data (ph, (unsigned char *)read_buf, (int)nread);
1694       if ( status != SANE_STATUS_GOOD )
1695       {
1696         DBG(1,"do_read: Error in process_data\n");
1697         goto quit;
1698       }
1699       count -= nread;
1700     }
1701   }
1702 
1703   process_data_flush (ph);
1704 
1705 quit:
1706 
1707   process_data_finish (ph);
1708 
1709   if ( image_buf ) sanei_hp_free ( image_buf );
1710   if ( read_buf ) sanei_hp_free ( read_buf );
1711 
1712   if (enable_requests && (reqs_completed < reqs_issued))
1713     {
1714       DBG(1, "do_read: cleaning up leftover requests\n");
1715       while (reqs_completed < reqs_issued)
1716 	{
1717 	  req = buf + (reqs_completed++ % 2);
1718 	  sanei_scsi_req_wait(req->id);
1719 	}
1720     }
1721 
1722   sigfillset(&sig_set);
1723   sigprocmask(SIG_BLOCK, &sig_set, 0);
1724   for (i = 0; i < (int)(HP_NSIGS); i++)
1725       sigaction(kill_sig[i], &old_handler[i], 0);
1726   sigprocmask(SIG_SETMASK, &old_set, 0);
1727 
1728   if (signal_caught)
1729     {
1730       DBG(1, "do_read: caught signal %d\n", signal_caught);
1731       raise(signal_caught);
1732       return SANE_STATUS_CANCELLED;
1733     }
1734 
1735   return status;
1736 }
1737 
1738 
1739 
1740 /*
1741  *
1742  */
1743 
1744 static SANE_Status
_hp_scl_inq(HpScsi scsi, HpScl scl, HpScl inq_cmnd, void *valp, size_t *lengthp)1745 _hp_scl_inq (HpScsi scsi, HpScl scl, HpScl inq_cmnd,
1746 	     void *valp, size_t *lengthp)
1747 {
1748   size_t	bufsize	= 16 + (lengthp ? *lengthp: 0);
1749   char *	buf	= alloca(bufsize);
1750   char		expect[16], expect_char;
1751   int		val, count;
1752   SANE_Status	status;
1753 
1754   if (!buf)
1755       return SANE_STATUS_NO_MEM;
1756 
1757   /* Flush data before sending inquiry. */
1758   /* Otherwise scanner might not generate a response. */
1759   RETURN_IF_FAIL( hp_scsi_flush (scsi)) ;
1760 
1761   RETURN_IF_FAIL( hp_scsi_scl(scsi, inq_cmnd, SCL_INQ_ID(scl)) );
1762   usleep (1000); /* 500 works, too, but not 100 */
1763 
1764   status =  hp_scsi_read(scsi, buf, &bufsize, 1);
1765   if (FAILED(status))
1766     {
1767       DBG(1, "scl_inq: read failed (%s)\n", sane_strstatus(status));
1768       return status;
1769     }
1770 
1771   if (SCL_PARAM_CHAR(inq_cmnd) == 'R')
1772       expect_char = 'p';
1773   else
1774       expect_char = tolower(SCL_PARAM_CHAR(inq_cmnd) - 1);
1775 
1776   count = sprintf(expect, "\033*s%d%c", SCL_INQ_ID(scl), expect_char);
1777   if (memcmp(buf, expect, count) != 0)
1778     {
1779       DBG(1, "scl_inq: malformed response: expected '%s', got '%.*s'\n",
1780 	  expect, count, buf);
1781       return SANE_STATUS_IO_ERROR;
1782     }
1783   buf += count;
1784 
1785   if (buf[0] == 'N')
1786     {				/* null response */
1787       DBG(3, "scl_inq: parameter %d unsupported\n", SCL_INQ_ID(scl));
1788       return SANE_STATUS_UNSUPPORTED;
1789     }
1790 
1791   if (sscanf(buf, "%d%n", &val, &count) != 1)
1792     {
1793       DBG(1, "scl_inq: malformed response: expected int, got '%.8s'\n", buf);
1794       return SANE_STATUS_IO_ERROR;
1795     }
1796   buf += count;
1797 
1798   expect_char = lengthp ? 'W' : 'V';
1799   if (*buf++ != expect_char)
1800     {
1801       DBG(1, "scl_inq: malformed response: expected '%c', got '%.4s'\n",
1802 	  expect_char, buf - 1);
1803       return SANE_STATUS_IO_ERROR;
1804     }
1805 
1806   if (!lengthp)
1807       *(int *)valp = val; /* Get integer value */
1808   else
1809     {
1810       if (val > (int)*lengthp)
1811 	{
1812 	  DBG(1, "scl_inq: inquiry returned %d bytes, expected <= %lu\n",
1813 	      val, (unsigned long) *lengthp);
1814 	  return SANE_STATUS_IO_ERROR;
1815 	}
1816       *lengthp = val;
1817       memcpy(valp, buf , *lengthp); /* Get binary data */
1818     }
1819 
1820   return SANE_STATUS_GOOD;
1821 }
1822 
1823 
1824 SANE_Status
sanei_hp_scl_upload_binary(HpScsi scsi, HpScl scl, size_t *lengthhp, char **bufhp)1825 sanei_hp_scl_upload_binary (HpScsi scsi, HpScl scl, size_t *lengthhp,
1826                             char **bufhp)
1827 {
1828   size_t	bufsize	= 16, sv;
1829   char *	buf	= alloca(bufsize);
1830   char *        bufstart = buf;
1831   char *        hpdata;
1832   char		expect[16], expect_char;
1833   int		n, val, count;
1834   SANE_Status	status;
1835 
1836   if (!buf)
1837       return SANE_STATUS_NO_MEM;
1838 
1839   assert ( IS_SCL_DATA_TYPE (scl) );
1840 
1841   /* Flush data before sending inquiry. */
1842   /* Otherwise scanner might not generate a response. */
1843   RETURN_IF_FAIL( hp_scsi_flush (scsi)) ;
1844 
1845   RETURN_IF_FAIL( hp_scsi_scl(scsi, SCL_UPLOAD_BINARY_DATA, SCL_INQ_ID(scl)) );
1846 
1847   status =  hp_scsi_read(scsi, buf, &bufsize, 0);
1848   if (FAILED(status))
1849     {
1850       DBG(1, "scl_upload_binary: read failed (%s)\n", sane_strstatus(status));
1851       return status;
1852     }
1853 
1854   expect_char = 't';
1855   count = sprintf(expect, "\033*s%d%c", SCL_INQ_ID(scl), expect_char);
1856   if (memcmp(buf, expect, count) != 0)
1857     {
1858       DBG(1, "scl_upload_binary: malformed response: expected '%s', got '%.*s'\n",
1859 	  expect, count, buf);
1860       return SANE_STATUS_IO_ERROR;
1861     }
1862   buf += count;
1863 
1864   if (buf[0] == 'N')
1865     {				/* null response */
1866       DBG(1, "scl_upload_binary: parameter %d unsupported\n", SCL_INQ_ID(scl));
1867       return SANE_STATUS_UNSUPPORTED;
1868     }
1869 
1870   if (sscanf(buf, "%d%n", &val, &count) != 1)
1871     {
1872       DBG(1, "scl_inq: malformed response: expected int, got '%.8s'\n", buf);
1873       return SANE_STATUS_IO_ERROR;
1874     }
1875   buf += count;
1876 
1877   expect_char = 'W';
1878   if (*buf++ != expect_char)
1879     {
1880       DBG(1, "scl_inq: malformed response: expected '%c', got '%.4s'\n",
1881 	  expect_char, buf - 1);
1882       return SANE_STATUS_IO_ERROR;
1883     }
1884 
1885   *lengthhp = val;
1886   *bufhp = hpdata = sanei_hp_alloc ( val );
1887   if (!hpdata)
1888       return SANE_STATUS_NO_MEM;
1889 
1890   if (buf < bufstart + bufsize)
1891     {
1892        n = bufsize - (buf - bufstart);
1893        if (n > val) n = val;
1894        memcpy (hpdata, buf, n);
1895        hpdata += n;
1896        val -= n;
1897     }
1898 
1899   status = SANE_STATUS_GOOD;
1900   if ( val > 0 )
1901     {
1902       sv = val;
1903       status = hp_scsi_read(scsi, hpdata, &sv, 0);
1904       if (status != SANE_STATUS_GOOD)
1905         sanei_hp_free ( *bufhp );
1906     }
1907 
1908   return status;
1909 }
1910 
1911 
1912 SANE_Status
sanei_hp_scl_set(HpScsi scsi, HpScl scl, int val)1913 sanei_hp_scl_set(HpScsi scsi, HpScl scl, int val)
1914 {
1915   RETURN_IF_FAIL( hp_scsi_scl(scsi, scl, val) );
1916 
1917 
1918 #ifdef PARANOID
1919   RETURN_IF_FAIL( sanei_hp_scl_errcheck(scsi) );
1920 #endif
1921 
1922   return SANE_STATUS_GOOD;
1923 }
1924 
1925 SANE_Status
sanei_hp_scl_inquire(HpScsi scsi, HpScl scl, int * valp, int * minp, int * maxp)1926 sanei_hp_scl_inquire(HpScsi scsi, HpScl scl, int * valp, int * minp, int * maxp)
1927 {
1928   HpScl	inquiry = ( IS_SCL_CONTROL(scl)
1929 		    ? SCL_INQUIRE_PRESENT_VALUE
1930 		    : SCL_INQUIRE_DEVICE_PARAMETER );
1931 
1932   assert(IS_SCL_CONTROL(scl) || IS_SCL_PARAMETER(scl));
1933   assert(IS_SCL_CONTROL(scl) || (!minp && !maxp));
1934 
1935   if (valp)
1936       RETURN_IF_FAIL( _hp_scl_inq(scsi, scl, inquiry, valp, 0) );
1937   if (minp)
1938       RETURN_IF_FAIL( _hp_scl_inq(scsi, scl,
1939 				  SCL_INQUIRE_MINIMUM_VALUE, minp, 0) );
1940   if (maxp)
1941       RETURN_IF_FAIL( _hp_scl_inq(scsi, scl,
1942 				  SCL_INQUIRE_MAXIMUM_VALUE, maxp, 0) );
1943   return SANE_STATUS_GOOD;
1944 }
1945 
1946 #ifdef _HP_NOT_USED
1947 static SANE_Status
hp_scl_get_bounds(HpScsi scsi, HpScl scl, int * minp, int * maxp)1948 hp_scl_get_bounds(HpScsi scsi, HpScl scl, int * minp, int * maxp)
1949 {
1950   assert(IS_SCL_CONTROL(scl));
1951   RETURN_IF_FAIL( _hp_scl_inq(scsi, scl, SCL_INQUIRE_MINIMUM_VALUE, minp, 0) );
1952   return _hp_scl_inq(scsi, scl, SCL_INQUIRE_MAXIMUM_VALUE, maxp, 0);
1953 }
1954 #endif
1955 
1956 #ifdef _HP_NOT_USED
1957 static SANE_Status
hp_scl_get_bounds_and_val(HpScsi scsi, HpScl scl, int * minp, int * maxp, int * valp)1958 hp_scl_get_bounds_and_val(HpScsi scsi, HpScl scl,
1959 			  int * minp, int * maxp, int * valp)
1960 {
1961   assert(IS_SCL_CONTROL(scl));
1962   RETURN_IF_FAIL( _hp_scl_inq(scsi, scl, SCL_INQUIRE_MINIMUM_VALUE, minp, 0) );
1963   RETURN_IF_FAIL( _hp_scl_inq(scsi, scl, SCL_INQUIRE_MAXIMUM_VALUE, maxp, 0) );
1964   return    _hp_scl_inq(scsi, scl, SCL_INQUIRE_PRESENT_VALUE, valp, 0);
1965 }
1966 #endif
1967 
1968 SANE_Status
sanei_hp_scl_download(HpScsi scsi, HpScl scl, const void * valp, size_t len)1969 sanei_hp_scl_download(HpScsi scsi, HpScl scl, const void * valp, size_t len)
1970 {
1971   assert(IS_SCL_DATA_TYPE(scl));
1972 
1973   sanei_hp_scl_clearErrors ( scsi );
1974   RETURN_IF_FAIL( hp_scsi_need(scsi, 16) );
1975   RETURN_IF_FAIL( hp_scsi_scl(scsi, SCL_DOWNLOAD_TYPE, SCL_INQ_ID(scl)) );
1976                             /* Download type not supported ? */
1977   RETURN_IF_FAIL( sanei_hp_scl_errcheck(scsi) );
1978   RETURN_IF_FAIL( hp_scsi_scl(scsi, SCL_DOWNLOAD_LENGTH, len) );
1979   RETURN_IF_FAIL( hp_scsi_write(scsi, valp, len) );
1980 
1981 #ifdef PARANOID
1982   RETURN_IF_FAIL( sanei_hp_scl_errcheck(scsi) );
1983 #endif
1984 
1985   return SANE_STATUS_GOOD;
1986 }
1987 
1988 SANE_Status
sanei_hp_scl_upload(HpScsi scsi, HpScl scl, void * valp, size_t len)1989 sanei_hp_scl_upload(HpScsi scsi, HpScl scl, void * valp, size_t len)
1990 {
1991   size_t	nread = len;
1992   HpScl		inquiry = ( IS_SCL_DATA_TYPE(scl)
1993 			    ? SCL_UPLOAD_BINARY_DATA
1994 			    : SCL_INQUIRE_DEVICE_PARAMETER );
1995 
1996   assert(IS_SCL_DATA_TYPE(scl) || IS_SCL_PARAMETER(scl));
1997 
1998   RETURN_IF_FAIL( _hp_scl_inq(scsi, scl, inquiry, valp, &nread) );
1999   if (IS_SCL_PARAMETER(scl) && nread < len)
2000       ((char *)valp)[nread] = '\0';
2001   else if (len != nread)
2002     {
2003       DBG(1, "scl_upload: requested %lu bytes, got %lu\n",
2004 	  (unsigned long) len, (unsigned long) nread);
2005       return SANE_STATUS_IO_ERROR;
2006     }
2007   return SANE_STATUS_GOOD;
2008 }
2009 
2010 SANE_Status
sanei_hp_scl_calibrate(HpScsi scsi)2011 sanei_hp_scl_calibrate(HpScsi scsi)
2012 {
2013   RETURN_IF_FAIL( hp_scsi_scl(scsi, SCL_CALIBRATE, 0) );
2014   return hp_scsi_flush(scsi);
2015 }
2016 
2017 SANE_Status
sanei_hp_scl_startScan(HpScsi scsi, HpScl scl)2018 sanei_hp_scl_startScan(HpScsi scsi, HpScl scl)
2019 {
2020   char *msg = "";
2021 
2022   if (scl == SCL_ADF_SCAN) msg = " (ADF)";
2023   else if (scl == SCL_XPA_SCAN) msg = " (XPA)";
2024   else scl = SCL_START_SCAN;
2025 
2026   DBG(1, "sanei_hp_scl_startScan: Start scan%s\n", msg);
2027 
2028   /* For active XPA we must not use XPA scan */
2029   if ((scl == SCL_XPA_SCAN) && sanei_hp_is_active_xpa (scsi))
2030   {
2031     DBG(3,"Map XPA scan to scan because of active XPA\n");
2032     scl = SCL_START_SCAN;
2033   }
2034 
2035   RETURN_IF_FAIL( hp_scsi_scl(scsi, scl, 0) );
2036   return hp_scsi_flush(scsi);
2037 }
2038 
2039 SANE_Status
sanei_hp_scl_reset(HpScsi scsi)2040 sanei_hp_scl_reset(HpScsi scsi)
2041 {
2042   RETURN_IF_FAIL( hp_scsi_write(scsi, "\033E", 2) );
2043   RETURN_IF_FAIL( hp_scsi_flush(scsi) );
2044   return sanei_hp_scl_errcheck(scsi);
2045 }
2046 
2047 SANE_Status
sanei_hp_scl_clearErrors(HpScsi scsi)2048 sanei_hp_scl_clearErrors(HpScsi scsi)
2049 {
2050   RETURN_IF_FAIL( hp_scsi_flush(scsi) );
2051   RETURN_IF_FAIL( hp_scsi_write(scsi, "\033*oE", 4) );
2052   return hp_scsi_flush(scsi);
2053 }
2054 
2055 static const char *
hp_scl_strerror(int errnum)2056 hp_scl_strerror (int errnum)
2057 {
2058   static const char * errlist[] = {
2059       "Command Format Error",
2060       "Unrecognized Command",
2061       "Parameter Error",
2062       "Illegal Window",
2063       "Scaling Error",
2064       "Dither ID Error",
2065       "Tone Map ID Error",
2066       "Lamp Error",
2067       "Matrix ID Error",
2068       "Cal Strip Param Error",
2069       "Gross Calibration Error"
2070   };
2071 
2072   if (errnum >= 0 && errnum < (int)(sizeof(errlist)/sizeof(errlist[0])))
2073       return errlist[errnum];
2074   else
2075       switch(errnum) {
2076       case 1024: return "ADF Paper Jam";
2077       case 1025: return "Home Position Missing";
2078       case 1026: return "Paper Not Loaded";
2079       default: return "??Unknown Error??";
2080       }
2081 }
2082 
2083 /* Check for SCL errors */
2084 SANE_Status
sanei_hp_scl_errcheck(HpScsi scsi)2085 sanei_hp_scl_errcheck (HpScsi scsi)
2086 {
2087   int		errnum;
2088   int		nerrors;
2089   SANE_Status	status;
2090 
2091   status = sanei_hp_scl_inquire(scsi, SCL_CURRENT_ERROR_STACK, &nerrors,0,0);
2092   if (!FAILED(status) && nerrors)
2093       status = sanei_hp_scl_inquire(scsi, SCL_OLDEST_ERROR, &errnum,0,0);
2094   if (FAILED(status))
2095     {
2096       DBG(1, "scl_errcheck: Can't read SCL error stack: %s\n",
2097 	  sane_strstatus(status));
2098       return SANE_STATUS_IO_ERROR;
2099     }
2100 
2101   if (nerrors)
2102     {
2103       DBG(1, "Scanner issued SCL error: (%d) %s\n",
2104 	  errnum, hp_scl_strerror(errnum));
2105 
2106       sanei_hp_scl_clearErrors (scsi);
2107       return SANE_STATUS_IO_ERROR;
2108     }
2109 
2110   return SANE_STATUS_GOOD;
2111 }
2112