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