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