Imported Upstream version 1.42.13
[platform/upstream/e2fsprogs.git] / lib / ext2fs / mkjournal.c
1 /*
2  * mkjournal.c --- make a journal for a filesystem
3  *
4  * Copyright (C) 2000 Theodore Ts'o.
5  *
6  * %Begin-Header%
7  * This file may be redistributed under the terms of the GNU Library
8  * General Public License, version 2.
9  * %End-Header%
10  */
11
12 #include "config.h"
13 #include <stdio.h>
14 #include <string.h>
15 #if HAVE_UNISTD_H
16 #include <unistd.h>
17 #endif
18 #if HAVE_ERRNO_H
19 #include <errno.h>
20 #endif
21 #include <fcntl.h>
22 #include <time.h>
23 #if HAVE_SYS_STAT_H
24 #include <sys/stat.h>
25 #endif
26 #if HAVE_SYS_TYPES_H
27 #include <sys/types.h>
28 #endif
29 #if HAVE_SYS_IOCTL_H
30 #include <sys/ioctl.h>
31 #endif
32 #if HAVE_NETINET_IN_H
33 #include <netinet/in.h>
34 #endif
35
36 #include "ext2_fs.h"
37 #include "e2p/e2p.h"
38 #include "ext2fs.h"
39 #include "jfs_user.h"
40
41 /*
42  * This function automatically sets up the journal superblock and
43  * returns it as an allocated block.
44  */
45 errcode_t ext2fs_create_journal_superblock(ext2_filsys fs,
46                                            __u32 num_blocks, int flags,
47                                            char  **ret_jsb)
48 {
49         errcode_t               retval;
50         journal_superblock_t    *jsb;
51
52         if (num_blocks < JFS_MIN_JOURNAL_BLOCKS)
53                 return EXT2_ET_JOURNAL_TOO_SMALL;
54
55         if ((retval = ext2fs_get_mem(fs->blocksize, &jsb)))
56                 return retval;
57
58         memset (jsb, 0, fs->blocksize);
59
60         jsb->s_header.h_magic = htonl(JFS_MAGIC_NUMBER);
61         if (flags & EXT2_MKJOURNAL_V1_SUPER)
62                 jsb->s_header.h_blocktype = htonl(JFS_SUPERBLOCK_V1);
63         else
64                 jsb->s_header.h_blocktype = htonl(JFS_SUPERBLOCK_V2);
65         jsb->s_blocksize = htonl(fs->blocksize);
66         jsb->s_maxlen = htonl(num_blocks);
67         jsb->s_nr_users = htonl(1);
68         jsb->s_first = htonl(1);
69         jsb->s_sequence = htonl(1);
70         memcpy(jsb->s_uuid, fs->super->s_uuid, sizeof(fs->super->s_uuid));
71         /*
72          * If we're creating an external journal device, we need to
73          * adjust these fields.
74          */
75         if (fs->super->s_feature_incompat &
76             EXT3_FEATURE_INCOMPAT_JOURNAL_DEV) {
77                 jsb->s_nr_users = 0;
78                 jsb->s_first = htonl(ext2fs_journal_sb_start(fs->blocksize) + 1);
79         }
80
81         *ret_jsb = (char *) jsb;
82         return 0;
83 }
84
85 /*
86  * This function writes a journal using POSIX routines.  It is used
87  * for creating external journals and creating journals on live
88  * filesystems.
89  */
90 static errcode_t write_journal_file(ext2_filsys fs, char *filename,
91                                     blk_t num_blocks, int flags)
92 {
93         errcode_t       retval;
94         char            *buf = 0;
95         int             fd, ret_size;
96         blk_t           i;
97
98         if ((retval = ext2fs_create_journal_superblock(fs, num_blocks, flags,
99                                                        &buf)))
100                 return retval;
101
102         /* Open the device or journal file */
103         if ((fd = open(filename, O_WRONLY)) < 0) {
104                 retval = errno;
105                 goto errfree;
106         }
107
108         /* Write the superblock out */
109         retval = EXT2_ET_SHORT_WRITE;
110         ret_size = write(fd, buf, fs->blocksize);
111         if (ret_size < 0) {
112                 retval = errno;
113                 goto errout;
114         }
115         if (ret_size != (int) fs->blocksize)
116                 goto errout;
117         memset(buf, 0, fs->blocksize);
118
119         if (flags & EXT2_MKJOURNAL_LAZYINIT)
120                 goto success;
121
122         for (i = 1; i < num_blocks; i++) {
123                 ret_size = write(fd, buf, fs->blocksize);
124                 if (ret_size < 0) {
125                         retval = errno;
126                         goto errout;
127                 }
128                 if (ret_size != (int) fs->blocksize)
129                         goto errout;
130         }
131
132 success:
133         retval = 0;
134 errout:
135         close(fd);
136 errfree:
137         ext2fs_free_mem(&buf);
138         return retval;
139 }
140
141 /*
142  * Convenience function which zeros out _num_ blocks starting at
143  * _blk_.  In case of an error, the details of the error is returned
144  * via _ret_blk_ and _ret_count_ if they are non-NULL pointers.
145  * Returns 0 on success, and an error code on an error.
146  *
147  * As a special case, if the first argument is NULL, then it will
148  * attempt to free the static zeroizing buffer.  (This is to keep
149  * programs that check for memory leaks happy.)
150  */
151 #define STRIDE_LENGTH 8
152 errcode_t ext2fs_zero_blocks2(ext2_filsys fs, blk64_t blk, int num,
153                               blk64_t *ret_blk, int *ret_count)
154 {
155         int             j, count;
156         static char     *buf;
157         errcode_t       retval;
158
159         /* If fs is null, clean up the static buffer and return */
160         if (!fs) {
161                 if (buf) {
162                         free(buf);
163                         buf = 0;
164                 }
165                 return 0;
166         }
167         /* Allocate the zeroizing buffer if necessary */
168         if (!buf) {
169                 buf = malloc(fs->blocksize * STRIDE_LENGTH);
170                 if (!buf)
171                         return ENOMEM;
172                 memset(buf, 0, fs->blocksize * STRIDE_LENGTH);
173         }
174         /* OK, do the write loop */
175         j=0;
176         while (j < num) {
177                 if (blk % STRIDE_LENGTH) {
178                         count = STRIDE_LENGTH - (blk % STRIDE_LENGTH);
179                         if (count > (num - j))
180                                 count = num - j;
181                 } else {
182                         count = num - j;
183                         if (count > STRIDE_LENGTH)
184                                 count = STRIDE_LENGTH;
185                 }
186                 retval = io_channel_write_blk64(fs->io, blk, count, buf);
187                 if (retval) {
188                         if (ret_count)
189                                 *ret_count = count;
190                         if (ret_blk)
191                                 *ret_blk = blk;
192                         return retval;
193                 }
194                 j += count; blk += count;
195         }
196         return 0;
197 }
198
199 errcode_t ext2fs_zero_blocks(ext2_filsys fs, blk_t blk, int num,
200                              blk_t *ret_blk, int *ret_count)
201 {
202         blk64_t ret_blk2;
203         errcode_t retval;
204
205         retval = ext2fs_zero_blocks2(fs, blk, num, &ret_blk2, ret_count);
206         if (retval)
207                 *ret_blk = (blk_t) ret_blk2;
208         return retval;
209 }
210
211 /*
212  * Helper function for creating the journal using direct I/O routines
213  */
214 struct mkjournal_struct {
215         int             num_blocks;
216         int             newblocks;
217         blk64_t         goal;
218         blk64_t         blk_to_zero;
219         int             zero_count;
220         int             flags;
221         char            *buf;
222         errcode_t       err;
223 };
224
225 static int mkjournal_proc(ext2_filsys   fs,
226                           blk64_t       *blocknr,
227                           e2_blkcnt_t   blockcnt,
228                           blk64_t       ref_block EXT2FS_ATTR((unused)),
229                           int           ref_offset EXT2FS_ATTR((unused)),
230                           void          *priv_data)
231 {
232         struct mkjournal_struct *es = (struct mkjournal_struct *) priv_data;
233         blk64_t new_blk;
234         errcode_t       retval;
235
236         if (*blocknr) {
237                 es->goal = *blocknr;
238                 return 0;
239         }
240         if (blockcnt &&
241             (EXT2FS_B2C(fs, es->goal) == EXT2FS_B2C(fs, es->goal+1)))
242                 new_blk = es->goal+1;
243         else {
244                 es->goal &= ~EXT2FS_CLUSTER_MASK(fs);
245                 retval = ext2fs_new_block2(fs, es->goal, 0, &new_blk);
246                 if (retval) {
247                         es->err = retval;
248                         return BLOCK_ABORT;
249                 }
250                 ext2fs_block_alloc_stats2(fs, new_blk, +1);
251                 es->newblocks++;
252         }
253         if (blockcnt >= 0)
254                 es->num_blocks--;
255
256         retval = 0;
257         if (blockcnt <= 0)
258                 retval = io_channel_write_blk64(fs->io, new_blk, 1, es->buf);
259         else if (!(es->flags & EXT2_MKJOURNAL_LAZYINIT)) {
260                 if (es->zero_count) {
261                         if ((es->blk_to_zero + es->zero_count == new_blk) &&
262                             (es->zero_count < 1024))
263                                 es->zero_count++;
264                         else {
265                                 retval = ext2fs_zero_blocks2(fs,
266                                                              es->blk_to_zero,
267                                                              es->zero_count,
268                                                              0, 0);
269                                 es->zero_count = 0;
270                         }
271                 }
272                 if (es->zero_count == 0) {
273                         es->blk_to_zero = new_blk;
274                         es->zero_count = 1;
275                 }
276         }
277
278         if (blockcnt == 0)
279                 memset(es->buf, 0, fs->blocksize);
280
281         if (retval) {
282                 es->err = retval;
283                 return BLOCK_ABORT;
284         }
285         *blocknr = es->goal = new_blk;
286
287         if (es->num_blocks == 0)
288                 return (BLOCK_CHANGED | BLOCK_ABORT);
289         else
290                 return BLOCK_CHANGED;
291
292 }
293
294 /*
295  * Calculate the initial goal block to be roughly at the middle of the
296  * filesystem.  Pick a group that has the largest number of free
297  * blocks.
298  */
299 static blk64_t get_midpoint_journal_block(ext2_filsys fs)
300 {
301         dgrp_t  group, start, end, i, log_flex;
302
303         group = ext2fs_group_of_blk2(fs, (ext2fs_blocks_count(fs->super) -
304                                          fs->super->s_first_data_block) / 2);
305         log_flex = 1 << fs->super->s_log_groups_per_flex;
306         if (fs->super->s_log_groups_per_flex && (group > log_flex)) {
307                 group = group & ~(log_flex - 1);
308                 while ((group < fs->group_desc_count) &&
309                        ext2fs_bg_free_blocks_count(fs, group) == 0)
310                         group++;
311                 if (group == fs->group_desc_count)
312                         group = 0;
313                 start = group;
314         } else
315                 start = (group > 0) ? group-1 : group;
316         end = ((group+1) < fs->group_desc_count) ? group+1 : group;
317         group = start;
318         for (i = start + 1; i <= end; i++)
319                 if (ext2fs_bg_free_blocks_count(fs, i) >
320                     ext2fs_bg_free_blocks_count(fs, group))
321                         group = i;
322         return ext2fs_group_first_block2(fs, group);
323 }
324
325 /*
326  * This function creates a journal using direct I/O routines.
327  */
328 static errcode_t write_journal_inode(ext2_filsys fs, ext2_ino_t journal_ino,
329                                      blk_t num_blocks, blk64_t goal, int flags)
330 {
331         char                    *buf;
332         errcode_t               retval;
333         struct ext2_inode       inode;
334         unsigned long long      inode_size;
335         struct mkjournal_struct es;
336
337         if ((retval = ext2fs_create_journal_superblock(fs, num_blocks, flags,
338                                                        &buf)))
339                 return retval;
340
341         if ((retval = ext2fs_read_bitmaps(fs)))
342                 goto out2;
343
344         if ((retval = ext2fs_read_inode(fs, journal_ino, &inode)))
345                 goto out2;
346
347         if (inode.i_blocks > 0) {
348                 retval = EEXIST;
349                 goto out2;
350         }
351
352         es.num_blocks = num_blocks;
353         es.newblocks = 0;
354         es.buf = buf;
355         es.err = 0;
356         es.flags = flags;
357         es.zero_count = 0;
358         es.goal = (goal != ~0ULL) ? goal : get_midpoint_journal_block(fs);
359
360         if (fs->super->s_feature_incompat & EXT3_FEATURE_INCOMPAT_EXTENTS) {
361                 inode.i_flags |= EXT4_EXTENTS_FL;
362                 if ((retval = ext2fs_write_inode(fs, journal_ino, &inode)))
363                         goto out2;
364         }
365
366         retval = ext2fs_block_iterate3(fs, journal_ino, BLOCK_FLAG_APPEND,
367                                        0, mkjournal_proc, &es);
368         if (es.err) {
369                 retval = es.err;
370                 goto errout;
371         }
372         if (es.zero_count) {
373                 retval = ext2fs_zero_blocks2(fs, es.blk_to_zero,
374                                             es.zero_count, 0, 0);
375                 if (retval)
376                         goto errout;
377         }
378
379         if ((retval = ext2fs_read_inode(fs, journal_ino, &inode)))
380                 goto errout;
381
382         inode_size = (unsigned long long)fs->blocksize * num_blocks;
383         ext2fs_iblk_add_blocks(fs, &inode, es.newblocks);
384         inode.i_mtime = inode.i_ctime = fs->now ? fs->now : time(0);
385         inode.i_links_count = 1;
386         inode.i_mode = LINUX_S_IFREG | 0600;
387         retval = ext2fs_inode_size_set(fs, &inode, inode_size);
388         if (retval)
389                 goto errout;
390
391         if ((retval = ext2fs_write_new_inode(fs, journal_ino, &inode)))
392                 goto errout;
393         retval = 0;
394
395         memcpy(fs->super->s_jnl_blocks, inode.i_block, EXT2_N_BLOCKS*4);
396         fs->super->s_jnl_blocks[15] = inode.i_size_high;
397         fs->super->s_jnl_blocks[16] = inode.i_size;
398         fs->super->s_jnl_backup_type = EXT3_JNL_BACKUP_BLOCKS;
399         ext2fs_mark_super_dirty(fs);
400
401 errout:
402         ext2fs_zero_blocks2(0, 0, 0, 0, 0);
403 out2:
404         ext2fs_free_mem(&buf);
405         return retval;
406 }
407
408 /*
409  * Find a reasonable journal file size (in blocks) given the number of blocks
410  * in the filesystem.  For very small filesystems, it is not reasonable to
411  * have a journal that fills more than half of the filesystem.
412  */
413 int ext2fs_default_journal_size(__u64 num_blocks)
414 {
415         if (num_blocks < 2048)
416                 return -1;
417         if (num_blocks < 32768)
418                 return (1024);
419         if (num_blocks < 256*1024)
420                 return (4096);
421         if (num_blocks < 512*1024)
422                 return (8192);
423         if (num_blocks < 1024*1024)
424                 return (16384);
425         return 32768;
426 }
427
428 int ext2fs_journal_sb_start(int blocksize)
429 {
430         if (blocksize == EXT2_MIN_BLOCK_SIZE)
431                 return 2;
432         return 1;
433 }
434
435 /*
436  * This function adds a journal device to a filesystem
437  */
438 errcode_t ext2fs_add_journal_device(ext2_filsys fs, ext2_filsys journal_dev)
439 {
440         struct stat     st;
441         errcode_t       retval;
442         char            buf[SUPERBLOCK_SIZE];
443         journal_superblock_t    *jsb;
444         int             start;
445         __u32           i, nr_users;
446
447         /* Make sure the device exists and is a block device */
448         if (stat(journal_dev->device_name, &st) < 0)
449                 return errno;
450
451         if (!S_ISBLK(st.st_mode))
452                 return EXT2_ET_JOURNAL_NOT_BLOCK; /* Must be a block device */
453
454         /* Get the journal superblock */
455         start = ext2fs_journal_sb_start(journal_dev->blocksize);
456         if ((retval = io_channel_read_blk64(journal_dev->io, start,
457                                             -SUPERBLOCK_SIZE,
458                                             buf)))
459                 return retval;
460
461         jsb = (journal_superblock_t *) buf;
462         if ((jsb->s_header.h_magic != (unsigned) ntohl(JFS_MAGIC_NUMBER)) ||
463             (jsb->s_header.h_blocktype != (unsigned) ntohl(JFS_SUPERBLOCK_V2)))
464                 return EXT2_ET_NO_JOURNAL_SB;
465
466         if (ntohl(jsb->s_blocksize) != (unsigned long) fs->blocksize)
467                 return EXT2_ET_UNEXPECTED_BLOCK_SIZE;
468
469         /* Check and see if this filesystem has already been added */
470         nr_users = ntohl(jsb->s_nr_users);
471         for (i=0; i < nr_users; i++) {
472                 if (memcmp(fs->super->s_uuid,
473                            &jsb->s_users[i*16], 16) == 0)
474                         break;
475         }
476         if (i >= nr_users) {
477                 memcpy(&jsb->s_users[nr_users*16],
478                        fs->super->s_uuid, 16);
479                 jsb->s_nr_users = htonl(nr_users+1);
480         }
481
482         /* Writeback the journal superblock */
483         if ((retval = io_channel_write_blk64(journal_dev->io, start,
484                                             -SUPERBLOCK_SIZE, buf)))
485                 return retval;
486
487         fs->super->s_journal_inum = 0;
488         fs->super->s_journal_dev = st.st_rdev;
489         memcpy(fs->super->s_journal_uuid, jsb->s_uuid,
490                sizeof(fs->super->s_journal_uuid));
491         fs->super->s_feature_compat |= EXT3_FEATURE_COMPAT_HAS_JOURNAL;
492         ext2fs_mark_super_dirty(fs);
493         return 0;
494 }
495
496 /*
497  * This function adds a journal inode to a filesystem, using either
498  * POSIX routines if the filesystem is mounted, or using direct I/O
499  * functions if it is not.
500  */
501 errcode_t ext2fs_add_journal_inode2(ext2_filsys fs, blk_t num_blocks,
502                                     blk64_t goal, int flags)
503 {
504         errcode_t               retval;
505         ext2_ino_t              journal_ino;
506         struct stat             st;
507         char                    jfile[1024];
508         int                     mount_flags;
509         int                     fd = -1;
510
511         if (flags & EXT2_MKJOURNAL_NO_MNT_CHECK)
512                 mount_flags = 0;
513         else if ((retval = ext2fs_check_mount_point(fs->device_name,
514                                                     &mount_flags,
515                                                     jfile, sizeof(jfile)-10)))
516                 return retval;
517
518         if (mount_flags & EXT2_MF_MOUNTED) {
519 #if HAVE_EXT2_IOCTLS
520                 int f = 0;
521 #endif
522                 strcat(jfile, "/.journal");
523
524                 /*
525                  * If .../.journal already exists, make sure any
526                  * immutable or append-only flags are cleared.
527                  */
528 #if defined(HAVE_CHFLAGS) && defined(UF_NODUMP)
529                 (void) chflags (jfile, 0);
530 #else
531 #if HAVE_EXT2_IOCTLS
532                 fd = open(jfile, O_RDONLY);
533                 if (fd >= 0) {
534                         retval = ioctl(fd, EXT2_IOC_SETFLAGS, &f);
535                         close(fd);
536                         if (retval)
537                                 return retval;
538                 }
539 #endif
540 #endif
541
542                 /* Create the journal file */
543                 if ((fd = open(jfile, O_CREAT|O_WRONLY, 0600)) < 0)
544                         return errno;
545
546                 /* Note that we can't do lazy journal initialization for mounted
547                  * filesystems, since the zero writing is also allocating the
548                  * journal blocks.  We could use fallocate, but not all kernels
549                  * support that, and creating a journal on a mounted ext2
550                  * filesystems is extremely rare these days...  Ignore it. */
551                 flags &= ~EXT2_MKJOURNAL_LAZYINIT;
552
553                 if ((retval = write_journal_file(fs, jfile, num_blocks, flags)))
554                         goto errout;
555
556                 /* Get inode number of the journal file */
557                 if (fstat(fd, &st) < 0) {
558                         retval = errno;
559                         goto errout;
560                 }
561
562 #if defined(HAVE_CHFLAGS) && defined(UF_NODUMP)
563                 retval = fchflags (fd, UF_NODUMP|UF_IMMUTABLE);
564 #else
565 #if HAVE_EXT2_IOCTLS
566                 if (ioctl(fd, EXT2_IOC_GETFLAGS, &f) < 0) {
567                         retval = errno;
568                         goto errout;
569                 }
570                 f |= EXT2_NODUMP_FL | EXT2_IMMUTABLE_FL;
571                 retval = ioctl(fd, EXT2_IOC_SETFLAGS, &f);
572 #endif
573 #endif
574                 if (retval) {
575                         retval = errno;
576                         goto errout;
577                 }
578
579                 if (close(fd) < 0) {
580                         retval = errno;
581                         fd = -1;
582                         goto errout;
583                 }
584                 journal_ino = st.st_ino;
585                 memset(fs->super->s_jnl_blocks, 0,
586                        sizeof(fs->super->s_jnl_blocks));
587         } else {
588                 if ((mount_flags & EXT2_MF_BUSY) &&
589                     !(fs->flags & EXT2_FLAG_EXCLUSIVE)) {
590                         retval = EBUSY;
591                         goto errout;
592                 }
593                 journal_ino = EXT2_JOURNAL_INO;
594                 if ((retval = write_journal_inode(fs, journal_ino,
595                                                   num_blocks, goal, flags)))
596                         return retval;
597         }
598
599         fs->super->s_journal_inum = journal_ino;
600         fs->super->s_journal_dev = 0;
601         memset(fs->super->s_journal_uuid, 0,
602                sizeof(fs->super->s_journal_uuid));
603         fs->super->s_feature_compat |= EXT3_FEATURE_COMPAT_HAS_JOURNAL;
604
605         ext2fs_mark_super_dirty(fs);
606         return 0;
607 errout:
608         if (fd >= 0)
609                 close(fd);
610         return retval;
611 }
612
613 errcode_t ext2fs_add_journal_inode(ext2_filsys fs, blk_t num_blocks, int flags)
614 {
615         return ext2fs_add_journal_inode2(fs, num_blocks, ~0ULL, flags);
616 }
617
618
619 #ifdef DEBUG
620 main(int argc, char **argv)
621 {
622         errcode_t       retval;
623         char            *device_name;
624         ext2_filsys     fs;
625
626         if (argc < 2) {
627                 fprintf(stderr, "Usage: %s filesystem\n", argv[0]);
628                 exit(1);
629         }
630         device_name = argv[1];
631
632         retval = ext2fs_open (device_name, EXT2_FLAG_RW, 0, 0,
633                               unix_io_manager, &fs);
634         if (retval) {
635                 com_err(argv[0], retval, "while opening %s", device_name);
636                 exit(1);
637         }
638
639         retval = ext2fs_add_journal_inode(fs, JFS_MIN_JOURNAL_BLOCKS, 0);
640         if (retval) {
641                 com_err(argv[0], retval, "while adding journal to %s",
642                         device_name);
643                 exit(1);
644         }
645         retval = ext2fs_flush(fs);
646         if (retval) {
647                 printf("Warning, had trouble writing out superblocks.\n");
648         }
649         ext2fs_close_free(&fs);
650         exit(0);
651
652 }
653 #endif