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