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