Whamcloud - gitweb
LU-17705 ptlrpc: replace synchronize_rcu() with rcu_barrier()
[fs/lustre-release.git] / lustre / utils / lhsmtool_posix.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.htm
19  *
20  * GPL HEADER END
21  */
22 /*
23  * (C) Copyright 2012 Commissariat a l'energie atomique et aux energies
24  *     alternatives
25  *
26  * Copyright (c) 2013, 2016, Intel Corporation.
27  */
28 /* HSM copytool program for POSIX filesystem-based HSM's.
29  *
30  * An HSM copytool daemon acts on action requests from Lustre to copy files
31  * to and from an HSM archive system. This one in particular makes regular
32  * POSIX filesystem calls to a given path, where an HSM is presumably mounted.
33  *
34  * This particular tool can also import an existing HSM archive.
35  */
36
37 #ifndef _GNU_SOURCE
38 #define _GNU_SOURCE
39 #endif
40 #include <ctype.h>
41 #include <fcntl.h>
42 #include <stdio.h>
43 #include <stdint.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <dirent.h>
47 #include <errno.h>
48 #include <getopt.h>
49 #include <pthread.h>
50 #include <time.h>
51 #include <unistd.h>
52 #include <utime.h>
53 #include <signal.h>
54 #include <sys/time.h>
55 #include <sys/xattr.h>
56 #include <sys/syscall.h>
57 #include <sys/types.h>
58
59 #include <libcfs/util/string.h>
60 #include <linux/lustre/lustre_fid.h>
61 #include <lustre/lustreapi.h>
62 #include "lstddef.h"
63
64 /* Progress reporting period */
65 #define REPORT_INTERVAL_DEFAULT 30
66 /* HSM hash subdir permissions */
67 #define DIR_PERM S_IRWXU
68 /* HSM hash file permissions */
69 #define FILE_PERM (S_IRUSR | S_IWUSR)
70
71 #define ONE_MB 0x100000
72
73 #ifndef NSEC_PER_SEC
74 # define NSEC_PER_SEC 1000000000UL
75 #endif
76
77 enum ct_action {
78         CA_IMPORT = 1,
79         CA_REBIND,
80         CA_MAXSEQ,
81 };
82
83 struct options {
84         int                      o_copy_attrs;
85         int                      o_daemonize;
86         int                      o_dry_run;
87         int                      o_abort_on_error;
88         int                      o_shadow_tree;
89         int                      o_verbose;
90         int                      o_copy_xattrs;
91         int                      o_archive_id_used;
92         int                      o_archive_id_cnt;
93         int                     *o_archive_id;
94         int                      o_report_int;
95         unsigned long long       o_bandwidth;
96         size_t                   o_chunk_size;
97         enum ct_action           o_action;
98         char                    *o_event_fifo;
99         char                    *o_mnt;
100         int                      o_mnt_fd;
101         char                    *o_hsm_root;
102         char                    *o_src; /* for import, or rebind */
103         char                    *o_dst; /* for import, or rebind */
104 };
105
106 /* everything else is zeroed */
107 struct options opt = {
108         .o_copy_attrs = 1,
109         .o_shadow_tree = 1,
110         .o_verbose = LLAPI_MSG_INFO,
111         .o_copy_xattrs = 1,
112         .o_report_int = REPORT_INTERVAL_DEFAULT,
113         .o_chunk_size = ONE_MB,
114 };
115
116 /* hsm_copytool_private will hold an open FD on the lustre mount point
117  * for us. Additionally open one on the archive FS root to make sure
118  * it doesn't drop out from under us (and remind the admin to shutdown
119  * the copytool before unmounting). */
120
121 static int arc_fd = -1;
122
123 static int err_major;
124 static int err_minor;
125
126 static char cmd_name[PATH_MAX];
127 static char fs_name[MAX_OBD_NAME + 1];
128
129 static struct hsm_copytool_private *ctdata;
130
131 static inline double ct_now(void)
132 {
133         struct timeval tv;
134
135         gettimeofday(&tv, NULL);
136
137         return tv.tv_sec + 0.000001 * tv.tv_usec;
138 }
139
140 #define CT_ERROR(_rc, _format, ...)                                     \
141         llapi_error(LLAPI_MSG_ERROR, _rc,                               \
142                     "%f %s[%ld]: "_format,                              \
143                     ct_now(), cmd_name, syscall(SYS_gettid), ## __VA_ARGS__)
144
145 #define CT_DEBUG(_format, ...)                                          \
146         llapi_error(LLAPI_MSG_DEBUG | LLAPI_MSG_NO_ERRNO, 0,            \
147                     "%f %s[%ld]: "_format,                              \
148                     ct_now(), cmd_name, syscall(SYS_gettid), ## __VA_ARGS__)
149
150 #define CT_WARN(_format, ...) \
151         llapi_error(LLAPI_MSG_WARN | LLAPI_MSG_NO_ERRNO, 0,             \
152                     "%f %s[%ld]: "_format,                              \
153                     ct_now(), cmd_name, syscall(SYS_gettid), ## __VA_ARGS__)
154
155 #define CT_TRACE(_format, ...)                                          \
156         llapi_error(LLAPI_MSG_INFO | LLAPI_MSG_NO_ERRNO, 0,             \
157                     "%f %s[%ld]: "_format,                              \
158                     ct_now(), cmd_name, syscall(SYS_gettid), ## __VA_ARGS__)
159
160 static void usage(const char *name, int rc)
161 {
162         fprintf(stdout,
163         " Usage: %s [options]... <mode> <lustre_mount_point>\n"
164         "The Lustre HSM Posix copy tool can be used as a daemon or "
165         "as a command line tool\n"
166         "The Lustre HSM daemon acts on action requests from Lustre\n"
167         "to copy files to and from an HSM archive system.\n"
168         "This POSIX-flavored daemon makes regular POSIX filesystem calls\n"
169         "to an HSM mounted at a given hsm_root.\n"
170         "   --daemon            Daemon mode, run in background\n"
171         " Options:\n"
172         "   --no-attr           Don't copy file attributes\n"
173         "   --no-shadow         Don't create shadow namespace in archive\n"
174         "   --no-xattr          Don't copy file extended attributes\n"
175         "The Lustre HSM tool performs administrator-type actions\n"
176         "on a Lustre HSM archive.\n"
177         "This POSIX-flavored tool can link an existing HSM namespace\n"
178         "into a Lustre filesystem.\n"
179         " Usage:\n"
180         "   %s [options] --import <src> <dst> <lustre_mount_point>\n"
181         "      import an archived subtree from\n"
182         "       <src> (FID or relative path to hsm_root) into the Lustre\n"
183         "             filesystem at\n"
184         "       <dst> (absolute path)\n"
185         "   %s [options] --rebind <old_FID> <new_FID> <lustre_mount_point>\n"
186         "      rebind an entry in the HSM to a new FID\n"
187         "       <old_FID> old FID the HSM entry is bound to\n"
188         "       <new_FID> new FID to bind the HSM entry to\n"
189         "   %s [options] --rebind <list_file> <lustre_mount_point>\n"
190         "      perform the rebind operation for all FID in the list file\n"
191         "       each line of <list_file> consists of <old_FID> <new_FID>\n"
192         "   %s [options] --max-sequence <fsname>\n"
193         "       return the max fid sequence of archived files\n"
194         "   --abort-on-error          Abort operation on major error\n"
195         "   -A, --archive <#>         Archive number (repeatable)\n"
196         "   -b, --bandwidth <bw>      Limit I/O bandwidth (unit can be used\n,"
197         "                             default is MB)\n"
198         "   --dry-run                 Don't run, just show what would be done\n"
199         "   -c, --chunk-size <sz>     I/O size used during data copy\n"
200         "                             (unit can be used, default is MB)\n"
201         "   -f, --event-fifo <path>   Write events stream to fifo\n"
202         "   -p, --hsm-root <path>     Target HSM mount point\n"
203         "   -q, --quiet               Produce less verbose output\n"
204         "   -u, --update-interval <s> Interval between progress reports sent\n"
205         "                             to Coordinator\n"
206         "   -v, --verbose             Produce more verbose output\n",
207         cmd_name, cmd_name, cmd_name, cmd_name, cmd_name);
208
209         exit(rc);
210 }
211
212 static int ct_parseopts(int argc, char * const *argv)
213 {
214         struct option long_opts[] = {
215         { .val = 1,     .name = "abort-on-error",
216           .flag = &opt.o_abort_on_error,        .has_arg = no_argument },
217         { .val = 1,     .name = "abort_on_error",
218           .flag = &opt.o_abort_on_error,        .has_arg = no_argument },
219         { .val = 'A',   .name = "archive",      .has_arg = required_argument },
220         { .val = 'b',   .name = "bandwidth",    .has_arg = required_argument },
221         { .val = 'c',   .name = "chunk-size",   .has_arg = required_argument },
222         { .val = 'c',   .name = "chunk_size",   .has_arg = required_argument },
223         { .val = 1,     .name = "daemon",       .has_arg = no_argument,
224           .flag = &opt.o_daemonize },
225         { .val = 'f',   .name = "event-fifo",   .has_arg = required_argument },
226         { .val = 'f',   .name = "event_fifo",   .has_arg = required_argument },
227         { .val = 1,     .name = "dry-run",      .has_arg = no_argument,
228           .flag = &opt.o_dry_run },
229         { .val = 'h',   .name = "help",         .has_arg = no_argument },
230         { .val = 'i',   .name = "import",       .has_arg = no_argument },
231         { .val = 'M',   .name = "max-sequence", .has_arg = no_argument },
232         { .val = 'M',   .name = "max_sequence", .has_arg = no_argument },
233         { .val = 0,     .name = "no-attr",      .has_arg = no_argument,
234           .flag = &opt.o_copy_attrs },
235         { .val = 0,     .name = "no_attr",      .has_arg = no_argument,
236           .flag = &opt.o_copy_attrs },
237         { .val = 0,     .name = "no-shadow",    .has_arg = no_argument,
238           .flag = &opt.o_shadow_tree },
239         { .val = 0,     .name = "no_shadow",    .has_arg = no_argument,
240           .flag = &opt.o_shadow_tree },
241         { .val = 0,     .name = "no-xattr",     .has_arg = no_argument,
242           .flag = &opt.o_copy_xattrs },
243         { .val = 0,     .name = "no_xattr",     .has_arg = no_argument,
244           .flag = &opt.o_copy_xattrs },
245         { .val = 'p',   .name = "hsm-root",     .has_arg = required_argument },
246         { .val = 'p',   .name = "hsm_root",     .has_arg = required_argument },
247         { .val = 'q',   .name = "quiet",        .has_arg = no_argument },
248         { .val = 'r',   .name = "rebind",       .has_arg = no_argument },
249         { .val = 'u',   .name = "update-interval",
250                                                 .has_arg = required_argument },
251         { .val = 'u',   .name = "update_interval",
252                                                 .has_arg = required_argument },
253         { .val = 'v',   .name = "verbose",      .has_arg = no_argument },
254         { .name = NULL } };
255         unsigned long long value;
256         unsigned long long unit;
257         bool all_id = false;
258         int c, rc;
259         int i;
260
261         optind = 0;
262
263         opt.o_archive_id_cnt = LL_HSM_ORIGIN_MAX_ARCHIVE;
264         opt.o_archive_id = malloc(opt.o_archive_id_cnt *
265                                   sizeof(*opt.o_archive_id));
266         if (opt.o_archive_id == NULL)
267                 return -ENOMEM;
268 repeat:
269         while ((c = getopt_long(argc, argv, "A:b:c:f:hiMp:qru:v",
270                                 long_opts, NULL)) != -1) {
271                 switch (c) {
272                 case 'A': {
273                         char *end = NULL;
274                         int val = strtol(optarg, &end, 10);
275
276                         if (*end != '\0') {
277                                 rc = -EINVAL;
278                                 CT_ERROR(rc, "invalid archive-id: '%s'",
279                                          optarg);
280                                 return rc;
281                         }
282                         /* if archiveID is zero, any archiveID is accepted */
283                         if (all_id == true)
284                                 goto repeat;
285
286                         if (val == 0) {
287                                 free(opt.o_archive_id);
288                                 opt.o_archive_id = NULL;
289                                 opt.o_archive_id_cnt = 0;
290                                 opt.o_archive_id_used = 0;
291                                 all_id = true;
292                                 CT_WARN("archive-id = 0 is found, any backend will be served\n");
293                                 goto repeat;
294                         }
295
296                         /* skip the duplicated id */
297                         for (i = 0; i < opt.o_archive_id_used; i++) {
298                                 if (opt.o_archive_id[i] == val)
299                                         goto repeat;
300                         }
301                         /* extend the space */
302                         if (opt.o_archive_id_used >= opt.o_archive_id_cnt) {
303                                 int *tmp;
304
305                                 opt.o_archive_id_cnt *= 2;
306                                 tmp = realloc(opt.o_archive_id,
307                                               sizeof(*opt.o_archive_id) *
308                                               opt.o_archive_id_cnt);
309                                 if (tmp == NULL)
310                                         return -ENOMEM;
311
312                                 opt.o_archive_id = tmp;
313                         }
314
315                         opt.o_archive_id[opt.o_archive_id_used++] = val;
316                         break;
317                 }
318                 case 'b': /* -b and -c have both a number with unit as arg */
319                 case 'c':
320                         unit = ONE_MB;
321                         if (llapi_parse_size(optarg, &value, &unit, 0) < 0) {
322                                 rc = -EINVAL;
323                                 CT_ERROR(rc, "bad value for -%c '%s'", c,
324                                          optarg);
325                                 return rc;
326                         }
327                         if (c == 'c')
328                                 opt.o_chunk_size = value;
329                         else
330                                 opt.o_bandwidth = value;
331                         break;
332                 case 'f':
333                         opt.o_event_fifo = optarg;
334                         break;
335                 case 'h':
336                         usage(argv[0], 0);
337                 case 'i':
338                         opt.o_action = CA_IMPORT;
339                         break;
340                 case 'M':
341                         opt.o_action = CA_MAXSEQ;
342                         break;
343                 case 'p':
344                         opt.o_hsm_root = optarg;
345                         break;
346                 case 'q':
347                         opt.o_verbose--;
348                         break;
349                 case 'r':
350                         opt.o_action = CA_REBIND;
351                         break;
352                 case 'u':
353                         opt.o_report_int = atoi(optarg);
354                         if (opt.o_report_int < 0) {
355                                 rc = -EINVAL;
356                                 CT_ERROR(rc, "bad value for -%c '%s'", c,
357                                          optarg);
358                                 return rc;
359                         }
360                         break;
361                 case 'v':
362                         opt.o_verbose++;
363                         break;
364                 case 0:
365                         break;
366                 default:
367                         return -EINVAL;
368                 }
369         }
370
371         switch (opt.o_action) {
372         case CA_IMPORT:
373                 /* src dst mount_point */
374                 if (argc != optind + 3) {
375                         rc = -EINVAL;
376                         CT_ERROR(rc, "--import requires 2 arguments");
377                         return rc;
378                 }
379                 opt.o_src = argv[optind++];
380                 opt.o_dst = argv[optind++];
381                 break;
382         case CA_REBIND:
383                 /* FID1 FID2 mount_point or FILE mount_point */
384                 if (argc == optind + 2) {
385                         opt.o_src = argv[optind++];
386                         opt.o_dst = NULL;
387                 } else if (argc == optind + 3) {
388                         opt.o_src = argv[optind++];
389                         opt.o_dst = argv[optind++];
390                 } else {
391                         rc = -EINVAL;
392                         CT_ERROR(rc, "--rebind requires 1 or 2 arguments");
393                         return rc;
394                 }
395                 break;
396         case CA_MAXSEQ:
397         default:
398                 /* just mount point */
399                 break;
400         }
401
402         if (argc != optind + 1) {
403                 rc = -EINVAL;
404                 CT_ERROR(rc, "no mount point specified");
405                 return rc;
406         }
407
408         opt.o_mnt = argv[optind];
409         opt.o_mnt_fd = -1;
410
411         CT_TRACE("action=%d src=%s dst=%s mount_point=%s",
412                  opt.o_action, opt.o_src, opt.o_dst, opt.o_mnt);
413
414         if (opt.o_hsm_root == NULL) {
415                 rc = -EINVAL;
416                 CT_ERROR(rc, "must specify a root directory for the backend");
417                 return rc;
418         }
419
420         if (opt.o_action == CA_IMPORT) {
421                 if (opt.o_src && opt.o_src[0] == '/') {
422                         rc = -EINVAL;
423                         CT_ERROR(rc,
424                                  "source path must be relative to HSM root");
425                         return rc;
426                 }
427
428                 if (opt.o_dst && opt.o_dst[0] != '/') {
429                         rc = -EINVAL;
430                         CT_ERROR(rc, "destination path must be absolute");
431                         return rc;
432                 }
433         }
434
435         return 0;
436 }
437
438 /* mkdir -p path */
439 static int ct_mkdir_p(const char *path)
440 {
441         char    *saved, *ptr;
442         int      rc;
443
444         ptr = strdup(path);
445         if (ptr == NULL)
446                 return -errno;
447
448         saved = ptr;
449         while (*ptr == '/')
450                 ptr++;
451
452         while ((ptr = strchr(ptr, '/')) != NULL) {
453                 *ptr = '\0';
454                 rc = mkdir(saved, DIR_PERM);
455                 *ptr = '/';
456                 if (rc < 0 && errno != EEXIST) {
457                         rc = -errno;
458                         CT_ERROR(rc, "cannot mkdir '%s'", path);
459                         free(saved);
460                         return rc;
461                 }
462                 ptr++;
463         }
464
465         free(saved);
466
467         return 0;
468 }
469
470 static int ct_save_stripe(int src_fd, const char *src, const char *dst)
471 {
472         char                     lov_file[PATH_MAX + 8];
473         char                     lov_buf[XATTR_SIZE_MAX];
474         struct lov_user_md      *lum;
475         int                      rc;
476         int                      fd;
477         ssize_t                  xattr_size;
478
479         snprintf(lov_file, sizeof(lov_file), "%s.lov", dst);
480         CT_TRACE("saving stripe info of '%s' in %s", src, lov_file);
481
482         xattr_size = fgetxattr(src_fd, XATTR_LUSTRE_LOV, lov_buf,
483                                sizeof(lov_buf));
484         if (xattr_size < 0) {
485                 rc = -errno;
486                 CT_ERROR(rc, "cannot get stripe info on '%s'", src);
487                 return rc;
488         }
489
490         lum = (struct lov_user_md *)lov_buf;
491
492         if (lum->lmm_magic == LOV_USER_MAGIC_V1 ||
493             lum->lmm_magic == LOV_USER_MAGIC_V3) {
494                 /* Set stripe_offset to -1 so that it is not interpreted as a
495                  * hint on restore. */
496                 lum->lmm_stripe_offset = -1;
497         }
498
499         fd = open(lov_file, O_TRUNC | O_CREAT | O_WRONLY, FILE_PERM);
500         if (fd < 0) {
501                 rc = -errno;
502                 CT_ERROR(rc, "cannot open '%s'", lov_file);
503                 goto err_cleanup;
504         }
505
506         rc = write(fd, lum, xattr_size);
507         if (rc < 0) {
508                 rc = -errno;
509                 CT_ERROR(rc, "cannot write %zd bytes to '%s'",
510                          xattr_size, lov_file);
511                 close(fd);
512                 goto err_cleanup;
513         }
514
515         rc = close(fd);
516         if (rc < 0) {
517                 rc = -errno;
518                 CT_ERROR(rc, "cannot close '%s'", lov_file);
519                 goto err_cleanup;
520         }
521
522         return 0;
523
524 err_cleanup:
525         unlink(lov_file);
526
527         return rc;
528 }
529
530 static int ct_load_stripe(const char *src, void *lovea, size_t *lovea_size)
531 {
532         char     lov_file[PATH_MAX + 4];
533         int      rc;
534         int      fd;
535
536         snprintf(lov_file, sizeof(lov_file), "%s.lov", src);
537         CT_TRACE("reading stripe rules from '%s' for '%s'", lov_file, src);
538
539         fd = open(lov_file, O_RDONLY);
540         if (fd < 0) {
541                 CT_ERROR(errno, "cannot open '%s'", lov_file);
542                 return -ENODATA;
543         }
544
545         rc = read(fd, lovea, *lovea_size);
546         if (rc < 0) {
547                 CT_ERROR(errno, "cannot read %zu bytes from '%s'",
548                          *lovea_size, lov_file);
549                 close(fd);
550                 return -ENODATA;
551         }
552
553         *lovea_size = rc;
554         close(fd);
555
556         return 0;
557 }
558
559 static int ct_restore_stripe(const char *src, const char *dst, int dst_fd,
560                              const void *lovea, size_t lovea_size)
561 {
562         int     rc;
563
564         rc = fsetxattr(dst_fd, XATTR_LUSTRE_LOV, lovea, lovea_size,
565                        XATTR_CREATE);
566         if (rc < 0) {
567                 rc = -errno;
568                 CT_ERROR(rc, "cannot set lov EA on '%s'", dst);
569         }
570
571         return rc;
572 }
573
574 static int ct_copy_data(struct hsm_copyaction_private *hcp, const char *src,
575                         const char *dst, int src_fd, int dst_fd,
576                         const struct hsm_action_item *hai, long hal_flags)
577 {
578         struct hsm_extent        he;
579         __u64                    offset = hai->hai_extent.offset;
580         struct stat              src_st;
581         struct stat              dst_st;
582         char                    *buf = NULL;
583         __u64                    write_total = 0;
584         __u64                    length = hai->hai_extent.length;
585         time_t                   last_report_time;
586         int                      rc = 0;
587         double                   start_ct_now = ct_now();
588         /* Bandwidth Control */
589         time_t                  start_time;
590         time_t                  now;
591         time_t                  last_bw_print;
592
593         if (fstat(src_fd, &src_st) < 0) {
594                 rc = -errno;
595                 CT_ERROR(rc, "cannot stat '%s'", src);
596                 return rc;
597         }
598
599         if (!S_ISREG(src_st.st_mode)) {
600                 rc = -EINVAL;
601                 CT_ERROR(rc, "'%s' is not a regular file", src);
602                 return rc;
603         }
604
605         if (hai->hai_extent.offset > (__u64)src_st.st_size) {
606                 rc = -EINVAL;
607                 CT_ERROR(rc, "Trying to start reading past end (%ju > "
608                          "%jd) of '%s' source file",
609                          (uintmax_t)hai->hai_extent.offset,
610                          (intmax_t)src_st.st_size, src);
611                 return rc;
612         }
613
614         if (fstat(dst_fd, &dst_st) < 0) {
615                 rc = -errno;
616                 CT_ERROR(rc, "cannot stat '%s'", dst);
617                 return rc;
618         }
619
620         if (!S_ISREG(dst_st.st_mode)) {
621                 rc = -EINVAL;
622                 CT_ERROR(rc, "'%s' is not a regular file", dst);
623                 return rc;
624         }
625
626         /* Don't read beyond a given extent */
627         if (length > src_st.st_size - hai->hai_extent.offset)
628                 length = src_st.st_size - hai->hai_extent.offset;
629
630         start_time = last_bw_print = last_report_time = time(NULL);
631
632         he.offset = offset;
633         he.length = 0;
634         rc = llapi_hsm_action_progress(hcp, &he, length, 0);
635         if (rc < 0) {
636                 /* Action has been canceled or something wrong
637                  * is happening. Stop copying data. */
638                 CT_ERROR(rc, "progress ioctl for copy '%s'->'%s' failed",
639                          src, dst);
640                 goto out;
641         }
642
643         errno = 0;
644
645         buf = malloc(opt.o_chunk_size);
646         if (buf == NULL) {
647                 rc = -ENOMEM;
648                 goto out;
649         }
650
651         CT_TRACE("start copy of %ju bytes from '%s' to '%s'",
652                  (uintmax_t)length, src, dst);
653
654         while (write_total < length) {
655                 ssize_t rsize;
656                 ssize_t wsize;
657                 int     chunk = (length - write_total > opt.o_chunk_size) ?
658                                  opt.o_chunk_size : length - write_total;
659
660                 /* Try the accelerated copy path first. Once LU-10180 lands
661                  * we should deal with holes.
662                  */
663                 wsize = copy_file_range(src_fd, NULL, dst_fd, NULL,
664                                         chunk, 0);
665                 if (wsize != -1)
666                         goto fini_fastcopy;
667                 rc = -errno;
668                 /* Before Linux kernel 5.3 copy_file_range only supported
669                  * file copies between filesystems of the same type. In
670                  * that case copy_file_range() will return -EXDEV.
671                  */
672                 if (rc != -EXDEV && rc != -ENOSYS) {
673                         CT_ERROR(rc, "copy_file_range failed for '%s' to '%s'",
674                                  src, dst);
675                         break;
676                 }
677
678                 /* copy_file_range is not avalible or failed
679                  * so use what works.
680                  */
681                 rsize = pread(src_fd, buf, chunk, offset);
682                 if (rsize == 0)
683                         /* EOF */
684                         break;
685
686                 if (rsize < 0) {
687                         rc = -errno;
688                         CT_ERROR(rc, "cannot read from '%s'", src);
689                         break;
690                 }
691
692                 wsize = pwrite(dst_fd, buf, rsize, offset);
693                 if (wsize < 0) {
694                         rc = -errno;
695                         CT_ERROR(rc, "cannot write to '%s'", dst);
696                         break;
697                 }
698 fini_fastcopy:
699                 write_total += wsize;
700                 offset += wsize;
701
702                 now = time(NULL);
703                 /* sleep if needed, to honor bandwidth limits */
704                 if (opt.o_bandwidth != 0) {
705                         unsigned long long write_theory;
706
707                         write_theory = (now - start_time) * opt.o_bandwidth;
708
709                         if (write_theory < write_total) {
710                                 unsigned long long      excess;
711                                 struct timespec         delay;
712
713                                 excess = write_total - write_theory;
714
715                                 delay.tv_sec = excess / opt.o_bandwidth;
716                                 delay.tv_nsec = (excess % opt.o_bandwidth) *
717                                         NSEC_PER_SEC / opt.o_bandwidth;
718
719                                 if (now >= last_bw_print + opt.o_report_int) {
720                                         CT_TRACE("bandwith control: %lluB/s "
721                                                  "excess=%llu sleep for "
722                                                  "%lld.%09lds",
723                                                  (unsigned long long)opt.o_bandwidth,
724                                                  (unsigned long long)excess,
725                                                  (long long)delay.tv_sec,
726                                                  delay.tv_nsec);
727                                         last_bw_print = now;
728                                 }
729
730                                 do {
731                                         rc = nanosleep(&delay, &delay);
732                                 } while (rc < 0 && errno == EINTR);
733                                 if (rc < 0) {
734                                         CT_ERROR(errno, "delay for bandwidth "
735                                                  "control failed to sleep: "
736                                                  "residual=%lld.%09lds",
737                                                  (long long)delay.tv_sec,
738                                                  delay.tv_nsec);
739                                         rc = 0;
740                                 }
741                         }
742                 }
743
744                 now = time(NULL);
745                 if (now >= last_report_time + opt.o_report_int) {
746                         last_report_time = now;
747                         CT_TRACE("%%%ju ", (uintmax_t)(100 * write_total / length));
748                         /* only give the length of the write since the last
749                          * progress report */
750                         he.length = offset - he.offset;
751                         rc = llapi_hsm_action_progress(hcp, &he, length, 0);
752                         if (rc < 0) {
753                                 /* Action has been canceled or something wrong
754                                  * is happening. Stop copying data. */
755                                 CT_ERROR(rc, "progress ioctl for copy"
756                                          " '%s'->'%s' failed", src, dst);
757                                 goto out;
758                         }
759                         he.offset = offset;
760                 }
761                 rc = 0;
762         }
763
764 out:
765         /*
766          * truncate restored file
767          * size is taken from the archive this is done to support
768          * restore after a force release which leaves the file with the
769          * wrong size (can big bigger than the new size)
770          */
771         if ((hai->hai_action == HSMA_RESTORE) &&
772             (src_st.st_size < dst_st.st_size)) {
773                 /*
774                  * make sure the file is on disk before reporting success.
775                  */
776                 rc = ftruncate(dst_fd, src_st.st_size);
777                 if (rc < 0) {
778                         rc = -errno;
779                         CT_ERROR(rc, "cannot truncate '%s' to size %jd",
780                                  dst, (intmax_t)src_st.st_size);
781                         err_major++;
782                 }
783         }
784
785         if (buf != NULL)
786                 free(buf);
787
788         CT_TRACE("copied %ju bytes in %f seconds",
789                  (uintmax_t)length, ct_now() - start_ct_now);
790
791         return rc;
792 }
793
794 /* Copy file attributes from file src to file dest */
795 static int ct_copy_attr(const char *src, const char *dst, int src_fd,
796                         int dst_fd)
797 {
798         struct stat     st;
799         struct timeval  times[2];
800         int             rc;
801
802         if (fstat(src_fd, &st) < 0) {
803                 rc = -errno;
804                 CT_ERROR(rc, "cannot stat '%s'", src);
805                 return rc;
806         }
807
808         times[0].tv_sec = st.st_atime;
809         times[0].tv_usec = 0;
810         times[1].tv_sec = st.st_mtime;
811         times[1].tv_usec = 0;
812         if (fchmod(dst_fd, st.st_mode) < 0 ||
813             fchown(dst_fd, st.st_uid, st.st_gid) < 0 ||
814             futimes(dst_fd, times) < 0) {
815                 rc = -errno;
816                 CT_ERROR(rc, "cannot set attributes of '%s'", src);
817                 return rc;
818         }
819
820         return 0;
821 }
822
823 static int ct_copy_xattr(const char *src, const char *dst, int src_fd,
824                          int dst_fd, bool is_restore)
825 {
826         char     list[XATTR_LIST_MAX];
827         char     value[XATTR_SIZE_MAX];
828         char    *name;
829         ssize_t  list_len;
830         int      rc;
831
832         list_len = flistxattr(src_fd, list, sizeof(list));
833         if (list_len < 0)
834                 return -errno;
835
836         name = list;
837         while (name < list + list_len) {
838                 rc = fgetxattr(src_fd, name, value, sizeof(value));
839                 if (rc < 0)
840                         return -errno;
841
842                 /* when we restore, we do not restore lustre xattr */
843                 if (!is_restore ||
844                     (strncmp(XATTR_TRUSTED_PREFIX, name,
845                              sizeof(XATTR_TRUSTED_PREFIX) - 1) != 0)) {
846                         rc = fsetxattr(dst_fd, name, value, rc, 0);
847                         CT_TRACE("fsetxattr of '%s' on '%s' rc=%d (%s)",
848                                  name, dst, rc, strerror(errno));
849                         /* lustre.* attrs aren't supported on other FS's */
850                         if (rc < 0 && errno != EOPNOTSUPP) {
851                                 rc = -errno;
852                                 CT_ERROR(rc, "cannot set extended attribute"
853                                          " '%s' of '%s'",
854                                          name, dst);
855                                 return rc;
856                         }
857                 }
858                 name += strlen(name) + 1;
859         }
860
861         return 0;
862 }
863
864 static int ct_path_lustre(char *buf, int sz, const char *mnt,
865                           const struct lu_fid *fid)
866 {
867         return snprintf(buf, sz, "%s/%s/fid/"DFID_NOBRACE, mnt,
868                         dot_lustre_name, PFID(fid));
869 }
870
871 static int ct_path_archive(char *buf, int sz, const char *archive_dir,
872                            const struct lu_fid *fid)
873 {
874         return snprintf(buf, sz, "%s/%04x/%04x/%04x/%04x/%04x/%04x/"
875                         DFID_NOBRACE, archive_dir,
876                         (fid)->f_oid       & 0xFFFF,
877                         (fid)->f_oid >> 16 & 0xFFFF,
878                         (unsigned int)((fid)->f_seq       & 0xFFFF),
879                         (unsigned int)((fid)->f_seq >> 16 & 0xFFFF),
880                         (unsigned int)((fid)->f_seq >> 32 & 0xFFFF),
881                         (unsigned int)((fid)->f_seq >> 48 & 0xFFFF),
882                         PFID(fid));
883 }
884
885 static bool ct_is_retryable(int err)
886 {
887         return err == -ETIMEDOUT;
888 }
889
890 static int ct_begin_restore(struct hsm_copyaction_private **phcp,
891                             const struct hsm_action_item *hai,
892                             int mdt_index, int open_flags)
893 {
894         char     src[PATH_MAX];
895         int      rc;
896
897         rc = llapi_hsm_action_begin(phcp, ctdata, hai, mdt_index, open_flags,
898                                     false);
899         if (rc < 0) {
900                 ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_fid);
901                 CT_ERROR(rc, "llapi_hsm_action_begin() on '%s' failed", src);
902         }
903
904         return rc;
905 }
906
907 static int ct_begin(struct hsm_copyaction_private **phcp,
908                     const struct hsm_action_item *hai)
909 {
910         /* Restore takes specific parameters. Call the same function w/ default
911          * values for all other operations. */
912         return ct_begin_restore(phcp, hai, -1, 0);
913 }
914
915 static int ct_fini(struct hsm_copyaction_private **phcp,
916                    const struct hsm_action_item *hai, int hp_flags, int ct_rc)
917 {
918         struct hsm_copyaction_private   *hcp;
919         char                             lstr[PATH_MAX];
920         int                              rc;
921
922         CT_TRACE("Action completed, notifying coordinator "
923                  "cookie=%#jx, FID="DFID", hp_flags=%d err=%d",
924                  (uintmax_t)hai->hai_cookie, PFID(&hai->hai_fid),
925                  hp_flags, -ct_rc);
926
927         ct_path_lustre(lstr, sizeof(lstr), opt.o_mnt, &hai->hai_fid);
928
929         if (phcp == NULL || *phcp == NULL) {
930                 rc = llapi_hsm_action_begin(&hcp, ctdata, hai, -1, 0, true);
931                 if (rc < 0) {
932                         CT_ERROR(rc, "llapi_hsm_action_begin() on '%s' failed",
933                                  lstr);
934                         return rc;
935                 }
936                 phcp = &hcp;
937         }
938
939         rc = llapi_hsm_action_end(phcp, &hai->hai_extent, hp_flags, abs(ct_rc));
940         if (rc == -ECANCELED)
941                 CT_ERROR(rc, "completed action on '%s' has been canceled: "
942                          "cookie=%#jx, FID="DFID, lstr,
943                          (uintmax_t)hai->hai_cookie, PFID(&hai->hai_fid));
944         else if (rc < 0)
945                 CT_ERROR(rc, "llapi_hsm_action_end() on '%s' failed", lstr);
946         else
947                 CT_TRACE("llapi_hsm_action_end() on '%s' ok (rc=%d)",
948                          lstr, rc);
949
950         return rc;
951 }
952
953 static int ct_archive(const struct hsm_action_item *hai, const long hal_flags)
954 {
955         struct hsm_copyaction_private   *hcp = NULL;
956         char                             src[PATH_MAX];
957         char                             dst[PATH_MAX + 4] = "";
958         char                             root[PATH_MAX] = "";
959         int                              rc;
960         int                              rcf = 0;
961         bool                             rename_needed = false;
962         int                              hp_flags = 0;
963         int                              open_flags;
964         int                              src_fd = -1;
965         int                              dst_fd = -1;
966
967         rc = ct_begin(&hcp, hai);
968         if (rc < 0)
969                 goto fini_major;
970
971         /* we fill archive so:
972          * source = data FID
973          * destination = lustre FID
974          */
975         ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_dfid);
976         ct_path_archive(root, sizeof(root), opt.o_hsm_root, &hai->hai_fid);
977         if (hai->hai_extent.length == -1) {
978                 /* whole file, write it to tmp location and atomically
979                  * replace old archived file */
980                 snprintf(dst, sizeof(dst), "%s_tmp", root);
981                 /* we cannot rely on the same test because ct_copy_data()
982                  * updates hai_extent.length */
983                 rename_needed = true;
984         } else {
985                 snprintf(dst, sizeof(dst), "%s", root);
986         }
987
988         CT_TRACE("archiving '%s' to '%s'", src, dst);
989
990         if (opt.o_dry_run) {
991                 rc = 0;
992                 goto fini_major;
993         }
994
995         rc = ct_mkdir_p(dst);
996         if (rc < 0) {
997                 CT_ERROR(rc, "mkdir_p '%s' failed", dst);
998                 goto fini_major;
999         }
1000
1001         src_fd = llapi_hsm_action_get_fd(hcp);
1002         if (src_fd < 0) {
1003                 rc = src_fd;
1004                 CT_ERROR(rc, "cannot open '%s' for read", src);
1005                 goto fini_major;
1006         }
1007
1008         open_flags = O_WRONLY | O_NOFOLLOW;
1009         /* If extent is specified, don't truncate an old archived copy */
1010         open_flags |= ((hai->hai_extent.length == -1) ? O_TRUNC : 0) | O_CREAT;
1011
1012         dst_fd = open(dst, open_flags, FILE_PERM);
1013         if (dst_fd == -1) {
1014                 rc = -errno;
1015                 CT_ERROR(rc, "cannot open '%s' for write", dst);
1016                 goto fini_major;
1017         }
1018
1019         /* saving stripe is not critical */
1020         rc = ct_save_stripe(src_fd, src, dst);
1021         if (rc < 0)
1022                 CT_ERROR(rc, "cannot save file striping info of '%s' in '%s'",
1023                          src, dst);
1024
1025         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
1026         if (rc < 0) {
1027                 CT_ERROR(rc, "data copy failed from '%s' to '%s'", src, dst);
1028                 goto fini_major;
1029         }
1030
1031         rc = fsync(dst_fd);
1032         if (rc < 0) {
1033                 rc = -errno;
1034                 CT_ERROR(rc, "cannot flush '%s' archive file '%s'", src, dst);
1035                 goto fini_major;
1036         }
1037
1038         CT_TRACE("data archiving for '%s' to '%s' done", src, dst);
1039
1040         /* attrs will remain on the MDS; no need to copy them, except possibly
1041           for disaster recovery */
1042         if (opt.o_copy_attrs) {
1043                 rc = ct_copy_attr(src, dst, src_fd, dst_fd);
1044                 if (rc < 0) {
1045                         CT_ERROR(rc, "cannot copy attr of '%s' to '%s'",
1046                                  src, dst);
1047                         rcf = rc;
1048                 }
1049                 CT_TRACE("attr file for '%s' saved to archive '%s'",
1050                          src, dst);
1051         }
1052
1053         /* xattrs will remain on the MDS; no need to copy them, except possibly
1054          for disaster recovery */
1055         if (opt.o_copy_xattrs) {
1056                 rc = ct_copy_xattr(src, dst, src_fd, dst_fd, false);
1057                 if (rc < 0) {
1058                         CT_ERROR(rc, "cannot copy xattr of '%s' to '%s'",
1059                                  src, dst);
1060                         rcf = rcf ? rcf : rc;
1061                 }
1062                 CT_TRACE("xattr file for '%s' saved to archive '%s'",
1063                          src, dst);
1064         }
1065
1066         if (rename_needed == true) {
1067                 char     tmp_src[PATH_MAX + 8];
1068                 char     tmp_dst[PATH_MAX + 8];
1069
1070                 /* atomically replace old archived file */
1071                 ct_path_archive(src, sizeof(src), opt.o_hsm_root,
1072                                 &hai->hai_fid);
1073                 rc = rename(dst, src);
1074                 if (rc < 0) {
1075                         rc = -errno;
1076                         CT_ERROR(rc, "cannot rename '%s' to '%s'", dst, src);
1077                         goto fini_major;
1078                 }
1079                 /* rename lov file */
1080                 snprintf(tmp_src, sizeof(tmp_src), "%s.lov", src);
1081                 snprintf(tmp_dst, sizeof(tmp_dst), "%s.lov", dst);
1082                 rc = rename(tmp_dst, tmp_src);
1083                 if (rc < 0)
1084                         CT_ERROR(errno, "cannot rename '%s' to '%s'",
1085                                  tmp_dst, tmp_src);
1086         }
1087
1088         if (opt.o_shadow_tree) {
1089                 /* Create a namespace of softlinks that shadows the original
1090                  * Lustre namespace.  This will only be current at
1091                  * time-of-archive (won't follow renames).
1092                  * WARNING: release won't kill these links; a manual
1093                  * cleanup of dead links would be required.
1094                  */
1095                 char             buf[PATH_MAX];
1096                 long long        recno = -1;
1097                 int              linkno = 0;
1098                 char            *ptr;
1099                 int              depth = 0;
1100                 ssize_t          sz;
1101
1102                 sprintf(buf, DFID, PFID(&hai->hai_fid));
1103                 sprintf(src, "%s/shadow/", opt.o_hsm_root);
1104
1105                 ptr = opt.o_hsm_root;
1106                 while (*ptr)
1107                         (*ptr++ == '/') ? depth-- : 0;
1108
1109                 rc = llapi_fid2path(opt.o_mnt, buf, src + strlen(src),
1110                                     sizeof(src) - strlen(src), &recno, &linkno);
1111                 if (rc < 0) {
1112                         CT_ERROR(rc, "cannot get FID of '%s'", buf);
1113                         rcf = rcf ? rcf : rc;
1114                         goto fini_minor;
1115                 }
1116
1117                 /* Figure out how many parent dirs to symlink back */
1118                 ptr = src;
1119                 while (*ptr)
1120                         (*ptr++ == '/') ? depth++ : 0;
1121                 sprintf(buf, "..");
1122                 while (--depth > 1)
1123                         strcat(buf, "/..");
1124
1125                 ct_path_archive(dst, sizeof(dst), buf, &hai->hai_fid);
1126
1127                 if (ct_mkdir_p(src)) {
1128                         CT_ERROR(errno, "mkdir_p '%s' failed", src);
1129                         rcf = rcf ? rcf : -errno;
1130                         goto fini_minor;
1131                 }
1132                 /* symlink already exists ? */
1133                 sz = readlink(src, buf, sizeof(buf));
1134                 /* detect truncation */
1135                 if (sz == sizeof(buf)) {
1136                         rcf = rcf ? rcf : -E2BIG;
1137                         CT_ERROR(rcf, "readlink '%s' truncated", src);
1138                         goto fini_minor;
1139                 }
1140                 if (sz >= 0) {
1141                         buf[sz] = '\0';
1142                         if (sz == 0 || strncmp(buf, dst, sz) != 0) {
1143                                 if (unlink(src) && errno != ENOENT) {
1144                                         CT_ERROR(errno,
1145                                                  "cannot unlink symlink '%s'",
1146                                                  src);
1147                                         rcf = rcf ? rcf : -errno;
1148                                         goto fini_minor;
1149                                 }
1150                                 /* unlink old symlink done */
1151                                 CT_TRACE("remove old symlink '%s' pointing"
1152                                          " to '%s'", src, buf);
1153                         } else {
1154                                 /* symlink already ok */
1155                                 CT_TRACE("symlink '%s' already pointing"
1156                                          " to '%s'", src, dst);
1157                                 rcf = 0;
1158                                 goto fini_minor;
1159                         }
1160                 }
1161                 if (symlink(dst, src)) {
1162                         CT_ERROR(errno, "cannot symlink '%s' to '%s'",
1163                                  src, dst);
1164                         rcf = rcf ? rcf : -errno;
1165                         goto fini_minor;
1166                 }
1167                 CT_TRACE("symlink '%s' to '%s' done", src, dst);
1168         }
1169 fini_minor:
1170         if (rcf)
1171                 err_minor++;
1172         goto out;
1173
1174
1175 fini_major:
1176         err_major++;
1177
1178         unlink(dst);
1179         if (ct_is_retryable(rc))
1180                 hp_flags |= HP_FLAG_RETRY;
1181
1182         rcf = rc;
1183
1184 out:
1185         if (!(src_fd < 0))
1186                 close(src_fd);
1187
1188         if (!(dst_fd < 0))
1189                 close(dst_fd);
1190
1191         rc = ct_fini(&hcp, hai, hp_flags, rcf);
1192
1193         return rc;
1194 }
1195
1196 static int ct_restore(const struct hsm_action_item *hai, const long hal_flags)
1197 {
1198         struct hsm_copyaction_private   *hcp = NULL;
1199         char                             src[PATH_MAX];
1200         char                             dst[PATH_MAX];
1201         char                             lov_buf[XATTR_SIZE_MAX];
1202         size_t                           lov_size = sizeof(lov_buf);
1203         int                              rc;
1204         int                              hp_flags = 0;
1205         int                              src_fd = -1;
1206         int                              dst_fd = -1;
1207         int                              mdt_index = -1;
1208         int                              open_flags = 0;
1209         bool                             set_lovea;
1210         struct lu_fid                    dfid;
1211         /* we fill lustre so:
1212          * source = lustre FID in the backend
1213          * destination = data FID = volatile file
1214          */
1215
1216         /* build backend file name from released file FID */
1217         ct_path_archive(src, sizeof(src), opt.o_hsm_root, &hai->hai_fid);
1218
1219         rc = llapi_get_mdt_index_by_fid(opt.o_mnt_fd, &hai->hai_fid,
1220                                         &mdt_index);
1221         if (rc < 0) {
1222                 CT_ERROR(rc, "cannot get mdt index "DFID"",
1223                          PFID(&hai->hai_fid));
1224                 return rc;
1225         }
1226         /* restore loads and sets the LOVEA w/o interpreting it to avoid
1227          * dependency on the structure format. */
1228         rc = ct_load_stripe(src, lov_buf, &lov_size);
1229         if (rc < 0) {
1230                 CT_WARN("cannot get stripe rules for '%s' (%s), use default",
1231                         src, strerror(-rc));
1232                 set_lovea = false;
1233         } else {
1234                 open_flags |= O_LOV_DELAY_CREATE;
1235                 set_lovea = true;
1236         }
1237
1238         rc = ct_begin_restore(&hcp, hai, mdt_index, open_flags);
1239         if (rc < 0)
1240                 goto fini;
1241
1242         /* get the FID of the volatile file */
1243         rc = llapi_hsm_action_get_dfid(hcp, &dfid);
1244         if (rc < 0) {
1245                 CT_ERROR(rc, "restoring "DFID
1246                          ", cannot get FID of created volatile file",
1247                          PFID(&hai->hai_fid));
1248                 goto fini;
1249         }
1250
1251         /* build volatile "file name", for messages */
1252         snprintf(dst, sizeof(dst), "{VOLATILE}="DFID, PFID(&dfid));
1253
1254         CT_TRACE("restoring data from '%s' to '%s'", src, dst);
1255
1256         if (opt.o_dry_run) {
1257                 rc = 0;
1258                 goto fini;
1259         }
1260
1261         src_fd = open(src, O_RDONLY | O_NOATIME | O_NOFOLLOW);
1262         if (src_fd < 0) {
1263                 rc = -errno;
1264                 CT_ERROR(rc, "cannot open '%s' for read", src);
1265                 goto fini;
1266         }
1267
1268         dst_fd = llapi_hsm_action_get_fd(hcp);
1269         if (dst_fd < 0) {
1270                 rc = dst_fd;
1271                 CT_ERROR(rc, "cannot open '%s' for write", dst);
1272                 goto fini;
1273         }
1274
1275         if (set_lovea) {
1276                 /* the layout cannot be allocated through .fid so we have to
1277                  * restore a layout */
1278                 rc = ct_restore_stripe(src, dst, dst_fd, lov_buf, lov_size);
1279                 if (rc < 0) {
1280                         CT_ERROR(rc, "cannot restore file striping info"
1281                                  " for '%s' from '%s'", dst, src);
1282                         err_major++;
1283                         goto fini;
1284                 }
1285         }
1286
1287         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
1288         if (rc < 0) {
1289                 CT_ERROR(rc, "cannot copy data from '%s' to '%s'",
1290                          src, dst);
1291                 err_major++;
1292                 if (ct_is_retryable(rc))
1293                         hp_flags |= HP_FLAG_RETRY;
1294                 goto fini;
1295         }
1296
1297         CT_TRACE("data restore from '%s' to '%s' done", src, dst);
1298
1299 fini:
1300         rc = ct_fini(&hcp, hai, hp_flags, rc);
1301
1302         /* object swaping is done by cdt at copy end, so close of volatile file
1303          * cannot be done before */
1304         if (!(src_fd < 0))
1305                 close(src_fd);
1306
1307         if (!(dst_fd < 0))
1308                 close(dst_fd);
1309
1310         return rc;
1311 }
1312
1313 static int ct_remove(const struct hsm_action_item *hai, const long hal_flags)
1314 {
1315         struct hsm_copyaction_private   *hcp = NULL;
1316         char                             dst[PATH_MAX], attr[PATH_MAX + 4];
1317         int                              rc;
1318
1319         rc = ct_begin(&hcp, hai);
1320         if (rc < 0)
1321                 goto fini;
1322
1323         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, &hai->hai_fid);
1324
1325         CT_TRACE("removing file '%s'", dst);
1326
1327         if (opt.o_dry_run) {
1328                 rc = 0;
1329                 goto fini;
1330         }
1331
1332         rc = unlink(dst);
1333         if (rc < 0) {
1334                 rc = -errno;
1335                 CT_ERROR(rc, "cannot unlink '%s'", dst);
1336                 err_minor++;
1337                 goto fini;
1338         }
1339
1340         snprintf(attr, sizeof(attr), "%s.lov", dst);
1341         rc = unlink(attr);
1342         if (rc < 0) {
1343                 rc = -errno;
1344                 CT_ERROR(rc, "cannot unlink '%s'", attr);
1345                 err_minor++;
1346
1347                 /* ignore the error when lov file does not exist. */
1348                 if (rc == -ENOENT)
1349                         rc = 0;
1350                 else
1351                         goto fini;
1352         }
1353
1354 fini:
1355         rc = ct_fini(&hcp, hai, 0, rc);
1356
1357         return rc;
1358 }
1359
1360 static int ct_process_item(struct hsm_action_item *hai, const long hal_flags)
1361 {
1362         int     rc = 0;
1363
1364         if (opt.o_verbose >= LLAPI_MSG_INFO || opt.o_dry_run) {
1365                 /* Print the original path */
1366                 char            fid[128];
1367                 char            path[PATH_MAX];
1368                 long long       recno = -1;
1369                 int             linkno = 0;
1370
1371                 sprintf(fid, DFID, PFID(&hai->hai_fid));
1372                 CT_TRACE("'%s' action %s reclen %d, cookie=%#jx",
1373                          fid, hsm_copytool_action2name(hai->hai_action),
1374                          hai->hai_len, (uintmax_t)hai->hai_cookie);
1375                 rc = llapi_fid2path(opt.o_mnt, fid, path,
1376                                     sizeof(path), &recno, &linkno);
1377                 if (rc < 0)
1378                         CT_ERROR(rc, "cannot get path of FID %s", fid);
1379                 else
1380                         CT_TRACE("processing file '%s'", path);
1381         }
1382
1383         switch (hai->hai_action) {
1384         /* set err_major, minor inside these functions */
1385         case HSMA_ARCHIVE:
1386                 rc = ct_archive(hai, hal_flags);
1387                 break;
1388         case HSMA_RESTORE:
1389                 rc = ct_restore(hai, hal_flags);
1390                 break;
1391         case HSMA_REMOVE:
1392                 rc = ct_remove(hai, hal_flags);
1393                 break;
1394         case HSMA_CANCEL:
1395                 CT_TRACE("cancel not implemented for file system '%s'",
1396                          opt.o_mnt);
1397                 /* Don't report progress to coordinator for this cookie:
1398                  * the copy function will get ECANCELED when reporting
1399                  * progress. */
1400                 err_minor++;
1401                 return 0;
1402                 break;
1403         default:
1404                 rc = -EINVAL;
1405                 CT_ERROR(rc, "unknown action %d, on '%s'", hai->hai_action,
1406                          opt.o_mnt);
1407                 err_minor++;
1408                 ct_fini(NULL, hai, 0, rc);
1409         }
1410
1411         return 0;
1412 }
1413
1414 struct ct_th_data {
1415         long                     hal_flags;
1416         struct hsm_action_item  *hai;
1417 };
1418
1419 static void *ct_thread(void *data)
1420 {
1421         struct ct_th_data *cttd = data;
1422         int rc;
1423
1424         rc = ct_process_item(cttd->hai, cttd->hal_flags);
1425
1426         free(cttd->hai);
1427         free(cttd);
1428         pthread_exit((void *)(intptr_t)rc);
1429 }
1430
1431 static int ct_process_item_async(const struct hsm_action_item *hai,
1432                                  long hal_flags)
1433 {
1434         pthread_attr_t           attr;
1435         pthread_t                thread;
1436         struct ct_th_data       *data;
1437         int                      rc;
1438
1439         data = malloc(sizeof(*data));
1440         if (data == NULL)
1441                 return -ENOMEM;
1442
1443         data->hai = malloc(hai->hai_len);
1444         if (data->hai == NULL) {
1445                 free(data);
1446                 return -ENOMEM;
1447         }
1448
1449         memcpy(data->hai, hai, hai->hai_len);
1450         data->hal_flags = hal_flags;
1451
1452         rc = pthread_attr_init(&attr);
1453         if (rc != 0) {
1454                 CT_ERROR(rc, "pthread_attr_init failed for '%s' service",
1455                          opt.o_mnt);
1456                 free(data->hai);
1457                 free(data);
1458                 return -rc;
1459         }
1460
1461         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1462
1463         rc = pthread_create(&thread, &attr, ct_thread, data);
1464         if (rc != 0)
1465                 CT_ERROR(rc, "cannot create thread for '%s' service",
1466                          opt.o_mnt);
1467
1468         pthread_attr_destroy(&attr);
1469         return 0;
1470 }
1471
1472 static int ct_import_one(const char *src, const char *dst)
1473 {
1474         char            newarc[PATH_MAX];
1475         struct lu_fid   fid;
1476         struct stat     st;
1477         int             rc;
1478
1479         CT_TRACE("importing '%s' from '%s'", dst, src);
1480
1481         if (stat(src, &st) < 0) {
1482                 rc = -errno;
1483                 CT_ERROR(rc, "cannot stat '%s'", src);
1484                 return rc;
1485         }
1486
1487         if (opt.o_dry_run)
1488                 return 0;
1489
1490         rc = llapi_hsm_import(dst,
1491                               opt.o_archive_id_used ?
1492                               opt.o_archive_id[0] : 0,
1493                               &st, 0, 0, 0, 0, NULL, &fid);
1494         if (rc < 0) {
1495                 CT_ERROR(rc, "cannot import '%s' from '%s'", dst, src);
1496                 return rc;
1497         }
1498
1499         ct_path_archive(newarc, sizeof(newarc), opt.o_hsm_root, &fid);
1500
1501         rc = ct_mkdir_p(newarc);
1502         if (rc < 0) {
1503                 CT_ERROR(rc, "mkdir_p '%s' failed", newarc);
1504                 err_major++;
1505                 return rc;
1506
1507         }
1508
1509         /* Lots of choices now: mv, ln, ln -s ? */
1510         rc = link(src, newarc); /* hardlink */
1511         if (rc < 0) {
1512                 rc = -errno;
1513                 CT_ERROR(rc, "cannot link '%s' to '%s'", newarc, src);
1514                 err_major++;
1515                 return rc;
1516         }
1517         CT_TRACE("imported '%s' from '%s'=='%s'", dst, newarc, src);
1518
1519         return 0;
1520 }
1521
1522 static char *path_concat(const char *dirname, const char *basename)
1523 {
1524         char    *result;
1525         int      rc;
1526
1527         rc = asprintf(&result, "%s/%s", dirname, basename);
1528         if (rc < 0)
1529                 return NULL;
1530
1531         return result;
1532 }
1533
1534 static int ct_import_fid(const struct lu_fid *import_fid)
1535 {
1536         char    fid_path[PATH_MAX];
1537         int     rc;
1538
1539         ct_path_lustre(fid_path, sizeof(fid_path), opt.o_mnt, import_fid);
1540         rc = access(fid_path, F_OK);
1541         if (rc == 0 || errno != ENOENT) {
1542                 rc = (errno == 0) ? -EEXIST : -errno;
1543                 CT_ERROR(rc, "cannot import '"DFID"'", PFID(import_fid));
1544                 return rc;
1545         }
1546
1547         ct_path_archive(fid_path, sizeof(fid_path), opt.o_hsm_root,
1548                         import_fid);
1549
1550         CT_TRACE("Resolving "DFID" to %s", PFID(import_fid), fid_path);
1551
1552         return ct_import_one(fid_path, opt.o_dst);
1553 }
1554
1555 static int ct_import_recurse(const char *relpath)
1556 {
1557         DIR             *dir;
1558         struct dirent   *ent;
1559         char            *srcpath, *newpath;
1560         struct lu_fid    import_fid;
1561         int              rc;
1562
1563         if (relpath == NULL)
1564                 return -EINVAL;
1565
1566         /* Is relpath a FID? */
1567         rc = llapi_fid_parse(relpath, &import_fid, NULL);
1568         if (!rc)
1569                 return ct_import_fid(&import_fid);
1570
1571         srcpath = path_concat(opt.o_hsm_root, relpath);
1572         if (srcpath == NULL) {
1573                 err_major++;
1574                 return -ENOMEM;
1575         }
1576
1577         dir = opendir(srcpath);
1578         if (dir == NULL) {
1579                 /* Not a dir, or error */
1580                 if (errno == ENOTDIR) {
1581                         /* Single regular file case, treat o_dst as absolute
1582                            final location. */
1583                         rc = ct_import_one(srcpath, opt.o_dst);
1584                 } else {
1585                         rc = -errno;
1586                         CT_ERROR(rc, "cannot opendir '%s'", srcpath);
1587                         err_major++;
1588                 }
1589                 free(srcpath);
1590                 return rc;
1591         }
1592         free(srcpath);
1593
1594         while ((ent = readdir(dir)) != NULL) {
1595                 if (!strcmp(ent->d_name, ".") ||
1596                     !strcmp(ent->d_name, ".."))
1597                         continue;
1598
1599                 /* New relative path */
1600                 newpath = path_concat(relpath, ent->d_name);
1601                 if (newpath == NULL) {
1602                         err_major++;
1603                         rc = -ENOMEM;
1604                         goto out;
1605                 }
1606
1607                 if (ent->d_type == DT_DIR) {
1608                         rc = ct_import_recurse(newpath);
1609                 } else {
1610                         char src[PATH_MAX];
1611                         char dst[PATH_MAX];
1612
1613                         sprintf(src, "%s/%s", opt.o_hsm_root, newpath);
1614                         sprintf(dst, "%s/%s", opt.o_dst, newpath);
1615                         /* Make the target dir in the Lustre fs */
1616                         rc = ct_mkdir_p(dst);
1617                         if (rc == 0) {
1618                                 /* Import the file */
1619                                 rc = ct_import_one(src, dst);
1620                         } else {
1621                                 CT_ERROR(rc, "ct_mkdir_p '%s' failed", dst);
1622                                 err_major++;
1623                         }
1624                 }
1625
1626                 if (rc != 0) {
1627                         CT_ERROR(rc, "cannot import '%s'", newpath);
1628                         if (err_major && opt.o_abort_on_error) {
1629                                 free(newpath);
1630                                 goto out;
1631                         }
1632                 }
1633                 free(newpath);
1634         }
1635
1636         rc = 0;
1637 out:
1638         closedir(dir);
1639         return rc;
1640 }
1641
1642 static int ct_rebind_one(const struct lu_fid *old_fid,
1643                          const struct lu_fid *new_fid)
1644 {
1645         char    src[PATH_MAX];
1646         char    dst[PATH_MAX];
1647         int     rc;
1648
1649         CT_TRACE("rebind "DFID" to "DFID, PFID(old_fid), PFID(new_fid));
1650
1651         ct_path_archive(src, sizeof(src), opt.o_hsm_root, old_fid);
1652         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, new_fid);
1653
1654         if (!opt.o_dry_run) {
1655                 char src_attr[PATH_MAX + 4];
1656                 char dst_attr[PATH_MAX + 4];
1657
1658                 ct_mkdir_p(dst);
1659                 if (rename(src, dst)) {
1660                         rc = -errno;
1661                         CT_ERROR(rc, "cannot rename '%s' to '%s'", src, dst);
1662                         return -errno;
1663                 }
1664                 /* rename lov file */
1665                 snprintf(src_attr, sizeof(src_attr), "%s.lov", src);
1666                 snprintf(dst_attr, sizeof(dst_attr), "%s.lov", dst);
1667                 if (rename(src_attr, dst_attr))
1668                         CT_ERROR(errno, "cannot rename '%s' to '%s'",
1669                                  src_attr, dst_attr);
1670
1671         }
1672         return 0;
1673 }
1674
1675 static bool fid_is_file(struct lu_fid *fid)
1676 {
1677         return fid_is_norm(fid) || fid_is_igif(fid);
1678 }
1679
1680 static bool should_ignore_line(const char *line)
1681 {
1682         int     i;
1683
1684         for (i = 0; line[i] != '\0'; i++) {
1685                 if (isspace(line[i]))
1686                         continue;
1687                 else if (line[i] == '#')
1688                         return true;
1689                 else
1690                         return false;
1691         }
1692
1693         return true;
1694 }
1695
1696 static int ct_rebind_list(const char *list)
1697 {
1698         int              rc;
1699         FILE            *filp;
1700         ssize_t          r;
1701         char            *line = NULL;
1702         size_t           line_size = 0;
1703         unsigned int     nl = 0;
1704         unsigned int     ok = 0;
1705
1706         filp = fopen(list, "r");
1707         if (filp == NULL) {
1708                 rc = -errno;
1709                 CT_ERROR(rc, "cannot open '%s'", list);
1710                 return rc;
1711         }
1712
1713         /* each line consists of 2 FID */
1714         while ((r = getline(&line, &line_size, filp)) != -1) {
1715                 struct lu_fid old_fid;
1716                 struct lu_fid new_fid;
1717                 char *next_fid;
1718
1719                 /* Ignore empty and commented out ('#...') lines. */
1720                 if (should_ignore_line(line))
1721                         continue;
1722
1723                 nl++;
1724
1725                 rc = llapi_fid_parse(line, &old_fid, &next_fid);
1726                 if (rc)
1727                         goto error;
1728                 rc = llapi_fid_parse(next_fid, &new_fid, NULL);
1729                 if (rc)
1730                         goto error;
1731                 if (!fid_is_file(&old_fid) || !fid_is_file(&new_fid))
1732                         rc = -EINVAL;
1733                 if (rc) {
1734 error:                  CT_ERROR(rc, "%s:%u: two FIDs expected in '%s'",
1735                                  list, nl, line);
1736                         err_major++;
1737                         continue;
1738                 }
1739
1740                 if (ct_rebind_one(&old_fid, &new_fid))
1741                         err_major++;
1742                 else
1743                         ok++;
1744         }
1745
1746         fclose(filp);
1747
1748         if (line)
1749                 free(line);
1750
1751         /* return 0 if all rebinds were successful */
1752         CT_TRACE("%u lines read from '%s', %u rebind successful", nl, list, ok);
1753
1754         return ok == nl ? 0 : -1;
1755 }
1756
1757 static int ct_rebind(void)
1758 {
1759         int rc;
1760
1761         if (opt.o_dst) {
1762                 struct lu_fid old_fid;
1763                 struct lu_fid new_fid;
1764
1765                 rc = llapi_fid_parse(opt.o_src, &old_fid, NULL);
1766                 if (!rc && !fid_is_file(&old_fid))
1767                         rc = -EINVAL;
1768                 if (rc) {
1769                         CT_ERROR(rc, "invalid source FID '%s'", opt.o_src);
1770                         return rc;
1771                 }
1772
1773                 rc = llapi_fid_parse(opt.o_dst, &new_fid, NULL);
1774                 if (!rc && !fid_is_file(&new_fid))
1775                         rc = -EINVAL;
1776                 if (rc) {
1777                         CT_ERROR(rc, "invalid destination FID '%s'", opt.o_dst);
1778                         return rc;
1779                 }
1780
1781                 rc = ct_rebind_one(&old_fid, &new_fid);
1782
1783                 return rc;
1784         }
1785
1786         /* o_src is a list file */
1787         rc = ct_rebind_list(opt.o_src);
1788
1789         return rc;
1790 }
1791
1792 static int ct_dir_level_max(const char *dirpath, __u16 *sub_seqmax)
1793 {
1794         DIR             *dir;
1795         int              rc;
1796         __u16            sub_seq;
1797         struct dirent *ent;
1798
1799         *sub_seqmax = 0;
1800
1801         dir = opendir(dirpath);
1802         if (dir == NULL) {
1803                 rc = -errno;
1804                 CT_ERROR(rc, "cannot open directory '%s'", opt.o_hsm_root);
1805                 return rc;
1806         }
1807
1808         do {
1809                 errno = 0;
1810                 ent = readdir(dir);
1811                 if (ent == NULL) {
1812                         /* end of directory.
1813                          * rc is 0 and seqmax contains the max value. */
1814                         rc = -errno;
1815                         if (rc)
1816                                 CT_ERROR(rc, "cannot readdir '%s'", dirpath);
1817                         goto out;
1818                 }
1819
1820                 if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
1821                         continue;
1822
1823                 if (sscanf(ent->d_name, "%hx", &sub_seq) != 1) {
1824                         CT_TRACE("'%s' has an unexpected dirname format, "
1825                                  "skip entry", ent->d_name);
1826                         continue;
1827                 }
1828                 if (sub_seq > *sub_seqmax)
1829                         *sub_seqmax = sub_seq;
1830         } while (1);
1831 out:
1832         closedir(dir);
1833         return rc;
1834 }
1835
1836 static int ct_max_sequence(void)
1837 {
1838         int     rc, i;
1839         char    path[PATH_MAX];
1840         __u64   seq = 0;
1841         __u16   subseq;
1842
1843         snprintf(path, sizeof(path), "%s", opt.o_hsm_root);
1844         /* FID sequence is stored in top-level directory names:
1845          * hsm_root/16bits (high weight)/16 bits/16 bits/16 bits (low weight).
1846          */
1847         for (i = 0; i < 4; i++) {
1848                 size_t path_len;
1849
1850                 rc = ct_dir_level_max(path, &subseq);
1851                 if (rc != 0)
1852                         return rc;
1853                 seq |= ((__u64)subseq << ((3 - i) * 16));
1854                 path_len = strlen(path);
1855                 rc = snprintf(path + path_len, sizeof(path) - path_len,
1856                               "/%04x", subseq);
1857                 if (rc >= (sizeof(path) - path_len))
1858                         return -E2BIG;
1859                 path[sizeof(path) - 1] = '\0';
1860         }
1861
1862         printf("max_sequence: %#jx\n", (uintmax_t)seq);
1863
1864         return 0;
1865 }
1866
1867 static void handler(int signal)
1868 {
1869         psignal(signal, "exiting");
1870         /* If we don't clean up upon interrupt, umount thinks there's a ref
1871          * and doesn't remove us from mtab (EINPROGRESS). The lustre client
1872          * does successfully unmount and the mount is actually gone, but the
1873          * mtab entry remains. So this just makes mtab happier. */
1874         llapi_hsm_copytool_unregister(&ctdata);
1875
1876         /* Also remove fifo upon signal as during normal/error exit */
1877         if (opt.o_event_fifo != NULL)
1878                 llapi_hsm_unregister_event_fifo(opt.o_event_fifo);
1879         _exit(1);
1880 }
1881
1882 /* Daemon waits for messages from the kernel; run it in the background. */
1883 static int ct_run(void)
1884 {
1885         struct sigaction cleanup_sigaction;
1886         int rc;
1887
1888         if (opt.o_daemonize) {
1889                 rc = daemon(1, 1);
1890                 if (rc < 0) {
1891                         rc = -errno;
1892                         CT_ERROR(rc, "cannot daemonize");
1893                         return rc;
1894                 }
1895         }
1896
1897         setbuf(stdout, NULL);
1898
1899         if (opt.o_event_fifo != NULL) {
1900                 rc = llapi_hsm_register_event_fifo(opt.o_event_fifo);
1901                 if (rc < 0) {
1902                         CT_ERROR(rc, "failed to register event fifo");
1903                         return rc;
1904                 }
1905                 llapi_error_callback_set(llapi_hsm_log_error);
1906         }
1907
1908         rc = llapi_hsm_copytool_register(&ctdata, opt.o_mnt,
1909                                          opt.o_archive_id_used,
1910                                          opt.o_archive_id, 0);
1911         if (rc < 0) {
1912                 CT_ERROR(rc, "cannot start copytool interface");
1913                 return rc;
1914         }
1915
1916         memset(&cleanup_sigaction, 0, sizeof(cleanup_sigaction));
1917         cleanup_sigaction.sa_handler = handler;
1918         sigemptyset(&cleanup_sigaction.sa_mask);
1919         sigaction(SIGINT, &cleanup_sigaction, NULL);
1920         sigaction(SIGTERM, &cleanup_sigaction, NULL);
1921
1922         while (1) {
1923                 struct hsm_action_list *hal;
1924                 struct hsm_action_item *hai;
1925                 int msgsize;
1926                 int i = 0;
1927
1928                 CT_TRACE("waiting for message from kernel");
1929
1930                 rc = llapi_hsm_copytool_recv(ctdata, &hal, &msgsize);
1931                 if (rc == -ESHUTDOWN) {
1932                         CT_TRACE("shutting down");
1933                         break;
1934                 } else if (rc < 0) {
1935                         CT_WARN("cannot receive action list: %s",
1936                                 strerror(-rc));
1937                         err_major++;
1938                         if (opt.o_abort_on_error)
1939                                 break;
1940                         else
1941                                 continue;
1942                 }
1943
1944                 CT_TRACE("copytool fs=%s archive#=%d item_count=%d",
1945                          hal->hal_fsname, hal->hal_archive_id, hal->hal_count);
1946
1947                 if (strcmp(hal->hal_fsname, fs_name) != 0) {
1948                         rc = -EINVAL;
1949                         CT_ERROR(rc, "'%s' invalid fs name, expecting: %s",
1950                                  hal->hal_fsname, fs_name);
1951                         err_major++;
1952                         if (opt.o_abort_on_error)
1953                                 break;
1954                         else
1955                                 continue;
1956                 }
1957
1958                 hai = hai_first(hal);
1959                 while (++i <= hal->hal_count) {
1960                         if ((char *)hai - (char *)hal > msgsize) {
1961                                 rc = -EPROTO;
1962                                 CT_ERROR(rc,
1963                                          "'%s' item %d past end of message!",
1964                                          opt.o_mnt, i);
1965                                 err_major++;
1966                                 break;
1967                         }
1968                         rc = ct_process_item_async(hai, hal->hal_flags);
1969                         if (rc < 0)
1970                                 CT_ERROR(rc, "'%s' item %d process",
1971                                          opt.o_mnt, i);
1972                         if (opt.o_abort_on_error && err_major)
1973                                 break;
1974                         hai = hai_next(hai);
1975                 }
1976
1977                 if (opt.o_abort_on_error && err_major)
1978                         break;
1979         }
1980
1981         llapi_hsm_copytool_unregister(&ctdata);
1982         if (opt.o_event_fifo != NULL)
1983                 llapi_hsm_unregister_event_fifo(opt.o_event_fifo);
1984
1985         return rc;
1986 }
1987
1988 static int ct_setup(void)
1989 {
1990         int     rc;
1991
1992         /* set llapi message level */
1993         llapi_msg_set_level(opt.o_verbose);
1994
1995         arc_fd = open(opt.o_hsm_root, O_RDONLY);
1996         if (arc_fd < 0) {
1997                 rc = -errno;
1998                 CT_ERROR(rc, "cannot open archive at '%s'", opt.o_hsm_root);
1999                 return rc;
2000         }
2001
2002         rc = llapi_search_fsname(opt.o_mnt, fs_name);
2003         if (rc < 0) {
2004                 CT_ERROR(rc, "cannot find a Lustre filesystem mounted at '%s'",
2005                          opt.o_mnt);
2006                 return rc;
2007         }
2008
2009         opt.o_mnt_fd = open(opt.o_mnt, O_RDONLY);
2010         if (opt.o_mnt_fd < 0) {
2011                 rc = -errno;
2012                 CT_ERROR(rc, "cannot open mount point at '%s'",
2013                          opt.o_mnt);
2014                 return rc;
2015         }
2016
2017         return rc;
2018 }
2019
2020 static int ct_cleanup(void)
2021 {
2022         int     rc;
2023
2024         if (opt.o_mnt_fd >= 0) {
2025                 rc = close(opt.o_mnt_fd);
2026                 if (rc < 0) {
2027                         rc = -errno;
2028                         CT_ERROR(rc, "cannot close mount point");
2029                         return rc;
2030                 }
2031         }
2032
2033         if (arc_fd >= 0) {
2034                 rc = close(arc_fd);
2035                 if (rc < 0) {
2036                         rc = -errno;
2037                         CT_ERROR(rc, "cannot close archive root directory");
2038                         return rc;
2039                 }
2040         }
2041
2042         if (opt.o_archive_id_cnt > 0) {
2043                 free(opt.o_archive_id);
2044                 opt.o_archive_id = NULL;
2045                 opt.o_archive_id_cnt = 0;
2046         }
2047
2048         return 0;
2049 }
2050
2051 int main(int argc, char **argv)
2052 {
2053         int     rc;
2054
2055         snprintf(cmd_name, sizeof(cmd_name), "%s", basename(argv[0]));
2056         rc = ct_parseopts(argc, argv);
2057         if (rc < 0) {
2058                 CT_WARN("try '%s --help' for more information", cmd_name);
2059                 return -rc;
2060         }
2061
2062         rc = ct_setup();
2063         if (rc < 0)
2064                 goto error_cleanup;
2065
2066         switch (opt.o_action) {
2067         case CA_IMPORT:
2068                 rc = ct_import_recurse(opt.o_src);
2069                 break;
2070         case CA_REBIND:
2071                 rc = ct_rebind();
2072                 break;
2073         case CA_MAXSEQ:
2074                 rc = ct_max_sequence();
2075                 break;
2076         default:
2077                 rc = ct_run();
2078                 break;
2079         }
2080
2081         if (opt.o_action != CA_MAXSEQ)
2082                 CT_TRACE("process finished, errs: %d major, %d minor,"
2083                          " rc=%d (%s)", err_major, err_minor, rc,
2084                          strerror(-rc));
2085
2086 error_cleanup:
2087         ct_cleanup();
2088
2089         return -rc;
2090 }