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