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