]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/block.c
c1317da712b4ca0f6f8ada930c98b29be855cd25
[bacula/bacula] / bacula / src / stored / block.c
1 /*
2  *
3  *   block.c -- tape block handling functions
4  *
5  *              Kern Sibbald, March MMI
6  *                 added BB02 format October MMII
7  *
8  *   Version $Id$
9  *
10  */
11 /*
12    Copyright (C) 2000-2005 Kern Sibbald
13
14    This program is free software; you can redistribute it and/or
15    modify it under the terms of the GNU General Public License as
16    published by the Free Software Foundation; either version 2 of
17    the License, or (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22    General Public License for more details.
23
24    You should have received a copy of the GNU General Public
25    License along with this program; if not, write to the Free
26    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27    MA 02111-1307, USA.
28
29  */
30
31
32 #include "bacula.h"
33 #include "stored.h"
34
35 extern int debug_level;
36 static bool terminate_writing_volume(DCR *dcr);
37
38 /*
39  * Dump the block header, then walk through
40  * the block printing out the record headers.
41  */
42 void dump_block(DEV_BLOCK *b, const char *msg)
43 {
44    ser_declare;
45    char *p;
46    char Id[BLKHDR_ID_LENGTH+1];
47    uint32_t CheckSum, BlockCheckSum;
48    uint32_t block_len;
49    uint32_t BlockNumber;
50    uint32_t VolSessionId, VolSessionTime, data_len;
51    int32_t  FileIndex;
52    int32_t  Stream;
53    int bhl, rhl;
54
55    unser_begin(b->buf, BLKHDR1_LENGTH);
56    unser_uint32(CheckSum);
57    unser_uint32(block_len);
58    unser_uint32(BlockNumber);
59    unser_bytes(Id, BLKHDR_ID_LENGTH);
60    ASSERT(unser_length(b->buf) == BLKHDR1_LENGTH);
61    Id[BLKHDR_ID_LENGTH] = 0;
62    if (Id[3] == '2') {
63       unser_uint32(VolSessionId);
64       unser_uint32(VolSessionTime);
65       bhl = BLKHDR2_LENGTH;
66       rhl = RECHDR2_LENGTH;
67    } else {
68       VolSessionId = VolSessionTime = 0;
69       bhl = BLKHDR1_LENGTH;
70       rhl = RECHDR1_LENGTH;
71    }
72
73    if (block_len > 100000) {
74       Dmsg3(20, "Dump block %s 0x%x blocksize too big %u\n", msg, b, block_len);
75       return;
76    }
77
78    BlockCheckSum = bcrc32((uint8_t *)b->buf+BLKHDR_CS_LENGTH,
79                          block_len-BLKHDR_CS_LENGTH);
80    Pmsg6(000, "Dump block %s %x: size=%d BlkNum=%d\n"
81 "               Hdrcksum=%x cksum=%x\n",
82       msg, b, block_len, BlockNumber, CheckSum, BlockCheckSum);
83    p = b->buf + bhl;
84    while (p < (b->buf + block_len+WRITE_RECHDR_LENGTH)) {
85       unser_begin(p, WRITE_RECHDR_LENGTH);
86       if (rhl == RECHDR1_LENGTH) {
87          unser_uint32(VolSessionId);
88          unser_uint32(VolSessionTime);
89       }
90       unser_int32(FileIndex);
91       unser_int32(Stream);
92       unser_uint32(data_len);
93       Pmsg6(000, "   Rec: VId=%u VT=%u FI=%s Strm=%s len=%d p=%x\n",
94            VolSessionId, VolSessionTime, FI_to_ascii(FileIndex),
95            stream_to_ascii(Stream, FileIndex), data_len, p);
96       p += data_len + rhl;
97   }
98 }
99
100 /*
101  * Create a new block structure.
102  * We pass device so that the block can inherit the
103  * min and max block sizes.
104  */
105 DEV_BLOCK *new_block(DEVICE *dev)
106 {
107    DEV_BLOCK *block = (DEV_BLOCK *)get_memory(sizeof(DEV_BLOCK));
108
109    memset(block, 0, sizeof(DEV_BLOCK));
110
111    /* If the user has specified a max_block_size, use it as the default */
112    if (dev->max_block_size == 0) {
113       block->buf_len = DEFAULT_BLOCK_SIZE;
114    } else {
115       block->buf_len = dev->max_block_size;
116    }
117    block->dev = dev;
118    block->block_len = block->buf_len;  /* default block size */
119    block->buf = get_memory(block->buf_len);
120    empty_block(block);
121    block->BlockVer = BLOCK_VER;       /* default write version */
122    Dmsg1(350, "Returning new block=%x\n", block);
123    return block;
124 }
125
126
127 /*
128  * Duplicate an existing block (eblock)
129  */
130 DEV_BLOCK *dup_block(DEV_BLOCK *eblock)
131 {
132    DEV_BLOCK *block = (DEV_BLOCK *)get_memory(sizeof(DEV_BLOCK));
133    int buf_len = sizeof_pool_memory(eblock->buf);
134
135    memcpy(block, eblock, sizeof(DEV_BLOCK));
136    block->buf = get_memory(buf_len);
137    memcpy(block->buf, eblock->buf, buf_len);
138    return block;
139 }
140
141
142 /*
143  * Only the first block checksum error was reported.
144  *   If there are more, report it now.
145  */
146 void print_block_read_errors(JCR *jcr, DEV_BLOCK *block)
147 {
148    if (block->read_errors > 1) {
149       Jmsg(jcr, M_ERROR, 0, _("%d block read errors not printed.\n"),
150          block->read_errors);
151    }
152 }
153
154 /*
155  * Free block
156  */
157 void free_block(DEV_BLOCK *block)
158 {
159    Dmsg1(199, "free_block buffer %x\n", block->buf);
160    free_memory(block->buf);
161    Dmsg1(199, "free_block block %x\n", block);
162    free_memory((POOLMEM *)block);
163 }
164
165 /* Empty the block -- for writing */
166 void empty_block(DEV_BLOCK *block)
167 {
168    block->binbuf = WRITE_BLKHDR_LENGTH;
169    block->bufp = block->buf + block->binbuf;
170    block->read_len = 0;
171    block->write_failed = false;
172    block->block_read = false;
173    block->FirstIndex = block->LastIndex = 0;
174 }
175
176 /*
177  * Create block header just before write. The space
178  * in the buffer should have already been reserved by
179  * init_block.
180  */
181 void ser_block_header(DEV_BLOCK *block)
182 {
183    ser_declare;
184    uint32_t CheckSum = 0;
185    uint32_t block_len = block->binbuf;
186
187    Dmsg1(390, "ser_block_header: block_len=%d\n", block_len);
188    ser_begin(block->buf, BLKHDR2_LENGTH);
189    ser_uint32(CheckSum);
190    ser_uint32(block_len);
191    ser_uint32(block->BlockNumber);
192    ser_bytes(WRITE_BLKHDR_ID, BLKHDR_ID_LENGTH);
193    if (BLOCK_VER >= 2) {
194       ser_uint32(block->VolSessionId);
195       ser_uint32(block->VolSessionTime);
196    }
197
198    /* Checksum whole block except for the checksum */
199    CheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH,
200                  block_len-BLKHDR_CS_LENGTH);
201    Dmsg1(390, "ser_bloc_header: checksum=%x\n", CheckSum);
202    ser_begin(block->buf, BLKHDR2_LENGTH);
203    ser_uint32(CheckSum);              /* now add checksum to block header */
204 }
205
206 /*
207  * Unserialize the block header for reading block.
208  *  This includes setting all the buffer pointers correctly.
209  *
210  *  Returns: false on failure (not a block)
211  *           true  on success
212  */
213 static bool unser_block_header(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
214 {
215    ser_declare;
216    char Id[BLKHDR_ID_LENGTH+1];
217    uint32_t CheckSum, BlockCheckSum;
218    uint32_t block_len;
219    uint32_t block_end;
220    uint32_t BlockNumber;
221    int bhl;
222
223    unser_begin(block->buf, BLKHDR_LENGTH);
224    unser_uint32(CheckSum);
225    unser_uint32(block_len);
226    unser_uint32(BlockNumber);
227    unser_bytes(Id, BLKHDR_ID_LENGTH);
228    ASSERT(unser_length(block->buf) == BLKHDR1_LENGTH);
229
230    Id[BLKHDR_ID_LENGTH] = 0;
231    if (Id[3] == '1') {
232       bhl = BLKHDR1_LENGTH;
233       block->BlockVer = 1;
234       block->bufp = block->buf + bhl;
235       if (strncmp(Id, BLKHDR1_ID, BLKHDR_ID_LENGTH) != 0) {
236          dev->dev_errno = EIO;
237          Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
238             dev->file, dev->block_num, BLKHDR1_ID, Id);
239          if (block->read_errors == 0 || verbose >= 2) {
240             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
241          }
242          block->read_errors++;
243          return false;
244       }
245    } else if (Id[3] == '2') {
246       unser_uint32(block->VolSessionId);
247       unser_uint32(block->VolSessionTime);
248       bhl = BLKHDR2_LENGTH;
249       block->BlockVer = 2;
250       block->bufp = block->buf + bhl;
251       if (strncmp(Id, BLKHDR2_ID, BLKHDR_ID_LENGTH) != 0) {
252          dev->dev_errno = EIO;
253          Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
254             dev->file, dev->block_num, BLKHDR2_ID, Id);
255          if (block->read_errors == 0 || verbose >= 2) {
256             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
257          }
258          block->read_errors++;
259          return false;
260       }
261    } else {
262       dev->dev_errno = EIO;
263       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Wanted ID: \"%s\", got \"%s\". Buffer discarded.\n"),
264           dev->file, dev->block_num, BLKHDR2_ID, Id);
265       if (block->read_errors == 0 || verbose >= 2) {
266          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
267       }
268       block->read_errors++;
269       unser_uint32(block->VolSessionId);
270       unser_uint32(block->VolSessionTime);
271       return false;
272    }
273
274    /* Sanity check */
275    if (block_len > MAX_BLOCK_LENGTH) {
276       dev->dev_errno = EIO;
277       Mmsg3(dev->errmsg,  _("Volume data error at %u:%u! Block length %u is insane (too large), probably due to a bad archive.\n"),
278          dev->file, dev->block_num, block_len);
279       if (block->read_errors == 0 || verbose >= 2) {
280          Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
281       }
282       block->read_errors++;
283       return false;
284    }
285
286    Dmsg1(390, "unser_block_header block_len=%d\n", block_len);
287    /* Find end of block or end of buffer whichever is smaller */
288    if (block_len > block->read_len) {
289       block_end = block->read_len;
290    } else {
291       block_end = block_len;
292    }
293    block->binbuf = block_end - bhl;
294    block->block_len = block_len;
295    block->BlockNumber = BlockNumber;
296    Dmsg3(390, "Read binbuf = %d %d block_len=%d\n", block->binbuf,
297       bhl, block_len);
298    if (block_len <= block->read_len) {
299       BlockCheckSum = bcrc32((uint8_t *)block->buf+BLKHDR_CS_LENGTH,
300                          block_len-BLKHDR_CS_LENGTH);
301       if (BlockCheckSum != CheckSum) {
302          dev->dev_errno = EIO;
303          Mmsg6(dev->errmsg, _("Volume data error at %u:%u!\n" 
304             "Block checksum mismatch in block=%u len=%d: calc=%x blk=%x\n"),
305             dev->file, dev->block_num, (unsigned)BlockNumber, 
306             block_len, BlockCheckSum, CheckSum);
307          if (block->read_errors == 0 || verbose >= 2) {
308             Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
309          }
310          block->read_errors++;
311          if (!forge_on) {
312             return false;
313          }
314       }
315    }
316    return true;
317 }
318
319 /*
320  * Write a block to the device, with locking and unlocking
321  *
322  * Returns: true  on success
323  *        : false on failure
324  *
325  */
326 bool write_block_to_device(DCR *dcr)
327 {
328    bool stat = true;
329    DEVICE *dev = dcr->dev;
330    JCR *jcr = dcr->jcr;
331
332    if (dcr->spooling) {
333       stat = write_block_to_spool_file(dcr);
334       return stat;
335    }
336
337    if (!dcr->dev_locked) {
338       lock_device(dev);
339    }
340
341    /*
342     * If a new volume has been mounted since our last write
343     *   Create a JobMedia record for the previous volume written,
344     *   and set new parameters to write this volume
345     * The same applies for if we are in a new file.
346     */
347    if (dcr->NewVol || dcr->NewFile) {
348       if (job_canceled(jcr)) {
349          stat = false;
350          goto bail_out;
351       }
352       /* Create a jobmedia record for this job */
353       if (!dir_create_jobmedia_record(dcr)) {
354          dev->dev_errno = EIO;
355          Jmsg(jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
356             dcr->VolCatInfo.VolCatName, jcr->Job);
357          set_new_volume_parameters(dcr);
358          stat = false;
359          goto bail_out;
360       }
361       if (dcr->NewVol) {
362          /* Note, setting a new volume also handles any pending new file */
363          set_new_volume_parameters(dcr);
364          dcr->NewFile = false;        /* this handled for new file too */
365       } else {
366          set_new_file_parameters(dcr);
367       }
368    }
369
370    if (!write_block_to_dev(dcr)) {
371        if (job_canceled(jcr) || jcr->JobType == JT_SYSTEM) {
372           stat = false;
373        } else {
374           stat = fixup_device_block_write_error(dcr);
375        }
376    }
377
378 bail_out:
379    if (!dcr->dev_locked) {
380       unlock_device(dev);
381    }
382    return stat;
383 }
384
385 /*
386  * Write a block to the device
387  *
388  *  Returns: true  on success or EOT
389  *           false on hard error
390  */
391 bool write_block_to_dev(DCR *dcr)
392 {
393    ssize_t stat = 0;
394    uint32_t wlen;                     /* length to write */
395    int hit_max1, hit_max2;
396    bool ok = true;
397    DEVICE *dev = dcr->dev;
398    JCR *jcr = dcr->jcr;
399    DEV_BLOCK *block = dcr->block;
400
401 #ifdef NO_TAPE_WRITE_TEST
402    empty_block(block);
403    return true;
404 #endif
405    ASSERT(block->binbuf == ((uint32_t) (block->bufp - block->buf)));
406
407    /* dump_block(block, "before write"); */
408    if (dev->state & ST_WEOT) {
409       Dmsg0(100, "return write_block_to_dev with ST_WEOT\n");
410       dev->dev_errno = ENOSPC;
411       Jmsg(jcr, M_FATAL, 0,  _("Cannot write block. Device at EOM.\n"));
412       return false;
413    }
414    if (!(dev->state & ST_APPEND)) {
415       dev->dev_errno = EIO;
416       Jmsg(jcr, M_FATAL, 0, _("Attempt to write on read-only Volume.\n"));
417       return false;
418    }
419    wlen = block->binbuf;
420    if (wlen <= WRITE_BLKHDR_LENGTH) {  /* Does block have data in it? */
421       Dmsg0(100, "return write_block_to_dev no data to write\n");
422       return true;
423    }
424    /*
425     * Clear to the end of the buffer if it is not full,
426     *  and on tape devices, apply min and fixed blocking.
427     */
428    if (wlen != block->buf_len) {
429       uint32_t blen;                  /* current buffer length */
430
431       Dmsg2(200, "binbuf=%d buf_len=%d\n", block->binbuf, block->buf_len);
432       blen = wlen;
433
434       /* Adjust write size to min/max for tapes only */
435       if (dev->state & ST_TAPE) {
436          /* check for fixed block size */
437          if (dev->min_block_size == dev->max_block_size) {
438             wlen = block->buf_len;    /* fixed block size already rounded */
439          /* Check for min block size */
440          } else if (wlen < dev->min_block_size) {
441             wlen =  ((dev->min_block_size + TAPE_BSIZE - 1) / TAPE_BSIZE) * TAPE_BSIZE;
442          /* Ensure size is rounded */
443          } else {
444             wlen = ((wlen + TAPE_BSIZE - 1) / TAPE_BSIZE) * TAPE_BSIZE;
445          }
446       }
447       if (wlen-blen > 0) {
448          memset(block->bufp, 0, wlen-blen); /* clear garbage */
449       }
450    }
451
452    ser_block_header(block);
453
454    /* Limit maximum Volume size to value specified by user */
455    hit_max1 = (dev->max_volume_size > 0) &&
456        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->max_volume_size;
457    hit_max2 = (dev->VolCatInfo.VolCatMaxBytes > 0) &&
458        ((dev->VolCatInfo.VolCatBytes + block->binbuf)) >= dev->VolCatInfo.VolCatMaxBytes;
459    if (hit_max1 || hit_max2) {
460       char ed1[50];
461       uint64_t max_cap;
462       Dmsg0(10, "==== Output bytes Triggered medium max capacity.\n");
463       if (hit_max1) {
464          max_cap = dev->max_volume_size;
465       } else {
466          max_cap = dev->VolCatInfo.VolCatMaxBytes;
467       }
468       Jmsg(jcr, M_INFO, 0, _("User defined maximum volume capacity %s exceeded on device %s.\n"),
469             edit_uint64_with_commas(max_cap, ed1),  dev->dev_name);
470       terminate_writing_volume(dcr);
471       dev->dev_errno = ENOSPC;
472       return false;
473    }
474
475    /* Limit maximum File size on volume to user specified value */
476    if ((dev->max_file_size > 0) &&
477        (dev->file_size+block->binbuf) >= dev->max_file_size) {
478       dev->file_size = 0;             /* reset file size */
479
480       if (dev->is_tape() && weof_dev(dev, 1) != 0) {            /* write eof */
481          Dmsg0(190, "WEOF error in max file size.\n");
482          terminate_writing_volume(dcr);
483          dev->dev_errno = ENOSPC;
484          return false;
485       }
486
487       /* Create a JobMedia record so restore can seek */
488       if (!dir_create_jobmedia_record(dcr)) {
489          Dmsg0(190, "Error from create_job_media.\n");
490          dev->dev_errno = EIO;
491           Jmsg(jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
492                dcr->VolCatInfo.VolCatName, jcr->Job);
493           terminate_writing_volume(dcr);
494           dev->dev_errno = EIO;
495           return false;
496       }
497       dev->VolCatInfo.VolCatFiles = dev->file;
498       if (!dir_update_volume_info(dcr, false)) {
499          Dmsg0(190, "Error from update_vol_info.\n");
500          terminate_writing_volume(dcr);
501          dev->dev_errno = EIO;
502          return false;
503       }
504       Dmsg0(100, "dir_update_volume_info max file size -- OK\n");
505
506
507       /*
508        * Walk through all attached dcrs setting flag to call
509        * set_new_file_parameters() when that dcr is next used.
510        */
511       DCR *mdcr;
512       foreach_dlist(mdcr, dev->attached_dcrs) {
513          if (mdcr->jcr->JobId == 0) {
514             continue;
515          }
516          mdcr->NewFile = true;        /* set reminder to do set_new_file_params */
517       }
518       /* Set new file/block parameters for current dcr */
519       set_new_file_parameters(dcr);
520    }
521    
522    /* Limit maximum part size to value specified by user (not applicable to tapes/fifos) */
523    if (!(dev->state & (ST_TAPE|ST_FIFO)) && 
524          (dev->max_part_size > 0) &&
525         ((dev->part_size + block->binbuf) >= dev->max_part_size)) {
526       if (dev->part < dev->num_parts) {
527          Jmsg3(dcr->jcr, M_FATAL, 0, _("Error while writing, current part number is less than the total number of parts (%d/%d, device=%s)\n"),
528                dev->part, dev->num_parts, dev_name(dev));
529          dev->dev_errno = EIO;
530          return false;
531       }
532       
533       if (open_next_part(dev) < 0) {
534          Jmsg2(dcr->jcr, M_FATAL, 0, _("Unable to open device next part %s. ERR=%s\n"),
535                 dev_name(dev), strerror_dev(dev));
536          dev->dev_errno = EIO;
537          return false;
538       }
539       
540       dev->VolCatInfo.VolCatParts = dev->num_parts;
541             
542       if (!dir_update_volume_info(dcr, false)) {
543          Dmsg0(190, "Error from update_vol_info.\n");
544          dev->dev_errno = EIO;
545          return false;
546       }
547    }
548    
549    if (dev->free_space_errno < 0) { /* Error while getting free space */
550       char ed1[50], ed2[50];
551       Dmsg1(10, "Cannot get free space on the device ERR=%s.\n", dev->errmsg);
552       Jmsg(jcr, M_FATAL, 0, _("End of Volume \"%s\" at %u:%u on device %s (part_size=%s, free_space=%s, free_space_errno=%d, errmsg=%s).\n"),
553            dev->VolCatInfo.VolCatName,
554            dev->file, dev->block_num, dev->dev_name,
555            edit_uint64_with_commas(dev->part_size, ed1), edit_uint64_with_commas(dev->free_space, ed2),
556            dev->free_space_errno, dev->errmsg);
557       dev->dev_errno = -dev->free_space_errno;
558       return false;
559    }
560    
561    if (((dev->free_space_errno > 0) && ((dev->part_size + block->binbuf) >= dev->free_space))) {
562       char ed1[50], ed2[50];
563       Dmsg0(10, "==== Just enough free space on the device to write the current part...\n");
564       Jmsg(jcr, M_INFO, 0, _("End of Volume \"%s\" at %u:%u on device %s (part_size=%s, free_space=%s, free_space_errno=%d).\n"),
565             dev->VolCatInfo.VolCatName,
566             dev->file, dev->block_num, dev->dev_name,
567             edit_uint64_with_commas(dev->part_size, ed1), edit_uint64_with_commas(dev->free_space, ed2),
568             dev->free_space_errno);
569       terminate_writing_volume(dcr);
570       dev->dev_errno = ENOSPC;
571       return false;
572    }   
573
574    dev->VolCatInfo.VolCatWrites++;
575    Dmsg1(300, "Write block of %u bytes\n", wlen);
576 #ifdef DEBUG_BLOCK_ZEROING
577    uint32_t *bp = (uint32_t *)block->buf;
578    if (bp[0] == 0 && bp[1] == 0 && bp[2] == 0 && block->buf[12] == 0) {
579       Jmsg0(jcr, M_ABORT, 0, "Write block header zeroed.\n");
580    }
581 #endif
582
583    stat = write(dev->fd, block->buf, (size_t)wlen);
584
585 #ifdef DEBUG_BLOCK_ZEROING
586    if (bp[0] == 0 && bp[1] == 0 && bp[2] == 0 && block->buf[12] == 0) {
587       Jmsg0(jcr, M_ABORT, 0, "Write block header zeroed.\n");
588    }
589 #endif
590
591    if (stat != (ssize_t)wlen) {
592       /* Some devices simply report EIO when the volume is full.
593        * With a little more thought we may be able to check
594        * capacity and distinguish real errors and EOT
595        * conditions.  In any case, we probably want to
596        * simulate an End of Medium.
597        */
598       if (stat == -1) {
599          berrno be;
600          clrerror_dev(dev, -1);
601          if (dev->dev_errno == 0) {
602             dev->dev_errno = ENOSPC;        /* out of space */
603          }
604          if (dev->dev_errno != ENOSPC) {
605             Jmsg4(jcr, M_ERROR, 0, _("Write error at %u:%u on device %s. ERR=%s.\n"),
606                dev->file, dev->block_num, dev->dev_name, be.strerror());
607          }
608       } else {
609         dev->dev_errno = ENOSPC;            /* out of space */
610       }
611       if (dev->dev_errno == ENOSPC) {
612          Jmsg(jcr, M_INFO, 0, _("End of Volume \"%s\" at %u:%u on device %s. Write of %u bytes got %d.\n"),
613             dev->VolCatInfo.VolCatName,
614             dev->file, dev->block_num, dev->dev_name, wlen, stat);
615       }
616       Dmsg6(100, "=== Write error. size=%u rtn=%d dev_blk=%d blk_blk=%d errno=%d: ERR=%s\n",
617          wlen, stat, dev->block_num, block->BlockNumber, dev->dev_errno, strerror(dev->dev_errno));
618
619       ok = terminate_writing_volume(dcr);
620       if (!ok && !forge_on) {
621          return false;
622       }
623
624 #define CHECK_LAST_BLOCK
625 #ifdef  CHECK_LAST_BLOCK
626       /*
627        * If the device is a tape and it supports backspace record,
628        *   we backspace over one or two eof marks depending on
629        *   how many we just wrote, then over the last record,
630        *   then re-read it and verify that the block number is
631        *   correct.
632        */
633       if (ok && (dev->state & ST_TAPE) && dev_cap(dev, CAP_BSR)) {
634          /* Now back up over what we wrote and read the last block */
635          if (!bsf_dev(dev, 1)) {
636             ok = false;
637             Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
638          }
639          if (ok && dev_cap(dev, CAP_TWOEOF) && !bsf_dev(dev, 1)) {
640             ok = false;
641             Jmsg(jcr, M_ERROR, 0, _("Backspace file at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
642          }
643          /* Backspace over record */
644          if (ok && !bsr_dev(dev, 1)) {
645             ok = false;
646             Jmsg(jcr, M_ERROR, 0, _("Backspace record at EOT failed. ERR=%s\n"), strerror(dev->dev_errno));
647             /*
648              *  On FreeBSD systems, if the user got here, it is likely that his/her
649              *    tape drive is "frozen".  The correct thing to do is a
650              *    rewind(), but if we do that, higher levels in cleaning up, will
651              *    most likely write the EOS record over the beginning of the
652              *    tape.  The rewind *is* done later in mount.c when another
653              *    tape is requested. Note, the clrerror_dev() call in bsr_dev()
654              *    calls ioctl(MTCERRSTAT), which *should* fix the problem.
655              */
656          }
657          if (ok) {
658             DEV_BLOCK *lblock = new_block(dev);
659             /* Note, this can destroy dev->errmsg */
660             dcr->block = lblock;
661             if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
662                Jmsg(jcr, M_ERROR, 0, _("Re-read last block at EOT failed. ERR=%s"), dev->errmsg);
663             } else {
664                if (lblock->BlockNumber+1 == block->BlockNumber) {
665                   Jmsg(jcr, M_INFO, 0, _("Re-read of last block succeeded.\n"));
666                } else {
667                   Jmsg(jcr, M_ERROR, 0, _(
668 "Re-read of last block failed. Last block=%u Current block=%u.\n"),
669                        lblock->BlockNumber, block->BlockNumber);
670                }
671             }
672             free_block(lblock);
673             dcr->block = block;
674          }
675       }
676 #endif
677       return false;
678    }
679
680    /* We successfully wrote the block, now do housekeeping */
681
682    dev->VolCatInfo.VolCatBytes += block->binbuf;
683    dev->VolCatInfo.VolCatBlocks++;
684    dev->EndBlock = dev->block_num;
685    dev->EndFile  = dev->file;
686    dev->block_num++;
687    block->BlockNumber++;
688
689    /* Update dcr values */
690    if (dev_state(dev, ST_TAPE)) {
691       dcr->EndBlock = dev->EndBlock;
692       dcr->EndFile  = dev->EndFile;
693    } else {
694       /* Save address of start of block just written */
695       dcr->EndBlock = (uint32_t)dev->file_addr;
696       dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
697    }
698    if (dcr->VolFirstIndex == 0 && block->FirstIndex > 0) {
699       dcr->VolFirstIndex = block->FirstIndex;
700    }
701    if (block->LastIndex > 0) {
702       dcr->VolLastIndex = block->LastIndex;
703    }
704    dcr->WroteVol = true;
705    dev->file_addr += wlen;            /* update file address */
706    dev->file_size += wlen;
707    dev->part_size += wlen;
708
709    Dmsg2(300, "write_block: wrote block %d bytes=%d\n", dev->block_num, wlen);
710    empty_block(block);
711    return true;
712 }
713
714 static bool terminate_writing_volume(DCR *dcr)
715 {
716    DEVICE *dev = dcr->dev;
717    bool ok = true;
718
719    /* Create a JobMedia record to indicated end of tape */
720    dev->VolCatInfo.VolCatFiles = dev->file;
721    if (!dir_create_jobmedia_record(dcr)) {
722       Dmsg0(190, "Error from create JobMedia\n");
723       dev->dev_errno = EIO;
724        Jmsg(dcr->jcr, M_FATAL, 0, _("Could not create JobMedia record for Volume=\"%s\" Job=%s\n"),
725             dcr->VolCatInfo.VolCatName, dcr->jcr->Job);
726        ok = false;
727        goto bail_out;
728    }
729    dcr->block->write_failed = true;
730    if (weof_dev(dev, 1) != 0) {         /* end the tape */
731       dev->VolCatInfo.VolCatErrors++;
732       Jmsg(dcr->jcr, M_ERROR, 0, "Error writing final EOF to tape. This tape may not be readable.\n"
733            "%s", dev->errmsg);
734       ok = false;
735       Dmsg0(100, "WEOF error.\n");
736    }
737    dev->VolCatInfo.VolCatFiles = dev->file;
738    
739    if (dev->is_dvd()) { /* Write the current (and last) part. */
740       open_next_part(dev);
741    }
742    
743    if (!dir_update_volume_info(dcr, false)) {
744       ok = false;
745    }
746    Dmsg1(100, "dir_update_volume_info terminate writing -- %s\n", ok?"OK":"ERROR");
747
748
749    /*
750     * Walk through all attached dcrs setting flag to call
751     * set_new_file_parameters() when that dcr is next used.
752     */
753    DCR *mdcr;
754    foreach_dlist(mdcr, dev->attached_dcrs) {
755       if (mdcr->jcr->JobId == 0) {
756          continue;
757       }
758       mdcr->NewFile = true;        /* set reminder to do set_new_file_params */
759    }
760    /* Set new file/block parameters for current dcr */
761    set_new_file_parameters(dcr);
762
763    if (ok && dev_cap(dev, CAP_TWOEOF) && weof_dev(dev, 1) != 0) {  /* end the tape */
764       dev->VolCatInfo.VolCatErrors++;
765       /* This may not be fatal since we already wrote an EOF */
766       Jmsg(dcr->jcr, M_ERROR, 0, "%s", dev->errmsg);
767    }
768 bail_out:
769    dev->state |= (ST_EOF|ST_EOT|ST_WEOT);
770    dev->state &= ~ST_APPEND;          /* make tape read-only */
771    Dmsg1(100, "Leave terminate_writing_volume -- %s\n", ok?"OK":"ERROR");
772    return ok;
773 }
774
775
776 /*
777  * Read block with locking
778  *
779  */
780 bool read_block_from_device(DCR *dcr, bool check_block_numbers)
781 {
782    bool stat;
783    DEVICE *dev = dcr->dev;
784    Dmsg0(200, "Enter read_block_from_device\n");
785    lock_device(dev);
786    stat = read_block_from_dev(dcr, check_block_numbers);
787    unlock_device(dev);
788    Dmsg0(200, "Leave read_block_from_device\n");
789    return stat;
790 }
791
792 /*
793  * Read the next block into the block structure and unserialize
794  *  the block header.  For a file, the block may be partially
795  *  or completely in the current buffer.
796  */
797 bool read_block_from_dev(DCR *dcr, bool check_block_numbers)
798 {
799    ssize_t stat;
800    int looping;
801    uint32_t BlockNumber;
802    int retry;
803    JCR *jcr = dcr->jcr;
804    DEVICE *dev = dcr->dev;
805    DEV_BLOCK *block = dcr->block;
806    
807    if (dev_state(dev, ST_EOT)) {
808       return false;
809    }
810    looping = 0;
811    Dmsg1(200, "Full read() in read_block_from_device() len=%d\n",
812          block->buf_len);
813 reread:
814    if (looping > 1) {
815       dev->dev_errno = EIO;
816       Mmsg1(dev->errmsg, _("Block buffer size looping problem on device %s\n"),
817          dev->dev_name);
818       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
819       block->read_len = 0;
820       return false;
821    }
822    
823    /*Dmsg1(200, "dev->file_size=%u\n",(unsigned int)dev->file_size);
824    Dmsg1(200, "lseek=%u\n",(unsigned int)lseek(dev->fd, 0, SEEK_CUR));
825    Dmsg1(200, "dev->part_start=%u\n",(unsigned int)dev->part_start);
826    Dmsg1(200, "dev->file_size-dev->part_start=%u\n",(unsigned int)dev->file_size-dev->part_start);
827    Dmsg1(200, "dev->part_size=%u\n", (unsigned int)dev->part_size);
828    Dmsg1(200, "dev->part=%u\n", (unsigned int)dev->part);
829    Dmsg1(200, "dev->VolCatInfo.VolCatParts=%u\n", (unsigned int)dev->VolCatInfo.VolCatParts);
830    Dmsg3(200, "Tests : %d %d %d\n", (dev->VolCatInfo.VolCatParts > 0), ((dev->file_size-dev->part_start) == dev->part_size), (dev->part <= dev->VolCatInfo.VolCatParts));*/
831    /* Check for part file end */
832    if ((dev->num_parts > 0) &&
833         ((dev->file_size-dev->part_start) == dev->part_size) && 
834         (dev->part < dev->num_parts)) {
835       if (open_next_part(dev) < 0) {
836          Jmsg2(dcr->jcr, M_FATAL, 0, _("Unable to open device next part %s. ERR=%s\n"),
837                dev_name(dev), strerror_dev(dev));
838          dev->dev_errno = EIO;
839          return false;
840       }
841    }
842    
843    retry = 0;
844    do {
845 //    uint32_t *bp = (uint32_t *)block->buf;
846 //    Dmsg3(000, "Read %p %u at %llu\n", block->buf, block->buf_len, lseek(dev->fd, 0, SEEK_CUR));
847
848       stat = read(dev->fd, block->buf, (size_t)block->buf_len);
849
850 //    Dmsg8(000, "stat=%d Csum=%u blen=%u bnum=%u %c%c%c%c\n",stat, bp[0],bp[1],bp[2],
851 //      block->buf[12],block->buf[13],block->buf[14],block->buf[15]);
852
853       if (retry == 1) {
854          dev->VolCatInfo.VolCatErrors++;
855       }
856    } while (stat == -1 && (errno == EINTR || errno == EIO) && retry++ < 11);
857    if (stat < 0) {
858       berrno be;
859       clrerror_dev(dev, -1);
860       Dmsg1(200, "Read device got: ERR=%s\n", be.strerror());
861       block->read_len = 0;
862       Mmsg4(dev->errmsg, _("Read error at file:blk %u:%u on device %s. ERR=%s.\n"),
863          dev->file, dev->block_num, dev->dev_name, be.strerror());
864       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
865       if (dev->at_eof()) {        /* EOF just seen? */
866          dev->state |= ST_EOT;    /* yes, error => EOT */
867       }
868       return false;
869    }
870    Dmsg3(200, "Read device got %d bytes at %u:%u\n", stat,
871       dev->file, dev->block_num);
872    if (stat == 0) {             /* Got EOF ! */
873       dev->block_num = 0;
874       block->read_len = 0;
875       Mmsg3(dev->errmsg, _("Read zero bytes at %u:%u on device %s.\n"),
876          dev->file, dev->block_num, dev->dev_name);
877       if (dev->at_eof()) {       /* EOF already read? */
878          dev->state |= ST_EOT;  /* yes, 2 EOFs => EOT */
879          return 0;
880       }
881       dev->set_eof();
882       return false;             /* return eof */
883    }
884    /* Continue here for successful read */
885    block->read_len = stat;      /* save length read */
886    if (block->read_len < BLKHDR2_LENGTH) {
887       dev->dev_errno = EIO;
888       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Very short block of %d bytes on device %s discarded.\n"),
889          dev->file, dev->block_num, block->read_len, dev->dev_name);
890       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
891       dev->state |= ST_SHORT;   /* set short block */
892       block->read_len = block->binbuf = 0;
893       return false;             /* return error */
894    }
895
896    BlockNumber = block->BlockNumber + 1;
897    if (!unser_block_header(jcr, dev, block)) {
898       if (forge_on) {
899          dev->file_addr += block->read_len;
900          dev->file_size += block->read_len;
901          goto reread;
902       }
903       return false;
904    }
905
906    /*
907     * If the block is bigger than the buffer, we reposition for
908     *  re-reading the block, allocate a buffer of the correct size,
909     *  and go re-read.
910     */
911    if (block->block_len > block->buf_len) {
912       dev->dev_errno = EIO;
913       Mmsg2(dev->errmsg,  _("Block length %u is greater than buffer %u. Attempting recovery.\n"),
914          block->block_len, block->buf_len);
915       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
916       Pmsg1(000, "%s", dev->errmsg);
917       /* Attempt to reposition to re-read the block */
918       if (dev->state & ST_TAPE) {
919          Dmsg0(200, "BSR for reread; block too big for buffer.\n");
920          if (!bsr_dev(dev, 1)) {
921             Jmsg(jcr, M_ERROR, 0, "%s", strerror_dev(dev));
922             block->read_len = 0;
923             return false;
924          }
925       } else {
926          Dmsg0(200, "Seek to beginning of block for reread.\n");
927          off_t pos = lseek_dev(dev, (off_t)0, SEEK_CUR); /* get curr pos */
928          pos -= block->read_len;
929          lseek_dev(dev, pos, SEEK_SET);
930          dev->file_addr = pos;
931       }
932       Mmsg1(dev->errmsg, _("Setting block buffer size to %u bytes.\n"), block->block_len);
933       Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
934       Pmsg1(000, "%s", dev->errmsg);
935       /* Set new block length */
936       dev->max_block_size = block->block_len;
937       block->buf_len = block->block_len;
938       free_memory(block->buf);
939       block->buf = get_memory(block->buf_len);
940       empty_block(block);
941       looping++;
942       goto reread;                    /* re-read block with correct block size */
943    }
944
945    if (block->block_len > block->read_len) {
946       dev->dev_errno = EIO;
947       Mmsg4(dev->errmsg, _("Volume data error at %u:%u! Short block of %d bytes on device %s discarded.\n"),
948          dev->file, dev->block_num, block->read_len, dev->dev_name);
949       Jmsg(jcr, M_ERROR, 0, "%s", dev->errmsg);
950       dev->state |= ST_SHORT;   /* set short block */
951       block->read_len = block->binbuf = 0;
952       return false;             /* return error */
953    }
954
955    dev->state &= ~(ST_EOF|ST_SHORT); /* clear EOF and short block */
956    dev->VolCatInfo.VolCatReads++;
957    dev->VolCatInfo.VolCatRBytes += block->read_len;
958
959    dev->VolCatInfo.VolCatBytes += block->block_len;
960    dev->VolCatInfo.VolCatBlocks++;
961    dev->EndBlock = dev->block_num;
962    dev->EndFile  = dev->file;
963    dev->block_num++;
964
965    /* Update dcr values */
966    if (dev->state & ST_TAPE) {
967       dcr->EndBlock = dev->EndBlock;
968       dcr->EndFile  = dev->EndFile;
969    } else {
970       dcr->EndBlock = (uint32_t)dev->file_addr;
971       dcr->EndFile = (uint32_t)(dev->file_addr >> 32);
972       dev->block_num = dcr->EndBlock;
973       dev->file = dcr->EndFile;
974    }
975    dev->file_addr += block->block_len;
976    dev->file_size += block->block_len;
977
978    /*
979     * If we read a short block on disk,
980     * seek to beginning of next block. This saves us
981     * from shuffling blocks around in the buffer. Take a
982     * look at this from an efficiency stand point later, but
983     * it should only happen once at the end of each job.
984     *
985     * I've been lseek()ing negative relative to SEEK_CUR for 30
986     *   years now. However, it seems that with the new off_t definition,
987     *   it is not possible to seek negative amounts, so we use two
988     *   lseek(). One to get the position, then the second to do an
989     *   absolute positioning -- so much for efficiency.  KES Sep 02.
990     */
991    Dmsg0(200, "At end of read block\n");
992    if (block->read_len > block->block_len && !dev->is_tape()) {
993       char ed1[50];
994       off_t pos = lseek_dev(dev, (off_t)0, SEEK_CUR); /* get curr pos */
995       pos -= (block->read_len - block->block_len);
996       lseek_dev(dev, pos, SEEK_SET);
997       Dmsg3(200, "Did lseek pos=%s blk_size=%d rdlen=%d\n", 
998          edit_uint64(pos, ed1), block->block_len,
999             block->read_len);
1000       dev->file_addr = pos;
1001       dev->file_size = pos;
1002    }
1003    Dmsg2(200, "Exit read_block read_len=%d block_len=%d\n",
1004       block->read_len, block->block_len);
1005    block->block_read = true;
1006    return true;
1007 }