Imported Upstream version 3.2.1
[debian/amanda] / device-src / tape-device.c
1 /*
2  * Copyright (c) 2007, 2008, 2009, 2010 Zmanda, Inc.  All Rights Reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License version 2 as published
6  * by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11  * for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16  *
17  * Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
18  * Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
19  */
20
21 #include "amanda.h"
22 #include "pipespawn.h"
23 #include <string.h> /* memset() */
24 #include "util.h"
25 #include "device.h"
26
27 #ifdef HAVE_SYS_TAPE_H
28 # include <sys/tape.h>
29 #endif
30 #ifdef HAVE_SYS_MTIO_H
31 # include <sys/mtio.h>
32 #endif
33 #ifdef HAVE_LIMITS_H
34 # include <limits.h>
35 #endif
36
37 /* This is equal to 2*1024*1024*1024 - 16*1024*1024 - 1, but written
38    explicitly to avoid overflow issues. */
39 #define RESETOFS_THRESHOLD (0x7effffff)
40
41 /* Largest possible block size on SCSI systems. */
42 #define LARGEST_BLOCK_ESTIMATE (16 * 1024 * 1024)
43
44 /*
45  * Type checking and casting macros
46  */
47
48 #define TYPE_TAPE_DEVICE        (tape_device_get_type())
49 #define TAPE_DEVICE(obj)        G_TYPE_CHECK_INSTANCE_CAST((obj), tape_device_get_type(), TapeDevice)
50 #define TAPE_DEVICE_CONST(obj)  G_TYPE_CHECK_INSTANCE_CAST((obj), tape_device_get_type(), TapeDevice const)
51 #define TAPE_DEVICE_CLASS(klass)        G_TYPE_CHECK_CLASS_CAST((klass), tape_device_get_type(), TapeDeviceClass)
52 #define IS_TAPE_DEVICE(obj)     G_TYPE_CHECK_INSTANCE_TYPE((obj), tape_device_get_type ())
53 #define TAPE_DEVICE_GET_CLASS(obj)      G_TYPE_INSTANCE_GET_CLASS((obj), tape_device_get_type(), TapeDeviceClass)
54 GType   tape_device_get_type    (void);
55
56 /*
57  * Main object structure
58  */
59 typedef struct TapeDevicePrivate_s TapeDevicePrivate;
60 typedef struct _TapeDevice {
61     Device __parent__;
62
63     /* It should go without saying that all this stuff is
64      * look-but-don't-touch. */
65
66     /* characteristics of the device */
67     gboolean fsf, bsf, fsr, bsr, eom, bsf_after_eom, broken_gmt_online;
68     gboolean leom;
69     gboolean nonblocking_open, fsf_after_filemark;
70     int final_filemarks;
71
72     /* 0 if we opened with O_RDWR; error otherwise. */
73     gboolean write_open_errno;
74     int fd;
75
76     TapeDevicePrivate * private;
77 } TapeDevice;
78
79 struct TapeDevicePrivate_s {
80     /* This holds the total number of bytes written to the device,
81        modulus RESETOFS_THRESHOLD. */
82     int write_count;
83     char * device_filename;
84     gsize read_block_size;
85 };
86
87 /*
88  * Class definition
89  */
90
91 typedef struct _TapeDeviceClass TapeDeviceClass;
92 struct _TapeDeviceClass {
93         DeviceClass __parent__;
94 };
95
96 void tape_device_register(void);
97
98 /* useful callback for tape ops */
99 void tape_device_set_capabilities(TapeDevice *self,
100         gboolean fsf, PropertySurety fsf_surety, PropertySource fsf_source,
101         gboolean fsf_after_filemark, PropertySurety faf_surety, PropertySource faf_source,
102         gboolean bsf, PropertySurety bsf_surety, PropertySource bsf_source,
103         gboolean fsr, PropertySurety fsr_surety, PropertySource fsr_source,
104         gboolean bsr, PropertySurety bsr_surety, PropertySource bsr_source,
105         gboolean eom, PropertySurety eom_surety, PropertySource eom_source,
106         gboolean leom, PropertySurety leom_surety, PropertySource leom_source,
107         gboolean bsf_after_eom, PropertySurety bae_surety, PropertySource bae_source,
108         guint final_filemarks, PropertySurety ff_surety, PropertySource ff_source);
109
110 /* Real Operations (always return FALSE if not implemented) */
111 gboolean tape_rewind(int fd);
112 gboolean tape_fsf(int fd, guint count);
113 gboolean tape_bsf(int fd, guint count);
114 gboolean tape_fsr(int fd, guint count);
115 gboolean tape_bsr(int fd, guint count);
116 gint tape_fileno(int fd);
117
118 /* tape_fileno returns tape position file number, or one of these: */
119 #define TAPE_OP_ERROR -1
120 #define TAPE_POSITION_UNKNOWN -2
121
122 /* Possible (abstracted) results from a system I/O operation. */
123 typedef enum {
124     RESULT_SUCCESS,
125     RESULT_ERROR,        /* Undefined error (*errmsg set) */
126     RESULT_SMALL_BUFFER, /* Tried to read with a buffer that is too
127                             small. */
128     RESULT_NO_DATA,      /* End of File, while reading */
129     RESULT_NO_SPACE,     /* Out of space. Sometimes we don't know if
130                             it was this or I/O error, but this is the
131                             preferred explanation. */
132     RESULT_MAX
133 } IoResult;
134
135 /* returns a fileno like tape_fileno */
136 gint tape_eod(int fd);
137
138 gboolean tape_weof(int fd, guint8 count);
139 gboolean tape_setcompression(int fd, gboolean on);
140
141 gboolean tape_offl(int fd);
142
143 DeviceStatusFlags tape_is_tape_device(int fd);
144 DeviceStatusFlags tape_is_ready(int fd, TapeDevice *t_self);
145
146 #define tape_device_read_size(self) \
147     (((TapeDevice *)(self))->private->read_block_size? \
148         ((TapeDevice *)(self))->private->read_block_size : ((Device *)(self))->block_size)
149
150 /*
151  * Our device-specific properties.
152  */
153
154 #define PROPERTY_BROKEN_GMT_ONLINE (device_property_broken_gmt_online.ID)
155 #define PROPERTY_FSF (device_property_fsf.ID)
156 #define PROPERTY_FSF_AFTER_FILEMARK (device_property_fsf_after_filemark.ID)
157 #define PROPERTY_BSF (device_property_bsf.ID)
158 #define PROPERTY_FSR (device_property_fsr.ID)
159 #define PROPERTY_BSR (device_property_bsr.ID)
160 #define PROPERTY_EOM (device_property_eom.ID)
161 #define PROPERTY_BSF_AFTER_EOM (device_property_bsf_after_eom.ID)
162 #define PROPERTY_NONBLOCKING_OPEN (device_property_nonblocking_open.ID)
163 #define PROPERTY_FINAL_FILEMARKS (device_property_final_filemarks.ID)
164
165 static DevicePropertyBase device_property_broken_gmt_online;
166 static DevicePropertyBase device_property_fsf;
167 static DevicePropertyBase device_property_fsf_after_filemark;
168 static DevicePropertyBase device_property_bsf;
169 static DevicePropertyBase device_property_fsr;
170 static DevicePropertyBase device_property_bsr;
171 static DevicePropertyBase device_property_eom;
172 static DevicePropertyBase device_property_bsf_after_eom;
173 static DevicePropertyBase device_property_nonblocking_open;
174 static DevicePropertyBase device_property_final_filemarks;
175 static DevicePropertyBase device_property_read_buffer_size; /* old name for READ_BLOCK_SIZE */
176
177 /* here are local prototypes */
178 static void tape_device_init (TapeDevice * o);
179 static void tape_device_class_init (TapeDeviceClass * c);
180 static void tape_device_base_init (TapeDeviceClass * c);
181 static gboolean tape_device_set_feature_property_fn(Device *p_self, DevicePropertyBase *base,
182                                     GValue *val, PropertySurety surety, PropertySource source);
183 static gboolean tape_device_set_final_filemarks_fn(Device *p_self, DevicePropertyBase *base,
184                                     GValue *val, PropertySurety surety, PropertySource source);
185 static gboolean tape_device_set_compression_fn(Device *p_self, DevicePropertyBase *base,
186                                     GValue *val, PropertySurety surety, PropertySource source);
187 static gboolean tape_device_get_read_block_size_fn(Device *p_self, DevicePropertyBase *base,
188                                     GValue *val, PropertySurety *surety, PropertySource *source);
189 static gboolean tape_device_set_read_block_size_fn(Device *p_self, DevicePropertyBase *base,
190                                     GValue *val, PropertySurety surety, PropertySource source);
191 static void tape_device_open_device (Device * self, char * device_name, char * device_type, char * device_node);
192 static Device * tape_device_factory (char * device_name, char * device_type, char * device_node);
193 static DeviceStatusFlags tape_device_read_label(Device * self);
194 static gboolean tape_device_write_block(Device * self, guint size, gpointer data);
195 static int tape_device_read_block(Device * self,  gpointer buf,
196                                        int * size_req);
197 static gboolean tape_device_start (Device * self, DeviceAccessMode mode,
198                                    char * label, char * timestamp);
199 static gboolean tape_device_start_file (Device * self, dumpfile_t * ji);
200 static gboolean tape_device_finish_file (Device * self);
201 static dumpfile_t * tape_device_seek_file (Device * self, guint file);
202 static gboolean tape_device_seek_block (Device * self, guint64 block);
203 static gboolean tape_device_eject (Device * self);
204 static gboolean tape_device_finish (Device * self);
205 static IoResult tape_device_robust_read (TapeDevice * self, void * buf,
206                                                int * count, char **errmsg);
207 static IoResult tape_device_robust_write (TapeDevice * self, void * buf, int count, char **errmsg);
208 static gboolean tape_device_fsf (TapeDevice * self, guint count);
209 static gboolean tape_device_fsr (TapeDevice * self, guint count);
210 static gboolean tape_device_bsr (TapeDevice * self, guint count, guint file, guint block);
211 static gboolean tape_device_eod (TapeDevice * self);
212
213 /* pointer to the class of our parent */
214 static DeviceClass *parent_class = NULL;
215
216 GType tape_device_get_type (void)
217 {
218     static GType type = 0;
219
220     if G_UNLIKELY(type == 0) {
221         static const GTypeInfo info = {
222             sizeof (TapeDeviceClass),
223             (GBaseInitFunc) tape_device_base_init,
224             (GBaseFinalizeFunc) NULL,
225             (GClassInitFunc) tape_device_class_init,
226             (GClassFinalizeFunc) NULL,
227             NULL /* class_data */,
228             sizeof (TapeDevice),
229             0 /* n_preallocs */,
230             (GInstanceInitFunc) tape_device_init,
231             NULL
232         };
233
234         type = g_type_register_static (TYPE_DEVICE, "TapeDevice",
235                                        &info, (GTypeFlags)0);
236     }
237
238     return type;
239 }
240
241 static void
242 tape_device_init (TapeDevice * self) {
243     Device * d_self;
244     GValue response;
245
246     d_self = DEVICE(self);
247     bzero(&response, sizeof(response));
248
249     self->private = g_new0(TapeDevicePrivate, 1);
250
251     /* Clear all fields. */
252     d_self->block_size = 32768;
253     d_self->min_block_size = 32768;
254     d_self->max_block_size = LARGEST_BLOCK_ESTIMATE;
255     self->broken_gmt_online = FALSE;
256
257     self->fd = -1;
258
259     /* set all of the feature properties to an unsure default of FALSE */
260     self->broken_gmt_online = FALSE;
261     self->fsf = FALSE;
262     self->bsf = FALSE;
263     self->fsr = FALSE;
264     self->bsr = FALSE;
265     self->eom = FALSE;
266     self->leom = FALSE;
267     self->bsf_after_eom = FALSE;
268
269     g_value_init(&response, G_TYPE_BOOLEAN);
270     g_value_set_boolean(&response, FALSE);
271     device_set_simple_property(d_self, PROPERTY_BROKEN_GMT_ONLINE,
272             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
273     device_set_simple_property(d_self, PROPERTY_FSF,
274             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
275     device_set_simple_property(d_self, PROPERTY_FSF_AFTER_FILEMARK,
276             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
277     device_set_simple_property(d_self, PROPERTY_BSF,
278             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
279     device_set_simple_property(d_self, PROPERTY_FSR,
280             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
281     device_set_simple_property(d_self, PROPERTY_BSR,
282             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
283     device_set_simple_property(d_self, PROPERTY_EOM,
284             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
285     device_set_simple_property(d_self, PROPERTY_LEOM,
286             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
287     device_set_simple_property(d_self, PROPERTY_BSF_AFTER_EOM,
288             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
289
290 #ifdef DEFAULT_TAPE_NON_BLOCKING_OPEN
291     self->nonblocking_open = TRUE;
292 #else
293     self->nonblocking_open = FALSE;
294 #endif
295     g_value_set_boolean(&response, self->nonblocking_open);
296     device_set_simple_property(d_self, PROPERTY_NONBLOCKING_OPEN,
297             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
298     g_value_unset(&response);
299
300     self->final_filemarks = 2;
301     g_value_init(&response, G_TYPE_UINT);
302     g_value_set_uint(&response, self->final_filemarks);
303     device_set_simple_property(d_self, PROPERTY_FINAL_FILEMARKS,
304             &response, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
305     g_value_unset(&response);
306
307     self->private->read_block_size = 0;
308     g_value_init(&response, G_TYPE_UINT);
309     g_value_set_uint(&response, self->private->read_block_size);
310     device_set_simple_property(d_self, PROPERTY_READ_BLOCK_SIZE,
311             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DEFAULT);
312     g_value_unset(&response);
313
314     self->private->write_count = 0;
315     self->private->device_filename = NULL;
316
317     /* Static properites */
318     g_value_init(&response, CONCURRENCY_PARADIGM_TYPE);
319     g_value_set_enum(&response, CONCURRENCY_PARADIGM_EXCLUSIVE);
320     device_set_simple_property(d_self, PROPERTY_CONCURRENCY,
321             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
322     g_value_unset(&response);
323
324     g_value_init(&response, STREAMING_REQUIREMENT_TYPE);
325     g_value_set_enum(&response, STREAMING_REQUIREMENT_DESIRED);
326     device_set_simple_property(d_self, PROPERTY_STREAMING,
327             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
328     g_value_unset(&response);
329
330     g_value_init(&response, G_TYPE_BOOLEAN);
331     g_value_set_boolean(&response, TRUE);
332     device_set_simple_property(d_self, PROPERTY_APPENDABLE,
333             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
334     g_value_unset(&response);
335
336     g_value_init(&response, G_TYPE_BOOLEAN);
337     g_value_set_boolean(&response, FALSE);
338     device_set_simple_property(d_self, PROPERTY_PARTIAL_DELETION,
339             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
340     g_value_unset(&response);
341
342     g_value_init(&response, G_TYPE_BOOLEAN);
343     g_value_set_boolean(&response, FALSE);
344     device_set_simple_property(d_self, PROPERTY_FULL_DELETION,
345             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
346     g_value_unset(&response);
347
348     g_value_init(&response, MEDIA_ACCESS_MODE_TYPE);
349     g_value_set_enum(&response, MEDIA_ACCESS_MODE_READ_WRITE);
350     device_set_simple_property(d_self, PROPERTY_MEDIUM_ACCESS_TYPE,
351             &response, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
352     g_value_unset(&response);
353 }
354
355 static void tape_device_finalize(GObject * obj_self) {
356     TapeDevice * self = TAPE_DEVICE(obj_self);
357
358     if(G_OBJECT_CLASS(parent_class)->finalize) \
359            (* G_OBJECT_CLASS(parent_class)->finalize)(obj_self);
360
361     robust_close(self->fd);
362     self->fd = -1;
363     amfree(self->private->device_filename);
364     amfree(self->private);
365 }
366
367 static void
368 tape_device_class_init (TapeDeviceClass * c)
369 {
370     DeviceClass *device_class = (DeviceClass *)c;
371     GObjectClass *g_object_class = (GObjectClass *)c;
372
373     parent_class = g_type_class_ref (TYPE_DEVICE);
374
375     device_class->open_device = tape_device_open_device;
376     device_class->read_label = tape_device_read_label;
377     device_class->write_block = tape_device_write_block;
378     device_class->read_block = tape_device_read_block;
379     device_class->start = tape_device_start;
380     device_class->start_file = tape_device_start_file;
381     device_class->finish_file = tape_device_finish_file;
382     device_class->seek_file = tape_device_seek_file;
383     device_class->seek_block = tape_device_seek_block;
384     device_class->eject = tape_device_eject;
385     device_class->finish = tape_device_finish;
386
387     g_object_class->finalize = tape_device_finalize;
388 }
389
390 static void
391 tape_device_base_init (TapeDeviceClass * c)
392 {
393     DeviceClass *device_class = (DeviceClass *)c;
394
395     device_class_register_property(device_class, PROPERTY_BROKEN_GMT_ONLINE,
396             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
397             device_simple_property_get_fn,
398             tape_device_set_feature_property_fn);
399
400     device_class_register_property(device_class, PROPERTY_FSF,
401             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
402             device_simple_property_get_fn,
403             tape_device_set_feature_property_fn);
404
405     device_class_register_property(device_class, PROPERTY_FSF_AFTER_FILEMARK,
406             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
407             device_simple_property_get_fn,
408             tape_device_set_feature_property_fn);
409
410     device_class_register_property(device_class, PROPERTY_BSF,
411             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
412             device_simple_property_get_fn,
413             tape_device_set_feature_property_fn);
414
415     device_class_register_property(device_class, PROPERTY_FSR,
416             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
417             device_simple_property_get_fn,
418             tape_device_set_feature_property_fn);
419
420     device_class_register_property(device_class, PROPERTY_BSR,
421             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
422             device_simple_property_get_fn,
423             tape_device_set_feature_property_fn);
424
425     device_class_register_property(device_class, PROPERTY_EOM,
426             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
427             device_simple_property_get_fn,
428             tape_device_set_feature_property_fn);
429
430     device_class_register_property(device_class, PROPERTY_BSF_AFTER_EOM,
431             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
432             device_simple_property_get_fn,
433             tape_device_set_feature_property_fn);
434
435     device_class_register_property(device_class, PROPERTY_NONBLOCKING_OPEN,
436             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
437             device_simple_property_get_fn,
438             tape_device_set_feature_property_fn);
439
440     device_class_register_property(device_class, PROPERTY_FINAL_FILEMARKS,
441             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
442             device_simple_property_get_fn,
443             tape_device_set_final_filemarks_fn);
444
445     /* We don't (yet?) support reading the device's compression state, so not
446      * gettable. */
447     device_class_register_property(device_class, PROPERTY_COMPRESSION,
448             PROPERTY_ACCESS_SET_MASK,
449             NULL,
450             tape_device_set_compression_fn);
451
452     device_class_register_property(device_class, PROPERTY_READ_BLOCK_SIZE,
453             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
454             tape_device_get_read_block_size_fn,
455             tape_device_set_read_block_size_fn);
456
457     device_class_register_property(device_class, device_property_read_buffer_size.ID,
458             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
459             tape_device_get_read_block_size_fn,
460             tape_device_set_read_block_size_fn);
461
462     /* add the ability to set LEOM to FALSE, for testing purposes */
463     device_class_register_property(device_class, PROPERTY_LEOM,
464             PROPERTY_ACCESS_GET_MASK | PROPERTY_ACCESS_SET_BEFORE_START,
465             device_simple_property_get_fn,
466             tape_device_set_feature_property_fn);
467 }
468
469 static gboolean
470 tape_device_set_feature_property_fn(Device *p_self, DevicePropertyBase *base,
471     GValue *val, PropertySurety surety, PropertySource source)
472 {
473     TapeDevice *self = TAPE_DEVICE(p_self);
474     GValue old_val;
475     gboolean old_bool, new_bool;
476     PropertySurety old_surety;
477     PropertySource old_source;
478
479     new_bool = g_value_get_boolean(val);
480
481     /* get the old source and surety and see if we're willing to make this change */
482     bzero(&old_val, sizeof(old_val));
483     if (device_get_simple_property(p_self, base->ID, &old_val, &old_surety, &old_source)) {
484         old_bool = g_value_get_boolean(&old_val);
485
486         if (old_surety == PROPERTY_SURETY_GOOD && old_source == PROPERTY_SOURCE_DETECTED) {
487             if (new_bool != old_bool) {
488                 device_set_error(p_self, vstrallocf(_(
489                            "Value for property '%s' was autodetected and cannot be changed"),
490                            base->name),
491                     DEVICE_STATUS_DEVICE_ERROR);
492                 return FALSE;
493             } else {
494                 /* pretend we set it, but don't change surety/source */
495                 return TRUE;
496             }
497         }
498     }
499
500     /* (note: PROPERTY_* are not constants, so we can't use switch) */
501     if (base->ID == PROPERTY_BROKEN_GMT_ONLINE)
502         self->broken_gmt_online = new_bool;
503     else if (base->ID == PROPERTY_FSF)
504         self->fsf = new_bool;
505     else if (base->ID == PROPERTY_FSF_AFTER_FILEMARK)
506         self->fsf_after_filemark = new_bool;
507     else if (base->ID == PROPERTY_BSF)
508         self->bsf = new_bool;
509     else if (base->ID == PROPERTY_FSR)
510         self->fsr = new_bool;
511     else if (base->ID == PROPERTY_BSR)
512         self->bsr = new_bool;
513     else if (base->ID == PROPERTY_EOM)
514         self->eom = new_bool;
515     else if (base->ID == PROPERTY_BSF_AFTER_EOM)
516         self->bsf_after_eom = new_bool;
517     else if (base->ID == PROPERTY_NONBLOCKING_OPEN)
518         self->nonblocking_open = new_bool;
519     else if (base->ID == PROPERTY_LEOM)
520         self->leom = new_bool;
521     else
522         return FALSE; /* shouldn't happen */
523
524     return device_simple_property_set_fn(p_self, base, val, surety, source);
525 }
526
527 static gboolean
528 tape_device_set_final_filemarks_fn(Device *p_self, DevicePropertyBase *base,
529     GValue *val, PropertySurety surety, PropertySource source)
530 {
531     TapeDevice *self = TAPE_DEVICE(p_self);
532     GValue old_val;
533     gboolean old_int, new_int;
534     PropertySurety old_surety;
535     PropertySource old_source;
536
537     new_int = g_value_get_uint(val);
538
539     /* get the old source and surety and see if we're willing to make this change */
540     bzero(&old_val, sizeof(old_val));
541     if (device_get_simple_property(p_self, base->ID, &old_val, &old_surety, &old_source)) {
542         old_int = g_value_get_uint(&old_val);
543
544         if (old_surety == PROPERTY_SURETY_GOOD && old_source == PROPERTY_SOURCE_DETECTED) {
545             if (new_int != old_int) {
546                 device_set_error(p_self, vstrallocf(_(
547                            "Value for property '%s' was autodetected and cannot be changed"),
548                            base->name),
549                     DEVICE_STATUS_DEVICE_ERROR);
550                 return FALSE;
551             } else {
552                 /* pretend we set it, but don't change surety/source */
553                 return TRUE;
554             }
555         }
556     }
557
558     self->final_filemarks = new_int;
559
560     return device_simple_property_set_fn(p_self, base, val, surety, source);
561 }
562
563 static gboolean
564 tape_device_set_compression_fn(Device *p_self, DevicePropertyBase *base,
565     GValue *val, PropertySurety surety, PropertySource source)
566 {
567     TapeDevice *self = TAPE_DEVICE(p_self);
568     gboolean request = g_value_get_boolean(val);
569
570     /* We allow this property to be set at any time. This is mostly
571      * because setting compression is a hit-and-miss proposition
572      * at any time; some drives accept the mode setting but don't
573      * actually support compression, while others do support
574      * compression but do it via density settings or some other
575      * way. Set this property whenever you want, but all we'll do
576      * is report whether or not the ioctl succeeded. */
577     if (tape_setcompression(self->fd, request)) {
578         /* looks good .. let's start the device over, though */
579         device_clear_volume_details(p_self);
580     } else {
581         return FALSE;
582     }
583
584     return device_simple_property_set_fn(p_self, base, val, surety, source);
585 }
586
587 static gboolean
588 tape_device_get_read_block_size_fn(Device *p_self, DevicePropertyBase *base G_GNUC_UNUSED,
589     GValue *val, PropertySurety *surety, PropertySource *source)
590 {
591     /* use the READ_BLOCK_SIZE, even if we're invoked to get the old READ_BUFFER_SIZE */
592     return device_simple_property_get_fn(p_self, &device_property_read_block_size,
593                                         val, surety, source);
594 }
595
596 static gboolean
597 tape_device_set_read_block_size_fn(Device *p_self, DevicePropertyBase *base G_GNUC_UNUSED,
598     GValue *val, PropertySurety surety, PropertySource source)
599 {
600     TapeDevice *self = TAPE_DEVICE(p_self);
601     guint read_block_size = g_value_get_uint(val);
602
603     if (read_block_size != 0 &&
604             ((gsize)read_block_size < p_self->block_size ||
605              (gsize)read_block_size > p_self->max_block_size))
606         return FALSE;
607
608     self->private->read_block_size = read_block_size;
609
610     /* use the READ_BLOCK_SIZE, even if we're invoked to get the old READ_BUFFER_SIZE */
611     return device_simple_property_set_fn(p_self, &device_property_read_block_size,
612                                         val, surety, source);
613 }
614
615 void tape_device_register(void) {
616     static const char * device_prefix_list[] = { "tape", NULL };
617
618     /* First register tape-specific properties */
619     device_property_fill_and_register(&device_property_broken_gmt_online,
620                                       G_TYPE_BOOLEAN, "broken_gmt_online",
621       "Does this drive support the GMT_ONLINE macro?");
622
623     device_property_fill_and_register(&device_property_fsf,
624                                       G_TYPE_BOOLEAN, "fsf",
625       "Does this drive support the MTFSF command?");
626
627     device_property_fill_and_register(&device_property_fsf_after_filemark,
628                                       G_TYPE_BOOLEAN, "fsf_after_filemark",
629       "Does this drive needs a FSF if a filemark is already read?");
630
631     device_property_fill_and_register(&device_property_bsf,
632                                       G_TYPE_BOOLEAN, "bsf",
633       "Does this drive support the MTBSF command?" );
634
635     device_property_fill_and_register(&device_property_fsr,
636                                       G_TYPE_BOOLEAN, "fsr",
637       "Does this drive support the MTFSR command?");
638
639     device_property_fill_and_register(&device_property_bsr,
640                                       G_TYPE_BOOLEAN, "bsr",
641       "Does this drive support the MTBSR command?");
642
643     device_property_fill_and_register(&device_property_eom,
644                                       G_TYPE_BOOLEAN, "eom",
645       "Does this drive support the MTEOM command?");
646
647     device_property_fill_and_register(&device_property_bsf_after_eom,
648                                       G_TYPE_BOOLEAN,
649                                       "bsf_after_eom",
650       "Does this drive require an MTBSF after MTEOM in order to append?" );
651
652     device_property_fill_and_register(&device_property_nonblocking_open,
653                                       G_TYPE_BOOLEAN,
654                                       "nonblocking_open",
655       "Does this drive require a open with O_NONBLOCK?" );
656
657     device_property_fill_and_register(&device_property_final_filemarks,
658                                       G_TYPE_UINT, "final_filemarks",
659       "How many filemarks to write after the last tape file?" );
660
661     device_property_fill_and_register(&device_property_read_buffer_size,
662                                       G_TYPE_UINT, "read_buffer_size",
663       "(deprecated name for READ_BLOCK_SIZE)");
664
665     /* Then the device itself */
666     register_device(tape_device_factory, device_prefix_list);
667 }
668
669 /* Open the tape device, trying various combinations of O_RDWR and
670    O_NONBLOCK.  Returns -1 and calls device_set_error for errors
671    On Linux, with O_NONBLOCK, the kernel just checks the state once,
672    whereas it checks it every second for ST_BLOCK_SECONDS if O_NONBLOCK is
673    not given.  Amanda already have the code to poll, we want open to check
674    the state only once. */
675
676 static int try_open_tape_device(TapeDevice * self, char * device_filename) {
677     int fd;
678     int save_errno;
679     DeviceStatusFlags new_status;
680
681 #ifdef O_NONBLOCK
682     int nonblocking = 0;
683
684     if (self->nonblocking_open) {
685         nonblocking = O_NONBLOCK;
686     }
687 #endif
688
689 #ifdef O_NONBLOCK
690     fd  = robust_open(device_filename, O_RDWR | nonblocking, 0);
691     save_errno = errno;
692     if (fd < 0 && nonblocking && (save_errno == EWOULDBLOCK || save_errno == EINVAL)) {
693         /* Maybe we don't support O_NONBLOCK for tape devices. */
694         fd = robust_open(device_filename, O_RDWR, 0);
695         save_errno = errno;
696     }
697 #else
698     fd = robust_open(device_filename, O_RDWR, 0);
699     save_errno = errno;
700 #endif
701     if (fd >= 0) {
702         self->write_open_errno = 0;
703     } else {
704         if (errno == EACCES || errno == EPERM
705 #ifdef EROFS
706                             || errno == EROFS
707 #endif
708            ) {
709             /* Device is write-protected. */
710             self->write_open_errno = errno;
711 #ifdef O_NONBLOCK
712             fd = robust_open(device_filename, O_RDONLY | nonblocking, 0);
713             save_errno = errno;
714             if (fd < 0 && nonblocking && (save_errno == EWOULDBLOCK || save_errno == EINVAL)) {
715                 fd = robust_open(device_filename, O_RDONLY, 0);
716                 save_errno = errno;
717             }
718 #else
719             fd = robust_open(device_filename, O_RDONLY, 0);
720             save_errno = errno;
721 #endif
722         }
723     }
724 #ifdef O_NONBLOCK
725     /* Clear O_NONBLOCK for operations from now on. */
726     if (fd >= 0 && nonblocking)
727         fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK);
728     errno = save_errno;
729     /* function continues after #endif */
730
731 #endif /* O_NONBLOCK */
732
733     if (fd < 0) {
734         DeviceStatusFlags status_flag = 0;
735         if (errno == EBUSY)
736             status_flag = DEVICE_STATUS_DEVICE_BUSY;
737         else
738             status_flag = DEVICE_STATUS_DEVICE_ERROR;
739         device_set_error(DEVICE(self),
740             vstrallocf(_("Can't open tape device %s: %s"), self->private->device_filename, strerror(errno)),
741             status_flag);
742         return -1;
743     }
744
745     /* Check that this is actually a tape device. */
746     new_status = tape_is_tape_device(fd);
747     if (new_status & DEVICE_STATUS_DEVICE_ERROR) {
748         device_set_error(DEVICE(self),
749             vstrallocf(_("File %s is not a tape device"), self->private->device_filename),
750             new_status);
751         robust_close(fd);
752         return -1;
753     }
754     if (new_status & DEVICE_STATUS_VOLUME_MISSING) {
755         device_set_error(DEVICE(self),
756             vstrallocf(_("Tape device %s is not ready or is empty"), self->private->device_filename),
757             new_status);
758         robust_close(fd);
759         return -1;
760     }
761
762     new_status = tape_is_ready(fd, self);
763     if (new_status & DEVICE_STATUS_VOLUME_MISSING) {
764         device_set_error(DEVICE(self),
765             vstrallocf(_("Tape device %s is empty"), self->private->device_filename),
766             new_status);
767         robust_close(fd);
768         return -1;
769     }
770     if (new_status != DEVICE_STATUS_SUCCESS) {
771         device_set_error(DEVICE(self),
772             vstrallocf(_("Tape device %s is not ready or is empty"), self->private->device_filename),
773             new_status);
774         robust_close(fd);
775         return -1;
776     }
777
778     return fd;
779 }
780
781 static void
782 tape_device_open_device (Device * dself, char * device_name,
783                         char * device_type, char * device_node) {
784     TapeDevice * self;
785     GValue val;
786
787     self = TAPE_DEVICE(dself);
788
789     self->fd = -1;
790     self->private->device_filename = stralloc(device_node);
791
792     /* Set tape drive/OS info */
793     bzero(&val, sizeof(val));
794     g_value_init(&val, G_TYPE_BOOLEAN);
795
796     self->fsf = TRUE;
797     g_value_set_boolean(&val, self->fsf);
798     device_set_simple_property(dself, PROPERTY_FSF, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
799
800     self->fsf_after_filemark = DEFAULT_FSF_AFTER_FILEMARK;
801     g_value_set_boolean(&val, self->fsf_after_filemark);
802     device_set_simple_property(dself, PROPERTY_FSF_AFTER_FILEMARK, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
803
804     self->bsf = TRUE;
805     g_value_set_boolean(&val, self->bsf);
806     device_set_simple_property(dself, PROPERTY_BSF, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
807
808     self->fsr = TRUE;
809     g_value_set_boolean(&val, self->fsr);
810     device_set_simple_property(dself, PROPERTY_FSR, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
811
812     self->bsr = TRUE;
813     g_value_set_boolean(&val, self->bsr);
814     device_set_simple_property(dself, PROPERTY_BSR, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
815
816     self->eom = TRUE;
817     g_value_set_boolean(&val, self->eom);
818     device_set_simple_property(dself, PROPERTY_EOM, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
819
820     self->leom = FALSE;
821     g_value_set_boolean(&val, self->leom);
822     device_set_simple_property(dself, PROPERTY_LEOM, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
823
824     self->bsf_after_eom = FALSE;
825     g_value_set_boolean(&val, self->bsf_after_eom);
826     device_set_simple_property(dself, PROPERTY_BSF_AFTER_EOM, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
827
828     g_value_unset(&val);
829     g_value_init(&val, G_TYPE_UINT);
830
831     self->final_filemarks = 2;
832     g_value_set_uint(&val, self->final_filemarks);
833     device_set_simple_property(dself, PROPERTY_FINAL_FILEMARKS, &val, PROPERTY_SURETY_BAD, PROPERTY_SOURCE_DEFAULT);
834
835     g_value_unset(&val);
836
837     /* Chain up */
838     if (parent_class->open_device) {
839         parent_class->open_device(dself, device_name, device_type, device_node);
840     }
841 }
842
843
844 static DeviceStatusFlags tape_device_read_label(Device * dself) {
845     TapeDevice * self;
846     char * header_buffer;
847     int buffer_len;
848     IoResult result;
849     dumpfile_t *header;
850     DeviceStatusFlags new_status;
851     char *msg = NULL;
852
853     self = TAPE_DEVICE(dself);
854
855     amfree(dself->volume_label);
856     amfree(dself->volume_time);
857     dumpfile_free(dself->volume_header);
858     dself->volume_header = NULL;
859
860     if (device_in_error(self)) return dself->status;
861
862     if (self->fd == -1) {
863         self->fd = try_open_tape_device(self, self->private->device_filename);
864         /* if the open failed, then try_open_tape_device already set the
865          * approppriate error status */
866         if (self->fd == -1)
867             return dself->status;
868     }
869
870     /* Rewind it. */
871     if (!tape_rewind(self->fd)) {
872         device_set_error(dself,
873             vstrallocf(_("Error rewinding device %s to read label: %s"),
874                     self->private->device_filename, strerror(errno)),
875               DEVICE_STATUS_DEVICE_ERROR
876             | DEVICE_STATUS_VOLUME_ERROR);
877         return dself->status;
878     }
879
880     buffer_len = tape_device_read_size(self);
881     header_buffer = malloc(buffer_len);
882     result = tape_device_robust_read(self, header_buffer, &buffer_len, &msg);
883
884     if (result != RESULT_SUCCESS) {
885         free(header_buffer);
886         tape_rewind(self->fd);
887         /* I/O error. */
888         switch (result) {
889         case RESULT_NO_DATA:
890             msg = stralloc(_("no data"));
891             new_status = (DEVICE_STATUS_VOLUME_ERROR |
892                           DEVICE_STATUS_VOLUME_UNLABELED);
893             header = dself->volume_header = g_new(dumpfile_t, 1);
894             fh_init(header);
895             break;
896
897         case RESULT_SMALL_BUFFER:
898             msg = stralloc(_("block size too small"));
899             new_status = (DEVICE_STATUS_DEVICE_ERROR |
900                           DEVICE_STATUS_VOLUME_ERROR);
901             header = dself->volume_header = g_new(dumpfile_t, 1);
902             fh_init(header);
903             header->type = F_WEIRD;
904             break;
905
906         default:
907             msg = stralloc(_("unknown error"));
908         case RESULT_ERROR:
909             new_status = (DEVICE_STATUS_DEVICE_ERROR |
910                           DEVICE_STATUS_VOLUME_ERROR |
911                           DEVICE_STATUS_VOLUME_UNLABELED);
912             break;
913         }
914         device_set_error(dself,
915                  g_strdup_printf(_("Error reading Amanda header: %s"),
916                         msg? msg : _("unknown error")),
917                  new_status);
918         amfree(msg);
919         return dself->status;
920     }
921
922     header = dself->volume_header = g_new(dumpfile_t, 1);
923     fh_init(header);
924
925     parse_file_header(header_buffer, header, buffer_len);
926     amfree(header_buffer);
927     if (header->type != F_TAPESTART) {
928         device_set_error(dself,
929                 stralloc(_("No tapestart header -- unlabeled device?")),
930                 DEVICE_STATUS_VOLUME_UNLABELED);
931         return dself->status;
932     }
933
934     dself->volume_label = g_strdup(header->name);
935     dself->volume_time = g_strdup(header->datestamp);
936     /* dself->volume_header is already set */
937
938     device_set_error(dself, NULL, DEVICE_STATUS_SUCCESS);
939
940     return dself->status;
941 }
942
943 static gboolean
944 tape_device_write_block(Device * pself, guint size, gpointer data) {
945     TapeDevice * self;
946     char *replacement_buffer = NULL;
947     IoResult result;
948     char *msg = NULL;
949
950     self = TAPE_DEVICE(pself);
951
952     g_assert(self->fd >= 0);
953     if (device_in_error(self)) return FALSE;
954
955     /* zero out to the end of a short block -- tape devices only write
956      * whole blocks. */
957     if (size < pself->block_size) {
958         replacement_buffer = malloc(pself->block_size);
959         memcpy(replacement_buffer, data, size);
960         bzero(replacement_buffer+size, pself->block_size-size);
961
962         data = replacement_buffer;
963         size = pself->block_size;
964     }
965
966     result = tape_device_robust_write(self, data, size, &msg);
967     amfree(replacement_buffer);
968
969     switch (result) {
970         case RESULT_SUCCESS:
971             break;
972
973         case RESULT_NO_SPACE:
974             device_set_error(pself,
975                 stralloc(_("No space left on device")),
976                 DEVICE_STATUS_VOLUME_ERROR);
977             pself->is_eom = TRUE;
978             return FALSE;
979
980         default:
981             msg = stralloc(_("unknown error"));
982         case RESULT_ERROR:
983             device_set_error(pself,
984                 g_strdup_printf(_("Error writing block: %s"), msg),
985                 DEVICE_STATUS_DEVICE_ERROR);
986             amfree(msg);
987             return FALSE;
988     }
989
990     pself->block++;
991
992     return TRUE;
993 }
994
995 static int tape_device_read_block (Device * pself, gpointer buf,
996                                    int * size_req) {
997     TapeDevice * self;
998     int size;
999     IoResult result;
1000     gssize read_block_size = tape_device_read_size(pself);
1001     char *msg = NULL;
1002
1003     self = TAPE_DEVICE(pself);
1004
1005     g_assert(self->fd >= 0);
1006     if (device_in_error(self)) return -1;
1007
1008     g_assert(read_block_size < INT_MAX); /* data type mismatch */
1009     if (buf == NULL || *size_req < (int)read_block_size) {
1010         /* Just a size query. */
1011         *size_req = (int)read_block_size;
1012         return 0;
1013     }
1014
1015     size = *size_req;
1016     result = tape_device_robust_read(self, buf, &size, &msg);
1017     switch (result) {
1018     case RESULT_SUCCESS:
1019         *size_req = size;
1020         pself->block++;
1021         return size;
1022     case RESULT_SMALL_BUFFER: {
1023         gsize new_size;
1024         GValue newval;
1025
1026         /* If this happens, it means that we have:
1027          *     (next block size) > (buffer size) >= (read_block_size)
1028          * The solution is to ask for an even bigger buffer. We also play
1029          * some games to refrain from reading above the SCSI limit or from
1030          * integer overflow.  Note that not all devices will tell us about
1031          * this problem -- some will just discard the "extra" data. */
1032         new_size = MIN(INT_MAX/2 - 1, *size_req) * 2;
1033         if (new_size > LARGEST_BLOCK_ESTIMATE &&
1034             *size_req < LARGEST_BLOCK_ESTIMATE) {
1035             new_size = LARGEST_BLOCK_ESTIMATE;
1036         }
1037         g_assert (new_size > (gsize)*size_req);
1038
1039         g_info("Device %s indicated blocksize %zd was too small; using %zd.",
1040             pself->device_name, (gsize)*size_req, new_size);
1041         *size_req = (int)new_size;
1042         self->private->read_block_size = new_size;
1043
1044         bzero(&newval, sizeof(newval));
1045         g_value_init(&newval, G_TYPE_UINT);
1046         g_value_set_uint(&newval, self->private->read_block_size);
1047         device_set_simple_property(pself, PROPERTY_READ_BLOCK_SIZE,
1048                 &newval, PROPERTY_SURETY_GOOD, PROPERTY_SOURCE_DETECTED);
1049         g_value_unset(&newval);
1050
1051         return 0;
1052     }
1053     case RESULT_NO_DATA:
1054         pself->is_eof = TRUE;
1055         pself->in_file = FALSE;
1056         device_set_error(pself,
1057             stralloc(_("EOF")),
1058             DEVICE_STATUS_SUCCESS);
1059         return -1;
1060
1061     default:
1062         msg = stralloc(_("unknown error"));
1063     case RESULT_ERROR:
1064         device_set_error(pself,
1065             vstrallocf(_("Error reading from tape device: %s"), msg),
1066             DEVICE_STATUS_VOLUME_ERROR | DEVICE_STATUS_DEVICE_ERROR);
1067         amfree(msg);
1068         return -1;
1069     }
1070
1071     g_assert_not_reached();
1072 }
1073
1074 /* Just a helper function for tape_device_start(). */
1075 static gboolean write_tapestart_header(TapeDevice * self, char * label,
1076                                        char * timestamp) {
1077      IoResult result;
1078      dumpfile_t * header;
1079      char * header_buf;
1080      Device * d_self = (Device*)self;
1081      char *msg = NULL;
1082
1083      tape_rewind(self->fd);
1084
1085      header = make_tapestart_header(d_self, label, timestamp);
1086      g_assert(header != NULL);
1087      header_buf = device_build_amanda_header(d_self, header, NULL);
1088      if (header_buf == NULL) {
1089          device_set_error(d_self,
1090             stralloc(_("Tapestart header won't fit in a single block!")),
1091             DEVICE_STATUS_DEVICE_ERROR);
1092          dumpfile_free(header);
1093          return FALSE;
1094      }
1095      dumpfile_free(d_self->volume_header);
1096      d_self->volume_header = NULL;
1097
1098      result = tape_device_robust_write(self, header_buf, d_self->block_size, &msg);
1099      if (result != RESULT_SUCCESS) {
1100         device_set_error(d_self,
1101             g_strdup_printf(_("Error writing tapestart header: %s"),
1102                         (result == RESULT_ERROR)? msg : _("out of space")),
1103             DEVICE_STATUS_DEVICE_ERROR);
1104
1105         if (result == RESULT_NO_SPACE)
1106             d_self->is_eom = TRUE;
1107
1108         amfree(msg);
1109         dumpfile_free(header);
1110         amfree(header_buf);
1111         return FALSE;
1112      }
1113
1114      amfree(header_buf);
1115
1116      if (!tape_weof(self->fd, 1)) {
1117         device_set_error(d_self,
1118                          vstrallocf(_("Error writing filemark: %s"),
1119                                     strerror(errno)),
1120                          DEVICE_STATUS_DEVICE_ERROR|DEVICE_STATUS_VOLUME_ERROR);
1121         /* can't tell if this was EOM or not, so assume it is */
1122         d_self->is_eom = TRUE;
1123         dumpfile_free(header);
1124         return FALSE;
1125      }
1126
1127      d_self->volume_header = header;
1128      return TRUE;
1129 }
1130
1131 static gboolean
1132 tape_device_start (Device * d_self, DeviceAccessMode mode, char * label,
1133                    char * timestamp) {
1134     TapeDevice * self;
1135
1136     self = TAPE_DEVICE(d_self);
1137
1138     if (device_in_error(self)) return FALSE;
1139
1140     if (self->fd == -1) {
1141         self->fd = try_open_tape_device(self, self->private->device_filename);
1142         /* if the open failed, then try_open_tape_device already set the
1143          * approppriate error status */
1144         if (self->fd == -1)
1145             return FALSE;
1146     }
1147
1148     if (mode != ACCESS_WRITE && d_self->volume_label == NULL) {
1149         /* we need a labeled volume for APPEND and READ */
1150         if (tape_device_read_label(d_self) != DEVICE_STATUS_SUCCESS)
1151             return FALSE;
1152     }
1153
1154     d_self->access_mode = mode;
1155     d_self->in_file = FALSE;
1156
1157     if (IS_WRITABLE_ACCESS_MODE(mode)) {
1158         if (self->write_open_errno != 0) {
1159             /* We tried and failed to open the device in write mode. */
1160             device_set_error(d_self,
1161                 vstrallocf(_("Can't open tape device %s for writing: %s"),
1162                             self->private->device_filename, strerror(self->write_open_errno)),
1163                 DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
1164             return FALSE;
1165         } else if (!tape_rewind(self->fd)) {
1166             device_set_error(d_self,
1167                 vstrallocf(_("Error rewinding device to start: %s"), strerror(errno)),
1168                 DEVICE_STATUS_DEVICE_ERROR);
1169             return FALSE;
1170         }
1171     }
1172
1173     /* Position the tape */
1174     switch (mode) {
1175     case ACCESS_APPEND:
1176         if (d_self->volume_label == NULL && device_read_label(d_self) != DEVICE_STATUS_SUCCESS) {
1177             /* device_read_label already set our error message */
1178             return FALSE;
1179         }
1180
1181         if (!tape_device_eod(self)) {
1182             device_set_error(d_self,
1183                 vstrallocf(_("Couldn't seek to end of tape: %s"), strerror(errno)),
1184                 DEVICE_STATUS_DEVICE_ERROR);
1185             return FALSE;
1186         }
1187         break;
1188
1189     case ACCESS_READ:
1190         if (d_self->volume_label == NULL && device_read_label(d_self) != DEVICE_STATUS_SUCCESS) {
1191             /* device_read_label already set our error message */
1192             return FALSE;
1193         }
1194
1195         if (!tape_rewind(self->fd)) {
1196             device_set_error(d_self,
1197                 vstrallocf(_("Error rewinding device after reading label: %s"), strerror(errno)),
1198                 DEVICE_STATUS_DEVICE_ERROR);
1199             return FALSE;
1200         }
1201         d_self->file = 0;
1202         break;
1203
1204     case ACCESS_WRITE:
1205         if (!write_tapestart_header(self, label, timestamp)) {
1206             /* write_tapestart_header already set the error status */
1207             return FALSE;
1208         }
1209
1210         d_self->volume_label = newstralloc(d_self->volume_label, label);
1211         d_self->volume_time = newstralloc(d_self->volume_time, timestamp);
1212
1213         /* unset the VOLUME_UNLABELED flag, if it was set */
1214         device_set_error(d_self, NULL, DEVICE_STATUS_SUCCESS);
1215         d_self->file = 0;
1216         break;
1217
1218     default:
1219         g_assert_not_reached();
1220     }
1221
1222     return TRUE;
1223 }
1224
1225 static gboolean tape_device_start_file(Device * d_self,
1226                                        dumpfile_t * info) {
1227     TapeDevice * self;
1228     IoResult result;
1229     char * amanda_header;
1230     char *msg = NULL;
1231
1232     self = TAPE_DEVICE(d_self);
1233
1234     g_assert(self->fd >= 0);
1235     if (device_in_error(self)) return FALSE;
1236
1237     /* set the blocksize in the header properly */
1238     info->blocksize = d_self->block_size;
1239
1240     /* Make the Amanda header suitable for writing to the device. */
1241     /* Then write the damn thing. */
1242     amanda_header = device_build_amanda_header(d_self, info, NULL);
1243     if (amanda_header == NULL) {
1244         device_set_error(d_self,
1245             stralloc(_("Amanda file header won't fit in a single block!")),
1246             DEVICE_STATUS_DEVICE_ERROR);
1247         return FALSE;
1248     }
1249
1250     result = tape_device_robust_write(self, amanda_header, d_self->block_size, &msg);
1251     if (result != RESULT_SUCCESS) {
1252         device_set_error(d_self,
1253             vstrallocf(_("Error writing file header: %s"),
1254                         (result == RESULT_ERROR)? msg : _("out of space")),
1255             DEVICE_STATUS_DEVICE_ERROR);
1256
1257         if (result == RESULT_NO_SPACE)
1258             d_self->is_eom = TRUE;
1259
1260         amfree(amanda_header);
1261         amfree(msg);
1262         return FALSE;
1263     }
1264     amfree(amanda_header);
1265
1266     /* arrange the file numbers correctly */
1267     d_self->in_file = TRUE;
1268     d_self->block = 0;
1269     if (d_self->file >= 0)
1270         d_self->file ++;
1271     return TRUE;
1272 }
1273
1274 static gboolean
1275 tape_device_finish_file (Device * d_self) {
1276     TapeDevice * self;
1277
1278     self = TAPE_DEVICE(d_self);
1279     if (device_in_error(d_self)) return FALSE;
1280
1281     if (!tape_weof(self->fd, 1)) {
1282         device_set_error(d_self,
1283                 vstrallocf(_("Error writing filemark: %s"), strerror(errno)),
1284                 DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
1285         /* can't tell if this was EOM or not, so assume it is */
1286         d_self->is_eom = TRUE;
1287         return FALSE;
1288     }
1289
1290     d_self->in_file = FALSE;
1291     return TRUE;
1292 }
1293
1294 static dumpfile_t *
1295 tape_device_seek_file (Device * d_self, guint file) {
1296     TapeDevice * self;
1297     gint got_file;
1298     int difference;
1299     char * header_buffer;
1300     dumpfile_t * rval;
1301     int buffer_len;
1302     IoResult result;
1303     char *msg;
1304
1305     self = TAPE_DEVICE(d_self);
1306
1307     if (device_in_error(self)) return NULL;
1308
1309     difference = file - d_self->file;
1310
1311     /* Check if we already read a filemark. */
1312     /* If we already read a filemark and the drive automaticaly goes to the
1313        next file, then we must reduce the difference by one. */
1314     if (d_self->is_eof && !self->fsf_after_filemark) {
1315         difference --;
1316     }
1317
1318     d_self->in_file = FALSE;
1319     d_self->is_eof = FALSE;
1320     d_self->block = 0;
1321
1322 reseek:
1323     if (difference > 0) {
1324         /* Seeking forwards */
1325         if (!tape_device_fsf(self, difference)) {
1326             tape_rewind(self->fd);
1327             device_set_error(d_self,
1328                 vstrallocf(_("Could not seek forward to file %d"), file),
1329                 DEVICE_STATUS_VOLUME_ERROR | DEVICE_STATUS_DEVICE_ERROR);
1330             return NULL;
1331         }
1332     } else { /* (difference <= 0) */
1333         /* Seeking backwards, or to this file itself */
1334
1335         /* if the drive supports bsf, we can do this the fancy way */
1336         if (self->bsf) {
1337             /* bsf one more than the difference */
1338             if (!tape_bsf(self->fd, -difference + 1)) {
1339                 tape_rewind(self->fd);
1340                 device_set_error(d_self,
1341                     vstrallocf(_("Could not seek backward to file %d"), file),
1342                     DEVICE_STATUS_VOLUME_ERROR | DEVICE_STATUS_DEVICE_ERROR);
1343                 return NULL;
1344             }
1345
1346             /* now we are on the BOT side of the desired filemark, so FSF to get to the
1347              * EOT side of it */
1348             if (!tape_device_fsf(self, 1)) {
1349                 tape_rewind(self->fd);
1350                 device_set_error(d_self,
1351                     vstrallocf(_("Could not seek forward to file %d"), file),
1352                     DEVICE_STATUS_VOLUME_ERROR | DEVICE_STATUS_DEVICE_ERROR);
1353                 return NULL;
1354             }
1355         } else {
1356             /* no BSF, so just rewind and seek forward */
1357             if (!tape_rewind(self->fd)) {
1358                 device_set_error(d_self,
1359                     vstrallocf(_("Could not rewind device while emulating BSF")),
1360                     DEVICE_STATUS_VOLUME_ERROR | DEVICE_STATUS_DEVICE_ERROR);
1361                 return FALSE;
1362             }
1363
1364             if (!tape_device_fsf(self, file)) {
1365                 tape_rewind(self->fd);
1366                 device_set_error(d_self,
1367                     vstrallocf(_("Could not seek forward to file %d"), file),
1368                     DEVICE_STATUS_VOLUME_ERROR | DEVICE_STATUS_DEVICE_ERROR);
1369                 return NULL;
1370             }
1371         }
1372     }
1373
1374     /* double-check that we're on the right fileno, if possible.  This is most
1375      * likely a programming error if it occurs, but could also be due to a weird
1376      * tape drive or driver (and that would *never* happen, right?) */
1377     got_file = tape_fileno(self->fd);
1378     if (got_file >= 0 && (guint)got_file != file) {
1379         device_set_error(d_self,
1380                 vstrallocf(_("Could not seek to file %d correctly; got %d"),
1381                             file, got_file),
1382                 DEVICE_STATUS_DEVICE_ERROR);
1383         d_self->file = (guint)got_file;
1384         return NULL;
1385     }
1386
1387     buffer_len = tape_device_read_size(d_self);
1388     header_buffer = malloc(buffer_len);
1389     d_self->is_eof = FALSE;
1390     result = tape_device_robust_read(self, header_buffer, &buffer_len, &msg);
1391
1392     if (result != RESULT_SUCCESS) {
1393         free(header_buffer);
1394         tape_rewind(self->fd);
1395         switch (result) {
1396         case RESULT_NO_DATA:
1397             /* If we read 0 bytes, that means we encountered a double
1398              * filemark, which indicates end of tape. This should
1399              * work even with QIC tapes on operating systems with
1400              * proper support. */
1401             d_self->file = file; /* other attributes are already correct */
1402             return make_tapeend_header();
1403
1404         case RESULT_SMALL_BUFFER:
1405             msg = stralloc(_("block size too small"));
1406             break;
1407
1408         default:
1409             msg = stralloc(_("unknown error"));
1410         case RESULT_ERROR:
1411             break;
1412         }
1413         device_set_error(d_self,
1414             g_strdup_printf(_("Error reading Amanda header: %s"), msg),
1415             DEVICE_STATUS_DEVICE_ERROR | DEVICE_STATUS_VOLUME_ERROR);
1416         amfree(msg);
1417         return NULL;
1418     }
1419
1420     rval = g_new(dumpfile_t, 1);
1421     parse_file_header(header_buffer, rval, buffer_len);
1422     amfree(header_buffer);
1423     switch (rval->type) {
1424     case F_DUMPFILE:
1425     case F_CONT_DUMPFILE:
1426     case F_SPLIT_DUMPFILE:
1427         break;
1428
1429     case F_NOOP:
1430         /* a NOOP is written on QIC tapes to avoid writing two sequential
1431          * filemarks when closing a device in WRITE or APPEND mode.  In this
1432          * case, we just seek to the next file. */
1433         amfree(rval);
1434         file++;
1435         difference = 1;
1436         goto reseek;
1437
1438     default:
1439         tape_rewind(self->fd);
1440         device_set_error(d_self,
1441             stralloc(_("Invalid amanda header while reading file header")),
1442             DEVICE_STATUS_VOLUME_ERROR);
1443         amfree(rval);
1444         return NULL;
1445     }
1446
1447     d_self->in_file = TRUE;
1448     d_self->file = file;
1449
1450     return rval;
1451 }
1452
1453 static gboolean
1454 tape_device_seek_block (Device * d_self, guint64 block) {
1455     TapeDevice * self;
1456     int difference;
1457
1458     self = TAPE_DEVICE(d_self);
1459
1460     if (device_in_error(self)) return FALSE;
1461
1462     difference = block - d_self->block;
1463
1464     if (difference > 0) {
1465         if (!tape_device_fsr(self, difference)) {
1466             device_set_error(d_self,
1467                 vstrallocf(_("Could not seek forward to block %ju: %s"), (uintmax_t)block, strerror(errno)),
1468                 DEVICE_STATUS_VOLUME_ERROR | DEVICE_STATUS_DEVICE_ERROR);
1469             return FALSE;
1470         }
1471     } else if (difference < 0) {
1472         if (!tape_device_bsr(self, difference, d_self->file, d_self->block)) {
1473             device_set_error(d_self,
1474                 vstrallocf(_("Could not seek backward to block %ju: %s"), (uintmax_t)block, strerror(errno)),
1475                 DEVICE_STATUS_VOLUME_ERROR | DEVICE_STATUS_DEVICE_ERROR);
1476             return FALSE;
1477         }
1478     }
1479
1480     d_self->block = block;
1481     return TRUE;
1482 }
1483
1484 static gboolean
1485 tape_device_eject (Device * d_self) {
1486     TapeDevice * self;
1487
1488     self = TAPE_DEVICE(d_self);
1489
1490     if (device_in_error(self)) return FALSE;
1491
1492     /* Open the device if not already opened */
1493     if (self->fd == -1) {
1494         self->fd = try_open_tape_device(self, self->private->device_filename);
1495         /* if the open failed, then try_open_tape_device already set the
1496          * approppriate error status */
1497         if (self->fd == -1)
1498             return FALSE;
1499     }
1500
1501     /* Rewind it. */
1502     if (!tape_rewind(self->fd)) {
1503         device_set_error(d_self,
1504             vstrallocf(_("Error rewinding device %s before ejecting: %s"),
1505                        self->private->device_filename, strerror(errno)),
1506               DEVICE_STATUS_DEVICE_ERROR
1507             | DEVICE_STATUS_VOLUME_ERROR);
1508         return FALSE;
1509     }
1510
1511     if (tape_offl(self->fd))
1512         return TRUE;
1513
1514     device_set_error(d_self,
1515         vstrallocf(_("Error ejecting device %s: %s\n"),
1516                    self->private->device_filename, strerror(errno)),
1517           DEVICE_STATUS_DEVICE_ERROR);
1518
1519     return FALSE;
1520 }
1521
1522 static gboolean
1523 tape_device_finish (Device * d_self) {
1524     TapeDevice * self;
1525     char *msg = NULL;
1526
1527     self = TAPE_DEVICE(d_self);
1528
1529     if (device_in_error(self))
1530         goto finish_error;
1531
1532     /* if we're already in ACCESS_NULL, then there are no filemarks or anything
1533      * to worry about, but we need to release the kernel device */
1534     if (d_self->access_mode == ACCESS_NULL) {
1535         robust_close(self->fd);
1536         self->fd = -1;
1537         return TRUE;
1538     }
1539
1540     /* Polish off this file, if relevant. */
1541     if (d_self->in_file && IS_WRITABLE_ACCESS_MODE(d_self->access_mode)) {
1542         if (!device_finish_file(d_self))
1543             goto finish_error;
1544     }
1545
1546     /* Straighten out the filemarks.  We already wrote one in finish_file, and
1547      * the device driver will write another filemark when we rewind.  This means
1548      * that, if we do nothing, we'll get two filemarks.  If final_filemarks is
1549      * 1, this would be wrong, so in this case we insert a F_NOOP header between
1550      * the two filemarks. */
1551     if (self->final_filemarks == 1 &&
1552         IS_WRITABLE_ACCESS_MODE(d_self->access_mode)) {
1553         dumpfile_t file;
1554         char *header;
1555         int result;
1556
1557         /* write a F_NOOP header */
1558         fh_init(&file);
1559         file.type = F_NOOP;
1560         header = device_build_amanda_header(d_self, &file, NULL);
1561         if (!header) {
1562             device_set_error(d_self,
1563                 stralloc(_("Amanda file header won't fit in a single block!")),
1564                 DEVICE_STATUS_DEVICE_ERROR);
1565             goto finish_error;
1566         }
1567
1568         result = tape_device_robust_write(self, header, d_self->block_size, &msg);
1569         if (result != RESULT_SUCCESS) {
1570             device_set_error(d_self,
1571                 vstrallocf(_("Error writing file header: %s"),
1572                             (result == RESULT_ERROR)? msg : _("out of space")),
1573                 DEVICE_STATUS_DEVICE_ERROR);
1574             amfree(header);
1575             amfree(msg);
1576             goto finish_error;
1577         }
1578         amfree(header);
1579     }
1580
1581     /* Rewind (the kernel will write a filemark first) */
1582     if (!tape_rewind(self->fd)) {
1583         device_set_error(d_self,
1584             vstrallocf(_("Couldn't rewind device to finish: %s"), strerror(errno)),
1585             DEVICE_STATUS_DEVICE_ERROR);
1586         goto finish_error;
1587     }
1588
1589     d_self->is_eof = FALSE;
1590     d_self->access_mode = ACCESS_NULL;
1591
1592     /* release the kernel's device */
1593     robust_close(self->fd);
1594     self->fd = -1;
1595
1596     return TRUE;
1597
1598 finish_error:
1599     d_self->access_mode = ACCESS_NULL;
1600
1601     /* release the kernel's device */
1602     robust_close(self->fd);
1603     self->fd = -1;
1604
1605     return FALSE;
1606 }
1607
1608 /* Works just like read(), except for the following:
1609  * 1) Retries on EINTR & friends.
1610  * 2) Stores count in parameter, not return value.
1611  * 3) Provides explicit return result.
1612  * *errmsg is only set on RESULT_ERROR.
1613  */
1614 static IoResult
1615 tape_device_robust_read (TapeDevice * self, void * buf, int * count, char **errmsg) {
1616     Device * d_self;
1617     int result;
1618
1619     d_self = (Device*)self;
1620
1621     /* Callers should ensure this. */
1622     g_assert(*count >= 0);
1623
1624     for (;;) {
1625         result = read(self->fd, buf, *count);
1626         if (result > 0) {
1627             /* Success. By definition, we read a full block. */
1628             d_self->is_eof = FALSE;
1629             *count = result;
1630             return RESULT_SUCCESS;
1631         } else if (result == 0) {
1632             d_self->is_eof = TRUE;
1633             return RESULT_NO_DATA;
1634         } else {
1635             if (0
1636 #ifdef EAGAIN
1637                 || errno == EAGAIN
1638 #endif
1639 #ifdef EWOULDBLOCK
1640                 || errno == EWOULDBLOCK
1641 #endif
1642 #ifdef EINTR
1643                 || errno == EINTR
1644 #endif
1645                 ) {
1646                 /* Interrupted system call */
1647                 continue;
1648             } else if ((0
1649 #ifdef ENOMEM
1650                         || errno == ENOMEM /* bad user-space buffer */
1651 #endif
1652 #ifdef EOVERFLOW
1653                         || errno == EOVERFLOW /* bad kernel-space buffer */
1654 #endif
1655 #ifdef EINVAL
1656                         || errno == EINVAL /* ??? */
1657 #endif
1658                         )) {
1659                 /* Buffer too small. */
1660                 g_warning("Buffer is too small (%d bytes) from %s: %s",
1661                         *count, self->private->device_filename, strerror(errno));
1662                 return RESULT_SMALL_BUFFER;
1663             } else {
1664                 *errmsg = g_strdup_printf(_("Error reading %d bytes from %s: %s"),
1665                         *count, self->private->device_filename, strerror(errno));
1666                 return RESULT_ERROR;
1667             }
1668         }
1669     }
1670
1671     g_assert_not_reached();
1672 }
1673
1674 /* Kernel workaround: If needed, poke the kernel so it doesn't fail.
1675    at the 2GB boundry. Parameters are G_GNUC_UNUSED in case NEED_RESETOFS
1676    is not defined. */
1677 static void check_resetofs(TapeDevice * self G_GNUC_UNUSED,
1678                            int count G_GNUC_UNUSED) {
1679 #ifdef NEED_RESETOFS
1680     Device * d_self;
1681     int result;
1682
1683     d_self = (Device*)self;
1684
1685     self->private->write_count += count;
1686     if (self->private->write_count < RESETOFS_THRESHOLD) {
1687         return;
1688     }
1689
1690     result = lseek(self->fd, 0, SEEK_SET);
1691     if (result < 0) {
1692         g_warning(_("lseek() failed during kernel 2GB workaround: %s"),
1693                strerror(errno));
1694     }
1695 #endif
1696 }
1697
1698 /* *errmsg is only set on RESULT_ERROR */
1699 static IoResult
1700 tape_device_robust_write (TapeDevice * self, void * buf, int count, char **errmsg) {
1701     Device * d_self;
1702     int result;
1703     gboolean retry = FALSE;
1704
1705     d_self = (Device*)self;
1706
1707     check_resetofs(self, count);
1708
1709     for (;;) {
1710         result = write(self->fd, buf, count);
1711
1712         /* Success. */
1713         if (result == count)
1714             return RESULT_SUCCESS;
1715
1716         if (result > 0) {
1717             /* write() returned a short count. This should not happen if the block sizes
1718              * are properly aligned. */
1719             *errmsg = g_strdup_printf("Short write on tape device: Tried %d, got %d.  Is "
1720                             "the drive using a block size smaller than %d bytes?",
1721                                 count, result, count);
1722             return RESULT_ERROR;
1723         }
1724
1725         /* Detect LEOM (early warning) and handle properly
1726          *
1727          * FreeBSD: 0-length write; next write will succeed
1728          *   http://lists.freebsd.org/pipermail/freebsd-scsi/2010-June/004414.html
1729          *
1730          * Solaris: 0-length write; next write will succeed
1731          *   (from Matthew Jacob on FreeBSD thread)
1732          *
1733          * Linux: -1/ENOSPC; next write will succeed
1734          *   http://www.mjmwired.net/kernel/Documentation/scsi/st.txt
1735          *
1736          * HP/UX: -1/ENOSPC; next write will succeed
1737          *   http://www.adssasia.com/Manual/IBM%203581%20tape%20autoloader.pdf
1738          */
1739         if (result == 0
1740 #ifdef ENOSPC
1741                         || (result < 0 && errno == ENOSPC)
1742 #endif
1743         ) {
1744             /* if we've retried once already, then we're probably really out of space */
1745             if (retry)
1746                 return RESULT_NO_SPACE;
1747             retry = TRUE;
1748             d_self->is_eom = TRUE;
1749
1750             g_debug("empty write to tape; treating as LEOM early warning and retrying");
1751             continue;
1752         }
1753
1754         /* at this point result < 0, so an error occurred - sort out what */
1755
1756         if (0
1757 #ifdef EAGAIN
1758                    || errno == EAGAIN
1759 #endif
1760 #ifdef EWOULDBLOCK
1761                    || errno == EWOULDBLOCK
1762 #endif
1763 #ifdef EINTR
1764                    || errno == EINTR
1765 #endif
1766                    ) {
1767                 /* Interrupted system call */
1768             continue;
1769         } else if (0
1770 #ifdef ENOSPC
1771                    || errno == ENOSPC
1772 #endif
1773 #ifdef EIO
1774                    || errno == EIO
1775 #endif
1776                    ) {
1777             /* Probably EOT. Print a message if we got EIO. */
1778 #ifdef EIO
1779             if (errno == EIO) {
1780                 g_warning(_("Got EIO on %s, assuming end of tape"),
1781                         self->private->device_filename);
1782             }
1783 #endif
1784             return RESULT_NO_SPACE;
1785         } else {
1786             /* WTF */
1787             *errmsg = vstrallocf(_("Kernel gave unexpected write() result of \"%s\" on device %s"),
1788                             strerror(errno), self->private->device_filename);
1789             return RESULT_ERROR;
1790         }
1791     }
1792
1793     g_assert_not_reached();
1794 }
1795
1796 /* Reads some number of tape blocks into the bit-bucket. If the count
1797    is negative, then we read the rest of the entire file. Returns the
1798    number of blocks read, or -1 if an error occured. If we encounter
1799    EOF (as opposed to some other error) we return the number of blocks
1800    actually read. */
1801 static int drain_tape_blocks(TapeDevice * self, int count) {
1802     char * buffer;
1803     gsize buffer_size;
1804     int i;
1805
1806     buffer_size = tape_device_read_size(self);
1807
1808     buffer = malloc(buffer_size);
1809
1810     for (i = 0; i < count || count < 0;) {
1811         int result;
1812
1813         result = read(self->fd, buffer, buffer_size);
1814         if (result > 0) {
1815             i ++;
1816             continue;
1817         } else if (result == 0) {
1818             amfree(buffer);
1819             return i;
1820         } else {
1821             /* First check for interrupted system call. */
1822             if (0
1823 #ifdef EAGAIN
1824                 || errno == EAGAIN
1825 #endif
1826 #ifdef EWOULDBLOCK
1827                 || errno == EWOULDBLOCK
1828 #endif
1829 #ifdef EINTR
1830                 || errno == EINTR
1831 #endif
1832                 ) {
1833                 /* Interrupted system call */
1834                 continue;
1835             } else if (0
1836 #ifdef ENOSPC
1837                        || errno == ENOSPC /* bad user-space buffer */
1838 #endif
1839 #ifdef EOVERFLOW
1840                        || errno == EOVERFLOW /* bad kernel-space buffer */
1841 #endif
1842 #ifdef EINVAL
1843                        || errno == EINVAL /* ??? */
1844 #endif
1845                        ) {
1846                 /* The buffer may not be big enough. But the OS is not
1847                    100% clear. We double the buffer and try again, but
1848                    in no case allow a buffer bigger than 32 MB. */
1849                 buffer_size *= 2;
1850
1851                 if (buffer_size > 32*1024*1024) {
1852                     amfree(buffer);
1853                     return -1;
1854                 } else {
1855                     buffer = realloc(buffer, buffer_size);
1856                     continue;
1857                 }
1858             }
1859         }
1860     }
1861
1862     amfree(buffer);
1863     return count;
1864 }
1865
1866 static gboolean
1867 tape_device_fsf (TapeDevice * self, guint count) {
1868     if (self->fsf) {
1869         return tape_fsf(self->fd, count);
1870     } else {
1871         guint i;
1872         for (i = 0; i < count; i ++) {
1873             if (drain_tape_blocks(self, -1) < 0)
1874                 return FALSE;
1875         }
1876         return TRUE;
1877     }
1878 }
1879
1880
1881 static gboolean
1882 tape_device_fsr (TapeDevice * self, guint count) {
1883     if (self->fsr) {
1884         return tape_fsr(self->fd, count);
1885     } else {
1886         int result = drain_tape_blocks(self, count);
1887         return result > 0 && (int)count == result;
1888     }
1889 }
1890
1891 /* Seek back the given number of blocks to block number block within
1892  * the current file, numbered file. */
1893
1894 static gboolean
1895 tape_device_bsr (TapeDevice * self, guint count, guint file, guint block) {
1896     if (self->bsr) {
1897         return tape_bsr(self->fd, count);
1898     } else if (self->bsf && self->fsf) {
1899         /* BSF, FSF to the right side of the filemark, and then FSR. */
1900         if (!tape_bsf(self->fd, 1))
1901             return FALSE;
1902
1903         if (!tape_fsf(self->fd, 1))
1904             return FALSE;
1905
1906         return tape_device_fsr(self, block);
1907     } else {
1908         /* rewind, FSF, and FSR */
1909         if (!tape_rewind(self->fd))
1910             return FALSE;
1911
1912         if (!tape_device_fsf(self, file))
1913             return FALSE;
1914
1915         return tape_device_fsr(self, block);
1916     }
1917     g_assert_not_reached();
1918 }
1919
1920 /* Go to the right place to write more data, and update the file
1921    number if possible. */
1922 static gboolean
1923 tape_device_eod (TapeDevice * self) {
1924     Device * d_self;
1925     int count;
1926
1927     d_self = (Device*)self;
1928
1929     if (self->eom) {
1930         int result;
1931         result = tape_eod(self->fd);
1932         if (result == TAPE_OP_ERROR) {
1933             return FALSE;
1934         } else if (result != TAPE_POSITION_UNKNOWN) {
1935             /* great - we just fast-forwarded to EOD, but don't know where we are, so
1936              * now we have to rewind and drain all of that data.  Warn the user so that
1937              * we can skip the fast-forward-rewind stage on the next run */
1938             g_warning("Seek to end of tape does not give an accurate tape position; set "
1939                       "the EOM property to 0 to avoid useless tape movement.");
1940             /* and set the property so that next time *this* object is opened for
1941              * append, we skip this stage */
1942             self->eom = FALSE;
1943             /* fall through to draining blocks, below */
1944         } else {
1945             /* We drop by 1 because Device will increment the first
1946                time the user does start_file. */
1947             d_self->file = result - 1;
1948             return TRUE;
1949         }
1950     }
1951
1952     if (!tape_rewind(self->fd))
1953         return FALSE;
1954
1955     count = 0;
1956     for (;;) {
1957         /* We alternately read a block and FSF. If the read is
1958            successful, then we are not there yet and should FSF
1959            again. */
1960         int result;
1961         result = drain_tape_blocks(self, 1);
1962         if (result == 1) {
1963             /* More data, FSF. */
1964             tape_device_fsf(self, 1);
1965             count ++;
1966         } else if (result == 0) {
1967             /* Finished. */
1968             d_self->file = count - 1;
1969             return TRUE;
1970         } else {
1971             return FALSE;
1972         }
1973     }
1974 }
1975
1976 static Device *
1977 tape_device_factory (char * device_name, char * device_type, char * device_node) {
1978     Device * rval;
1979     g_assert(0 == strcmp(device_type, "tape"));
1980     rval = DEVICE(g_object_new(TYPE_TAPE_DEVICE, NULL));
1981     device_open_device(rval, device_name, device_type, device_node);
1982     return rval;
1983 }
1984
1985 /*
1986  * Tape Operations using the POSIX interface
1987  */
1988
1989 /* Having one name for every operation would be too easy. */
1990 #if !defined(MTCOMPRESSION) && defined(MTCOMP)
1991 # define MTCOMPRESSION MTCOMP
1992 #endif
1993
1994 #if !defined(MTSETBLK) && defined(MTSETBSIZ)
1995 # define MTSETBLK MTSETBSIZ
1996 #endif
1997
1998 #if !defined(MTEOM) && defined(MTEOD)
1999 # define MTEOM MTEOD
2000 #endif
2001
2002 gboolean tape_rewind(int fd) {
2003     int count = 5;
2004     time_t stop_time;
2005
2006     /* We will retry this for up to 30 seconds or 5 retries,
2007        whichever is less, because some hardware/software combinations
2008        (notably EXB-8200 on FreeBSD) can fail to rewind. */
2009     stop_time = time(NULL) + 30;
2010
2011     while (--count >= 0 && time(NULL) < stop_time) {
2012         struct mtop mt;
2013         mt.mt_op = MTREW;
2014         mt.mt_count = 1;
2015
2016         if (0 == ioctl(fd, MTIOCTOP, &mt))
2017             return TRUE;
2018
2019         sleep(3);
2020     }
2021
2022     return FALSE;
2023 }
2024
2025 gboolean tape_fsf(int fd, guint count) {
2026     struct mtop mt;
2027     mt.mt_op = MTFSF;
2028     mt.mt_count = count;
2029     return 0 == ioctl(fd, MTIOCTOP, &mt);
2030 }
2031
2032 gboolean tape_bsf(int fd, guint count) {
2033     struct mtop mt;
2034     mt.mt_op = MTBSF;
2035     mt.mt_count = count;
2036     return 0 == ioctl(fd, MTIOCTOP, &mt);
2037 }
2038
2039 gboolean tape_fsr(int fd, guint count) {
2040     struct mtop mt;
2041     mt.mt_op = MTFSR;
2042     mt.mt_count = count;
2043     return 0 == ioctl(fd, MTIOCTOP, &mt);
2044 }
2045
2046 gboolean tape_bsr(int fd, guint count) {
2047     struct mtop mt;
2048     mt.mt_op = MTBSR;
2049     mt.mt_count = count;
2050     return 0 == ioctl(fd, MTIOCTOP, &mt);
2051 }
2052
2053 gint tape_fileno(int fd) {
2054     struct mtget get;
2055
2056     if (0 != ioctl(fd, MTIOCGET, &get))
2057         return TAPE_POSITION_UNKNOWN;
2058     if (get.mt_fileno < 0)
2059         return TAPE_POSITION_UNKNOWN;
2060     else
2061         return get.mt_fileno;
2062 }
2063
2064 gint tape_eod(int fd) {
2065     struct mtop mt;
2066     struct mtget get;
2067     mt.mt_op = MTEOM;
2068     mt.mt_count = 1;
2069     if (0 != ioctl(fd, MTIOCTOP, &mt))
2070         return TAPE_OP_ERROR;
2071
2072     /* Ignored result. This is just to flush buffers. */
2073     mt.mt_op = MTNOP;
2074     ioctl(fd, MTIOCTOP, &mt);
2075
2076     if (0 != ioctl(fd, MTIOCGET, &get))
2077         return TAPE_POSITION_UNKNOWN;
2078     if (get.mt_fileno < 0)
2079         return TAPE_POSITION_UNKNOWN;
2080     else
2081         return get.mt_fileno;
2082 }
2083
2084 gboolean tape_weof(int fd, guint8 count) {
2085     struct mtop mt;
2086     mt.mt_op = MTWEOF;
2087     mt.mt_count = count;
2088     return 0 == ioctl(fd, MTIOCTOP, &mt);
2089 }
2090
2091 gboolean tape_setcompression(int fd G_GNUC_UNUSED, 
2092         gboolean on G_GNUC_UNUSED) {
2093 #ifdef MTCOMPRESSION
2094     struct mtop mt;
2095     mt.mt_op = MTCOMPRESSION;
2096     mt.mt_count = on;
2097     return 0 == ioctl(fd, MTIOCTOP, &mt);
2098 #else
2099     return 0;
2100 #endif
2101 }
2102
2103 gboolean tape_offl(int fd) {
2104     struct mtop mt;
2105     int safe_errno;
2106
2107     mt.mt_op = MTOFFL;
2108     mt.mt_count = 1;
2109     if (0 == ioctl(fd, MTIOCTOP, &mt))
2110         return TRUE;
2111
2112     safe_errno = errno;
2113     g_debug("tape_off: ioctl(MTIOCTOP/MTOFFL) failed: %s", strerror(errno));
2114     errno = safe_errno;
2115
2116     return FALSE;
2117 }
2118
2119 DeviceStatusFlags tape_is_tape_device(int fd) {
2120     struct mtop mt;
2121     mt.mt_op = MTNOP;
2122     mt.mt_count = 1;
2123     if (0 == ioctl(fd, MTIOCTOP, &mt)) {
2124         return DEVICE_STATUS_SUCCESS;
2125 #ifdef ENOMEDIUM
2126     } else if (errno == ENOMEDIUM) {
2127         return DEVICE_STATUS_VOLUME_MISSING;
2128 #endif
2129     } else {
2130         g_debug("tape_is_tape_device: ioctl(MTIOCTOP/MTNOP) failed: %s",
2131                  strerror(errno));
2132         if (errno == EIO) {
2133             /* some devices return EIO while the drive is busy loading */
2134             return DEVICE_STATUS_DEVICE_ERROR|DEVICE_STATUS_DEVICE_BUSY;
2135         } else {
2136             return DEVICE_STATUS_DEVICE_ERROR;
2137         }
2138     }
2139 }
2140
2141 DeviceStatusFlags tape_is_ready(int fd, TapeDevice *t_self G_GNUC_UNUSED) {
2142     struct mtget get;
2143     if (0 == ioctl(fd, MTIOCGET, &get)) {
2144 #if defined(GMT_ONLINE) || defined(GMT_DR_OPEN)
2145         if (1
2146 #ifdef GMT_ONLINE
2147             && (t_self->broken_gmt_online || GMT_ONLINE(get.mt_gstat))
2148 #endif
2149 #ifdef GMT_DR_OPEN
2150             && !GMT_DR_OPEN(get.mt_gstat)
2151 #endif
2152             ) {
2153             return DEVICE_STATUS_SUCCESS;
2154         } else {
2155             return DEVICE_STATUS_VOLUME_MISSING;
2156         }
2157 #else /* Neither macro is defined. */
2158         return DEVICE_STATUS_SUCCESS;
2159 #endif
2160     } else {
2161         return DEVICE_STATUS_VOLUME_ERROR;
2162     }
2163 }
2164