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