Whamcloud - gitweb
LU-8854 llapi: remove lustre specific strlcpy & strlcat functions
[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 + 4] = "";
890         char                             root[PATH_MAX] = "";
891         int                              rc;
892         int                              rcf = 0;
893         bool                             rename_needed = false;
894         int                              hp_flags = 0;
895         int                              open_flags;
896         int                              src_fd = -1;
897         int                              dst_fd = -1;
898
899         rc = ct_begin(&hcp, hai);
900         if (rc < 0)
901                 goto fini_major;
902
903         /* we fill archive so:
904          * source = data FID
905          * destination = lustre FID
906          */
907         ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_dfid);
908         ct_path_archive(root, sizeof(root), opt.o_hsm_root, &hai->hai_fid);
909         if (hai->hai_extent.length == -1) {
910                 /* whole file, write it to tmp location and atomically
911                  * replace old archived file */
912                 snprintf(dst, sizeof(dst), "%s_tmp", root);
913                 /* we cannot rely on the same test because ct_copy_data()
914                  * updates hai_extent.length */
915                 rename_needed = true;
916         } else {
917                 snprintf(dst, sizeof(dst), "%s", root);
918         }
919
920         CT_TRACE("archiving '%s' to '%s'", src, dst);
921
922         if (opt.o_dry_run) {
923                 rc = 0;
924                 goto fini_major;
925         }
926
927         rc = ct_mkdir_p(dst);
928         if (rc < 0) {
929                 CT_ERROR(rc, "mkdir_p '%s' failed", dst);
930                 goto fini_major;
931         }
932
933         src_fd = llapi_hsm_action_get_fd(hcp);
934         if (src_fd < 0) {
935                 rc = src_fd;
936                 CT_ERROR(rc, "cannot open '%s' for read", src);
937                 goto fini_major;
938         }
939
940         open_flags = O_WRONLY | O_NOFOLLOW;
941         /* If extent is specified, don't truncate an old archived copy */
942         open_flags |= ((hai->hai_extent.length == -1) ? O_TRUNC : 0) | O_CREAT;
943
944         dst_fd = open(dst, open_flags, FILE_PERM);
945         if (dst_fd == -1) {
946                 rc = -errno;
947                 CT_ERROR(rc, "cannot open '%s' for write", dst);
948                 goto fini_major;
949         }
950
951         /* saving stripe is not critical */
952         rc = ct_save_stripe(src_fd, src, dst);
953         if (rc < 0)
954                 CT_ERROR(rc, "cannot save file striping info of '%s' in '%s'",
955                          src, dst);
956
957         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
958         if (rc < 0) {
959                 CT_ERROR(rc, "data copy failed from '%s' to '%s'", src, dst);
960                 goto fini_major;
961         }
962
963         rc = fsync(dst_fd);
964         if (rc < 0) {
965                 rc = -errno;
966                 CT_ERROR(rc, "cannot flush '%s' archive file '%s'", src, dst);
967                 goto fini_major;
968         }
969
970         CT_TRACE("data archiving for '%s' to '%s' done", src, dst);
971
972         /* attrs will remain on the MDS; no need to copy them, except possibly
973           for disaster recovery */
974         if (opt.o_copy_attrs) {
975                 rc = ct_copy_attr(src, dst, src_fd, dst_fd);
976                 if (rc < 0) {
977                         CT_ERROR(rc, "cannot copy attr of '%s' to '%s'",
978                                  src, dst);
979                         rcf = rc;
980                 }
981                 CT_TRACE("attr file for '%s' saved to archive '%s'",
982                          src, dst);
983         }
984
985         /* xattrs will remain on the MDS; no need to copy them, except possibly
986          for disaster recovery */
987         if (opt.o_copy_xattrs) {
988                 rc = ct_copy_xattr(src, dst, src_fd, dst_fd, false);
989                 if (rc < 0) {
990                         CT_ERROR(rc, "cannot copy xattr of '%s' to '%s'",
991                                  src, dst);
992                         rcf = rcf ? rcf : rc;
993                 }
994                 CT_TRACE("xattr file for '%s' saved to archive '%s'",
995                          src, dst);
996         }
997
998         if (rename_needed == true) {
999                 char     tmp_src[PATH_MAX];
1000                 char     tmp_dst[PATH_MAX];
1001
1002                 /* atomically replace old archived file */
1003                 ct_path_archive(src, sizeof(src), opt.o_hsm_root,
1004                                 &hai->hai_fid);
1005                 rc = rename(dst, src);
1006                 if (rc < 0) {
1007                         rc = -errno;
1008                         CT_ERROR(rc, "cannot rename '%s' to '%s'", dst, src);
1009                         goto fini_major;
1010                 }
1011                 /* rename lov file */
1012                 snprintf(tmp_src, sizeof(tmp_src), "%s.lov", src);
1013                 snprintf(tmp_dst, sizeof(tmp_dst), "%s.lov", dst);
1014                 rc = rename(tmp_dst, tmp_src);
1015                 if (rc < 0)
1016                         CT_ERROR(errno, "cannot rename '%s' to '%s'",
1017                                  tmp_dst, tmp_src);
1018         }
1019
1020         if (opt.o_shadow_tree) {
1021                 /* Create a namespace of softlinks that shadows the original
1022                  * Lustre namespace.  This will only be current at
1023                  * time-of-archive (won't follow renames).
1024                  * WARNING: release won't kill these links; a manual
1025                  * cleanup of dead links would be required.
1026                  */
1027                 char             buf[PATH_MAX];
1028                 long long        recno = -1;
1029                 int              linkno = 0;
1030                 char            *ptr;
1031                 int              depth = 0;
1032                 ssize_t          sz;
1033
1034                 sprintf(buf, DFID, PFID(&hai->hai_fid));
1035                 sprintf(src, "%s/shadow/", opt.o_hsm_root);
1036
1037                 ptr = opt.o_hsm_root;
1038                 while (*ptr)
1039                         (*ptr++ == '/') ? depth-- : 0;
1040
1041                 rc = llapi_fid2path(opt.o_mnt, buf, src + strlen(src),
1042                                     sizeof(src) - strlen(src), &recno, &linkno);
1043                 if (rc < 0) {
1044                         CT_ERROR(rc, "cannot get FID of '%s'", buf);
1045                         rcf = rcf ? rcf : rc;
1046                         goto fini_minor;
1047                 }
1048
1049                 /* Figure out how many parent dirs to symlink back */
1050                 ptr = src;
1051                 while (*ptr)
1052                         (*ptr++ == '/') ? depth++ : 0;
1053                 sprintf(buf, "..");
1054                 while (--depth > 1)
1055                         strcat(buf, "/..");
1056
1057                 ct_path_archive(dst, sizeof(dst), buf, &hai->hai_fid);
1058
1059                 if (ct_mkdir_p(src)) {
1060                         CT_ERROR(errno, "mkdir_p '%s' failed", src);
1061                         rcf = rcf ? rcf : -errno;
1062                         goto fini_minor;
1063                 }
1064                 /* symlink already exists ? */
1065                 sz = readlink(src, buf, sizeof(buf));
1066                 /* detect truncation */
1067                 if (sz == sizeof(buf)) {
1068                         rcf = rcf ? rcf : -E2BIG;
1069                         CT_ERROR(rcf, "readlink '%s' truncated", src);
1070                         goto fini_minor;
1071                 }
1072                 if (sz >= 0) {
1073                         buf[sz] = '\0';
1074                         if (sz == 0 || strncmp(buf, dst, sz) != 0) {
1075                                 if (unlink(src) && errno != ENOENT) {
1076                                         CT_ERROR(errno,
1077                                                  "cannot unlink symlink '%s'",
1078                                                  src);
1079                                         rcf = rcf ? rcf : -errno;
1080                                         goto fini_minor;
1081                                 /* unlink old symlink done */
1082                                 CT_TRACE("remove old symlink '%s' pointing"
1083                                          " to '%s'", src, buf);
1084                                 }
1085                         } else {
1086                                 /* symlink already ok */
1087                                 CT_TRACE("symlink '%s' already pointing"
1088                                          " to '%s'", src, dst);
1089                                 rcf = 0;
1090                                 goto fini_minor;
1091                         }
1092                 }
1093                 if (symlink(dst, src)) {
1094                         CT_ERROR(errno, "cannot symlink '%s' to '%s'",
1095                                  src, dst);
1096                         rcf = rcf ? rcf : -errno;
1097                         goto fini_minor;
1098                 }
1099                 CT_TRACE("symlink '%s' to '%s' done", src, dst);
1100         }
1101 fini_minor:
1102         if (rcf)
1103                 err_minor++;
1104         goto out;
1105
1106
1107 fini_major:
1108         err_major++;
1109
1110         unlink(dst);
1111         if (ct_is_retryable(rc))
1112                 hp_flags |= HP_FLAG_RETRY;
1113
1114         rcf = rc;
1115
1116 out:
1117         if (!(src_fd < 0))
1118                 close(src_fd);
1119
1120         if (!(dst_fd < 0))
1121                 close(dst_fd);
1122
1123         rc = ct_fini(&hcp, hai, hp_flags, rcf);
1124
1125         return rc;
1126 }
1127
1128 static int ct_restore(const struct hsm_action_item *hai, const long hal_flags)
1129 {
1130         struct hsm_copyaction_private   *hcp = NULL;
1131         char                             src[PATH_MAX];
1132         char                             dst[PATH_MAX];
1133         char                             lov_buf[XATTR_SIZE_MAX];
1134         size_t                           lov_size = sizeof(lov_buf);
1135         int                              rc;
1136         int                              hp_flags = 0;
1137         int                              src_fd = -1;
1138         int                              dst_fd = -1;
1139         int                              mdt_index = -1;
1140         int                              open_flags = 0;
1141         bool                             set_lovea;
1142         struct lu_fid                    dfid;
1143         /* we fill lustre so:
1144          * source = lustre FID in the backend
1145          * destination = data FID = volatile file
1146          */
1147
1148         /* build backend file name from released file FID */
1149         ct_path_archive(src, sizeof(src), opt.o_hsm_root, &hai->hai_fid);
1150
1151         rc = llapi_get_mdt_index_by_fid(opt.o_mnt_fd, &hai->hai_fid,
1152                                         &mdt_index);
1153         if (rc < 0) {
1154                 CT_ERROR(rc, "cannot get mdt index "DFID"",
1155                          PFID(&hai->hai_fid));
1156                 return rc;
1157         }
1158         /* restore loads and sets the LOVEA w/o interpreting it to avoid
1159          * dependency on the structure format. */
1160         rc = ct_load_stripe(src, lov_buf, &lov_size);
1161         if (rc < 0) {
1162                 CT_WARN("cannot get stripe rules for '%s' (%s), use default",
1163                         src, strerror(-rc));
1164                 set_lovea = false;
1165         } else {
1166                 open_flags |= O_LOV_DELAY_CREATE;
1167                 set_lovea = true;
1168         }
1169
1170         rc = ct_begin_restore(&hcp, hai, mdt_index, open_flags);
1171         if (rc < 0)
1172                 goto fini;
1173
1174         /* get the FID of the volatile file */
1175         rc = llapi_hsm_action_get_dfid(hcp, &dfid);
1176         if (rc < 0) {
1177                 CT_ERROR(rc, "restoring "DFID
1178                          ", cannot get FID of created volatile file",
1179                          PFID(&hai->hai_fid));
1180                 goto fini;
1181         }
1182
1183         /* build volatile "file name", for messages */
1184         snprintf(dst, sizeof(dst), "{VOLATILE}="DFID, PFID(&dfid));
1185
1186         CT_TRACE("restoring data from '%s' to '%s'", src, dst);
1187
1188         if (opt.o_dry_run) {
1189                 rc = 0;
1190                 goto fini;
1191         }
1192
1193         src_fd = open(src, O_RDONLY | O_NOATIME | O_NOFOLLOW);
1194         if (src_fd < 0) {
1195                 rc = -errno;
1196                 CT_ERROR(rc, "cannot open '%s' for read", src);
1197                 goto fini;
1198         }
1199
1200         dst_fd = llapi_hsm_action_get_fd(hcp);
1201         if (dst_fd < 0) {
1202                 rc = dst_fd;
1203                 CT_ERROR(rc, "cannot open '%s' for write", dst);
1204                 goto fini;
1205         }
1206
1207         if (set_lovea) {
1208                 /* the layout cannot be allocated through .fid so we have to
1209                  * restore a layout */
1210                 rc = ct_restore_stripe(src, dst, dst_fd, lov_buf, lov_size);
1211                 if (rc < 0) {
1212                         CT_ERROR(rc, "cannot restore file striping info"
1213                                  " for '%s' from '%s'", dst, src);
1214                         err_major++;
1215                         goto fini;
1216                 }
1217         }
1218
1219         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
1220         if (rc < 0) {
1221                 CT_ERROR(rc, "cannot copy data from '%s' to '%s'",
1222                          src, dst);
1223                 err_major++;
1224                 if (ct_is_retryable(rc))
1225                         hp_flags |= HP_FLAG_RETRY;
1226                 goto fini;
1227         }
1228
1229         CT_TRACE("data restore from '%s' to '%s' done", src, dst);
1230
1231 fini:
1232         rc = ct_fini(&hcp, hai, hp_flags, rc);
1233
1234         /* object swaping is done by cdt at copy end, so close of volatile file
1235          * cannot be done before */
1236         if (!(src_fd < 0))
1237                 close(src_fd);
1238
1239         if (!(dst_fd < 0))
1240                 close(dst_fd);
1241
1242         return rc;
1243 }
1244
1245 static int ct_remove(const struct hsm_action_item *hai, const long hal_flags)
1246 {
1247         struct hsm_copyaction_private   *hcp = NULL;
1248         char                             dst[PATH_MAX], attr[PATH_MAX + 4];
1249         int                              rc;
1250
1251         rc = ct_begin(&hcp, hai);
1252         if (rc < 0)
1253                 goto fini;
1254
1255         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, &hai->hai_fid);
1256
1257         CT_TRACE("removing file '%s'", dst);
1258
1259         if (opt.o_dry_run) {
1260                 rc = 0;
1261                 goto fini;
1262         }
1263
1264         rc = unlink(dst);
1265         if (rc < 0) {
1266                 rc = -errno;
1267                 CT_ERROR(rc, "cannot unlink '%s'", dst);
1268                 err_minor++;
1269                 goto fini;
1270         }
1271
1272         snprintf(attr, sizeof(attr), "%s.lov", dst);
1273         rc = unlink(attr);
1274         if (rc < 0) {
1275                 rc = -errno;
1276                 CT_ERROR(rc, "cannot unlink '%s'", attr);
1277                 err_minor++;
1278                 goto fini;
1279         }
1280
1281 fini:
1282         rc = ct_fini(&hcp, hai, 0, rc);
1283
1284         return rc;
1285 }
1286
1287 static int ct_process_item(struct hsm_action_item *hai, const long hal_flags)
1288 {
1289         int     rc = 0;
1290
1291         if (opt.o_verbose >= LLAPI_MSG_INFO || opt.o_dry_run) {
1292                 /* Print the original path */
1293                 char            fid[128];
1294                 char            path[PATH_MAX];
1295                 long long       recno = -1;
1296                 int             linkno = 0;
1297
1298                 sprintf(fid, DFID, PFID(&hai->hai_fid));
1299                 CT_TRACE("'%s' action %s reclen %d, cookie=%#jx",
1300                          fid, hsm_copytool_action2name(hai->hai_action),
1301                          hai->hai_len, (uintmax_t)hai->hai_cookie);
1302                 rc = llapi_fid2path(opt.o_mnt, fid, path,
1303                                     sizeof(path), &recno, &linkno);
1304                 if (rc < 0)
1305                         CT_ERROR(rc, "cannot get path of FID %s", fid);
1306                 else
1307                         CT_TRACE("processing file '%s'", path);
1308         }
1309
1310         switch (hai->hai_action) {
1311         /* set err_major, minor inside these functions */
1312         case HSMA_ARCHIVE:
1313                 rc = ct_archive(hai, hal_flags);
1314                 break;
1315         case HSMA_RESTORE:
1316                 rc = ct_restore(hai, hal_flags);
1317                 break;
1318         case HSMA_REMOVE:
1319                 rc = ct_remove(hai, hal_flags);
1320                 break;
1321         case HSMA_CANCEL:
1322                 CT_TRACE("cancel not implemented for file system '%s'",
1323                          opt.o_mnt);
1324                 /* Don't report progress to coordinator for this cookie:
1325                  * the copy function will get ECANCELED when reporting
1326                  * progress. */
1327                 err_minor++;
1328                 return 0;
1329                 break;
1330         default:
1331                 rc = -EINVAL;
1332                 CT_ERROR(rc, "unknown action %d, on '%s'", hai->hai_action,
1333                          opt.o_mnt);
1334                 err_minor++;
1335                 ct_fini(NULL, hai, 0, rc);
1336         }
1337
1338         return 0;
1339 }
1340
1341 struct ct_th_data {
1342         long                     hal_flags;
1343         struct hsm_action_item  *hai;
1344 };
1345
1346 static void *ct_thread(void *data)
1347 {
1348         struct ct_th_data *cttd = data;
1349         int rc;
1350
1351         rc = ct_process_item(cttd->hai, cttd->hal_flags);
1352
1353         free(cttd->hai);
1354         free(cttd);
1355         pthread_exit((void *)(intptr_t)rc);
1356 }
1357
1358 static int ct_process_item_async(const struct hsm_action_item *hai,
1359                                  long hal_flags)
1360 {
1361         pthread_attr_t           attr;
1362         pthread_t                thread;
1363         struct ct_th_data       *data;
1364         int                      rc;
1365
1366         data = malloc(sizeof(*data));
1367         if (data == NULL)
1368                 return -ENOMEM;
1369
1370         data->hai = malloc(hai->hai_len);
1371         if (data->hai == NULL) {
1372                 free(data);
1373                 return -ENOMEM;
1374         }
1375
1376         memcpy(data->hai, hai, hai->hai_len);
1377         data->hal_flags = hal_flags;
1378
1379         rc = pthread_attr_init(&attr);
1380         if (rc != 0) {
1381                 CT_ERROR(rc, "pthread_attr_init failed for '%s' service",
1382                          opt.o_mnt);
1383                 free(data->hai);
1384                 free(data);
1385                 return -rc;
1386         }
1387
1388         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1389
1390         rc = pthread_create(&thread, &attr, ct_thread, data);
1391         if (rc != 0)
1392                 CT_ERROR(rc, "cannot create thread for '%s' service",
1393                          opt.o_mnt);
1394
1395         pthread_attr_destroy(&attr);
1396         return 0;
1397 }
1398
1399 static int ct_import_one(const char *src, const char *dst)
1400 {
1401         char            newarc[PATH_MAX];
1402         struct lu_fid   fid;
1403         struct stat     st;
1404         int             rc;
1405
1406         CT_TRACE("importing '%s' from '%s'", dst, src);
1407
1408         if (stat(src, &st) < 0) {
1409                 rc = -errno;
1410                 CT_ERROR(rc, "cannot stat '%s'", src);
1411                 return rc;
1412         }
1413
1414         if (opt.o_dry_run)
1415                 return 0;
1416
1417         rc = llapi_hsm_import(dst,
1418                               opt.o_archive_cnt ? opt.o_archive_id[0] : 0,
1419                               &st, 0, 0, 0, 0, NULL, &fid);
1420         if (rc < 0) {
1421                 CT_ERROR(rc, "cannot import '%s' from '%s'", dst, src);
1422                 return rc;
1423         }
1424
1425         ct_path_archive(newarc, sizeof(newarc), opt.o_hsm_root, &fid);
1426
1427         rc = ct_mkdir_p(newarc);
1428         if (rc < 0) {
1429                 CT_ERROR(rc, "mkdir_p '%s' failed", newarc);
1430                 err_major++;
1431                 return rc;
1432
1433         }
1434
1435         /* Lots of choices now: mv, ln, ln -s ? */
1436         rc = link(src, newarc); /* hardlink */
1437         if (rc < 0) {
1438                 rc = -errno;
1439                 CT_ERROR(rc, "cannot link '%s' to '%s'", newarc, src);
1440                 err_major++;
1441                 return rc;
1442         }
1443         CT_TRACE("imported '%s' from '%s'=='%s'", dst, newarc, src);
1444
1445         return 0;
1446 }
1447
1448 static char *path_concat(const char *dirname, const char *basename)
1449 {
1450         char    *result;
1451         int      rc;
1452
1453         rc = asprintf(&result, "%s/%s", dirname, basename);
1454         if (rc < 0)
1455                 return NULL;
1456
1457         return result;
1458 }
1459
1460 static int ct_import_fid(const struct lu_fid *import_fid)
1461 {
1462         char    fid_path[PATH_MAX];
1463         int     rc;
1464
1465         ct_path_lustre(fid_path, sizeof(fid_path), opt.o_mnt, import_fid);
1466         rc = access(fid_path, F_OK);
1467         if (rc == 0 || errno != ENOENT) {
1468                 rc = (errno == 0) ? -EEXIST : -errno;
1469                 CT_ERROR(rc, "cannot import '"DFID"'", PFID(import_fid));
1470                 return rc;
1471         }
1472
1473         ct_path_archive(fid_path, sizeof(fid_path), opt.o_hsm_root,
1474                         import_fid);
1475
1476         CT_TRACE("Resolving "DFID" to %s", PFID(import_fid), fid_path);
1477
1478         return ct_import_one(fid_path, opt.o_dst);
1479 }
1480
1481 static int ct_import_recurse(const char *relpath)
1482 {
1483         DIR             *dir;
1484         struct dirent   *ent;
1485         char            *srcpath, *newpath;
1486         struct lu_fid    import_fid;
1487         int              rc;
1488
1489         if (relpath == NULL)
1490                 return -EINVAL;
1491
1492         /* Is relpath a FID? In which case SFID should expand to three
1493          * elements. */
1494         rc = sscanf(relpath, SFID, RFID(&import_fid));
1495         if (rc == 3)
1496                 return ct_import_fid(&import_fid);
1497
1498         srcpath = path_concat(opt.o_hsm_root, relpath);
1499         if (srcpath == NULL) {
1500                 err_major++;
1501                 return -ENOMEM;
1502         }
1503
1504         dir = opendir(srcpath);
1505         if (dir == NULL) {
1506                 /* Not a dir, or error */
1507                 if (errno == ENOTDIR) {
1508                         /* Single regular file case, treat o_dst as absolute
1509                            final location. */
1510                         rc = ct_import_one(srcpath, opt.o_dst);
1511                 } else {
1512                         rc = -errno;
1513                         CT_ERROR(rc, "cannot opendir '%s'", srcpath);
1514                         err_major++;
1515                 }
1516                 free(srcpath);
1517                 return rc;
1518         }
1519         free(srcpath);
1520
1521         while ((ent = readdir(dir)) != NULL) {
1522                 if (!strcmp(ent->d_name, ".") ||
1523                     !strcmp(ent->d_name, ".."))
1524                         continue;
1525
1526                 /* New relative path */
1527                 newpath = path_concat(relpath, ent->d_name);
1528                 if (newpath == NULL) {
1529                         err_major++;
1530                         rc = -ENOMEM;
1531                         goto out;
1532                 }
1533
1534                 if (ent->d_type == DT_DIR) {
1535                         rc = ct_import_recurse(newpath);
1536                 } else {
1537                         char src[PATH_MAX];
1538                         char dst[PATH_MAX];
1539
1540                         sprintf(src, "%s/%s", opt.o_hsm_root, newpath);
1541                         sprintf(dst, "%s/%s", opt.o_dst, newpath);
1542                         /* Make the target dir in the Lustre fs */
1543                         rc = ct_mkdir_p(dst);
1544                         if (rc == 0) {
1545                                 /* Import the file */
1546                                 rc = ct_import_one(src, dst);
1547                         } else {
1548                                 CT_ERROR(rc, "ct_mkdir_p '%s' failed", dst);
1549                                 err_major++;
1550                         }
1551                 }
1552
1553                 if (rc != 0) {
1554                         CT_ERROR(rc, "cannot import '%s'", newpath);
1555                         if (err_major && opt.o_abort_on_error) {
1556                                 free(newpath);
1557                                 goto out;
1558                         }
1559                 }
1560                 free(newpath);
1561         }
1562
1563         rc = 0;
1564 out:
1565         closedir(dir);
1566         return rc;
1567 }
1568
1569 static int ct_rebind_one(const struct lu_fid *old_fid,
1570                          const struct lu_fid *new_fid)
1571 {
1572         char    src[PATH_MAX];
1573         char    dst[PATH_MAX];
1574         int     rc;
1575
1576         CT_TRACE("rebind "DFID" to "DFID, PFID(old_fid), PFID(new_fid));
1577
1578         ct_path_archive(src, sizeof(src), opt.o_hsm_root, old_fid);
1579         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, new_fid);
1580
1581         if (!opt.o_dry_run) {
1582                 char src_attr[PATH_MAX + 4];
1583                 char dst_attr[PATH_MAX + 4];
1584
1585                 ct_mkdir_p(dst);
1586                 if (rename(src, dst)) {
1587                         rc = -errno;
1588                         CT_ERROR(rc, "cannot rename '%s' to '%s'", src, dst);
1589                         return -errno;
1590                 }
1591                 /* rename lov file */
1592                 snprintf(src_attr, sizeof(src_attr), "%s.lov", src);
1593                 snprintf(dst_attr, sizeof(dst_attr), "%s.lov", dst);
1594                 if (rename(src_attr, dst_attr))
1595                         CT_ERROR(errno, "cannot rename '%s' to '%s'",
1596                                  src_attr, dst_attr);
1597
1598         }
1599         return 0;
1600 }
1601
1602 static bool fid_is_file(struct lu_fid *fid)
1603 {
1604         return fid_is_norm(fid) || fid_is_igif(fid);
1605 }
1606
1607 static bool should_ignore_line(const char *line)
1608 {
1609         int     i;
1610
1611         for (i = 0; line[i] != '\0'; i++) {
1612                 if (isspace(line[i]))
1613                         continue;
1614                 else if (line[i] == '#')
1615                         return true;
1616                 else
1617                         return false;
1618         }
1619
1620         return true;
1621 }
1622
1623 static int ct_rebind_list(const char *list)
1624 {
1625         int              rc;
1626         FILE            *filp;
1627         ssize_t          r;
1628         char            *line = NULL;
1629         size_t           line_size = 0;
1630         unsigned int     nl = 0;
1631         unsigned int     ok = 0;
1632
1633         filp = fopen(list, "r");
1634         if (filp == NULL) {
1635                 rc = -errno;
1636                 CT_ERROR(rc, "cannot open '%s'", list);
1637                 return rc;
1638         }
1639
1640         /* each line consists of 2 FID */
1641         while ((r = getline(&line, &line_size, filp)) != -1) {
1642                 struct lu_fid   old_fid;
1643                 struct lu_fid   new_fid;
1644
1645                 /* Ignore empty and commented out ('#...') lines. */
1646                 if (should_ignore_line(line))
1647                         continue;
1648
1649                 nl++;
1650
1651                 rc = sscanf(line, SFID" "SFID, RFID(&old_fid), RFID(&new_fid));
1652                 if (rc != 6 || !fid_is_file(&old_fid) ||
1653                     !fid_is_file(&new_fid)) {
1654                         CT_ERROR(EINVAL,
1655                                  "'%s' FID expected near '%s', line %u",
1656                                  list, line, nl);
1657                         err_major++;
1658                         continue;
1659                 }
1660
1661                 if (ct_rebind_one(&old_fid, &new_fid))
1662                         err_major++;
1663                 else
1664                         ok++;
1665         }
1666
1667         fclose(filp);
1668
1669         if (line)
1670                 free(line);
1671
1672         /* return 0 if all rebinds were successful */
1673         CT_TRACE("%u lines read from '%s', %u rebind successful", nl, list, ok);
1674
1675         return ok == nl ? 0 : -1;
1676 }
1677
1678 static int ct_rebind(void)
1679 {
1680         int     rc;
1681
1682         if (opt.o_dst) {
1683                 struct lu_fid old_fid;
1684                 struct lu_fid new_fid;
1685
1686                 if (sscanf(opt.o_src, SFID, RFID(&old_fid)) != 3 ||
1687                     !fid_is_file(&old_fid)) {
1688                         rc = -EINVAL;
1689                         CT_ERROR(rc, "'%s' invalid FID format", opt.o_src);
1690                         return rc;
1691                 }
1692
1693                 if (sscanf(opt.o_dst, SFID, RFID(&new_fid)) != 3 ||
1694                     !fid_is_file(&new_fid)) {
1695                         rc = -EINVAL;
1696                         CT_ERROR(rc, "'%s' invalid FID format", opt.o_dst);
1697                         return rc;
1698                 }
1699
1700                 rc = ct_rebind_one(&old_fid, &new_fid);
1701
1702                 return rc;
1703         }
1704
1705         /* o_src is a list file */
1706         rc = ct_rebind_list(opt.o_src);
1707
1708         return rc;
1709 }
1710
1711 static int ct_dir_level_max(const char *dirpath, __u16 *sub_seqmax)
1712 {
1713         DIR             *dir;
1714         int              rc;
1715         __u16            sub_seq;
1716         struct dirent *ent;
1717
1718         *sub_seqmax = 0;
1719
1720         dir = opendir(dirpath);
1721         if (dir == NULL) {
1722                 rc = -errno;
1723                 CT_ERROR(rc, "cannot open directory '%s'", opt.o_hsm_root);
1724                 return rc;
1725         }
1726
1727         do {
1728                 errno = 0;
1729                 ent = readdir(dir);
1730                 if (ent == NULL) {
1731                         /* end of directory.
1732                          * rc is 0 and seqmax contains the max value. */
1733                         rc = -errno;
1734                         if (rc)
1735                                 CT_ERROR(rc, "cannot readdir '%s'", dirpath);
1736                         goto out;
1737                 }
1738
1739                 if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
1740                         continue;
1741
1742                 if (sscanf(ent->d_name, "%hx", &sub_seq) != 1) {
1743                         CT_TRACE("'%s' has an unexpected dirname format, "
1744                                  "skip entry", ent->d_name);
1745                         continue;
1746                 }
1747                 if (sub_seq > *sub_seqmax)
1748                         *sub_seqmax = sub_seq;
1749         } while (1);
1750 out:
1751         closedir(dir);
1752         return rc;
1753 }
1754
1755 static int ct_max_sequence(void)
1756 {
1757         int     rc, i;
1758         char    path[PATH_MAX];
1759         __u64   seq = 0;
1760         __u16   subseq;
1761
1762         snprintf(path, sizeof(path), "%s", opt.o_hsm_root);
1763         /* FID sequence is stored in top-level directory names:
1764          * hsm_root/16bits (high weight)/16 bits/16 bits/16 bits (low weight).
1765          */
1766         for (i = 0; i < 4; i++) {
1767                 size_t path_len;
1768
1769                 rc = ct_dir_level_max(path, &subseq);
1770                 if (rc != 0)
1771                         return rc;
1772                 seq |= ((__u64)subseq << ((3 - i) * 16));
1773                 path_len = strlen(path);
1774                 rc = snprintf(path + path_len, sizeof(path) - path_len,
1775                               "/%04x", subseq);
1776                 if (rc >= (sizeof(path) - path_len))
1777                         return -E2BIG;
1778                 path[sizeof(path) - 1] = '\0';
1779         }
1780
1781         printf("max_sequence: %#jx\n", (uintmax_t)seq);
1782
1783         return 0;
1784 }
1785
1786 static void handler(int signal)
1787 {
1788         psignal(signal, "exiting");
1789         /* If we don't clean up upon interrupt, umount thinks there's a ref
1790          * and doesn't remove us from mtab (EINPROGRESS). The lustre client
1791          * does successfully unmount and the mount is actually gone, but the
1792          * mtab entry remains. So this just makes mtab happier. */
1793         llapi_hsm_copytool_unregister(&ctdata);
1794
1795         /* Also remove fifo upon signal as during normal/error exit */
1796         if (opt.o_event_fifo != NULL)
1797                 llapi_hsm_unregister_event_fifo(opt.o_event_fifo);
1798         _exit(1);
1799 }
1800
1801 /* Daemon waits for messages from the kernel; run it in the background. */
1802 static int ct_run(void)
1803 {
1804         struct sigaction cleanup_sigaction;
1805         int rc;
1806
1807         if (opt.o_daemonize) {
1808                 rc = daemon(1, 1);
1809                 if (rc < 0) {
1810                         rc = -errno;
1811                         CT_ERROR(rc, "cannot daemonize");
1812                         return rc;
1813                 }
1814         }
1815
1816         setbuf(stdout, NULL);
1817
1818         if (opt.o_event_fifo != NULL) {
1819                 rc = llapi_hsm_register_event_fifo(opt.o_event_fifo);
1820                 if (rc < 0) {
1821                         CT_ERROR(rc, "failed to register event fifo");
1822                         return rc;
1823                 }
1824                 llapi_error_callback_set(llapi_hsm_log_error);
1825         }
1826
1827         rc = llapi_hsm_copytool_register(&ctdata, opt.o_mnt,
1828                                          opt.o_archive_cnt,
1829                                          opt.o_archive_id, 0);
1830         if (rc < 0) {
1831                 CT_ERROR(rc, "cannot start copytool interface");
1832                 return rc;
1833         }
1834
1835         memset(&cleanup_sigaction, 0, sizeof(cleanup_sigaction));
1836         cleanup_sigaction.sa_handler = handler;
1837         sigemptyset(&cleanup_sigaction.sa_mask);
1838         sigaction(SIGINT, &cleanup_sigaction, NULL);
1839         sigaction(SIGTERM, &cleanup_sigaction, NULL);
1840
1841         while (1) {
1842                 struct hsm_action_list *hal;
1843                 struct hsm_action_item *hai;
1844                 int msgsize;
1845                 int i = 0;
1846
1847                 CT_TRACE("waiting for message from kernel");
1848
1849                 rc = llapi_hsm_copytool_recv(ctdata, &hal, &msgsize);
1850                 if (rc == -ESHUTDOWN) {
1851                         CT_TRACE("shutting down");
1852                         break;
1853                 } else if (rc < 0) {
1854                         CT_WARN("cannot receive action list: %s",
1855                                 strerror(-rc));
1856                         err_major++;
1857                         if (opt.o_abort_on_error)
1858                                 break;
1859                         else
1860                                 continue;
1861                 }
1862
1863                 CT_TRACE("copytool fs=%s archive#=%d item_count=%d",
1864                          hal->hal_fsname, hal->hal_archive_id, hal->hal_count);
1865
1866                 if (strcmp(hal->hal_fsname, fs_name) != 0) {
1867                         rc = -EINVAL;
1868                         CT_ERROR(rc, "'%s' invalid fs name, expecting: %s",
1869                                  hal->hal_fsname, fs_name);
1870                         err_major++;
1871                         if (opt.o_abort_on_error)
1872                                 break;
1873                         else
1874                                 continue;
1875                 }
1876
1877                 hai = hai_first(hal);
1878                 while (++i <= hal->hal_count) {
1879                         if ((char *)hai - (char *)hal > msgsize) {
1880                                 rc = -EPROTO;
1881                                 CT_ERROR(rc,
1882                                          "'%s' item %d past end of message!",
1883                                          opt.o_mnt, i);
1884                                 err_major++;
1885                                 break;
1886                         }
1887                         rc = ct_process_item_async(hai, hal->hal_flags);
1888                         if (rc < 0)
1889                                 CT_ERROR(rc, "'%s' item %d process",
1890                                          opt.o_mnt, i);
1891                         if (opt.o_abort_on_error && err_major)
1892                                 break;
1893                         hai = hai_next(hai);
1894                 }
1895
1896                 if (opt.o_abort_on_error && err_major)
1897                         break;
1898         }
1899
1900         llapi_hsm_copytool_unregister(&ctdata);
1901         if (opt.o_event_fifo != NULL)
1902                 llapi_hsm_unregister_event_fifo(opt.o_event_fifo);
1903
1904         return rc;
1905 }
1906
1907 static int ct_setup(void)
1908 {
1909         int     rc;
1910
1911         /* set llapi message level */
1912         llapi_msg_set_level(opt.o_verbose);
1913
1914         arc_fd = open(opt.o_hsm_root, O_RDONLY);
1915         if (arc_fd < 0) {
1916                 rc = -errno;
1917                 CT_ERROR(rc, "cannot open archive at '%s'", opt.o_hsm_root);
1918                 return rc;
1919         }
1920
1921         rc = llapi_search_fsname(opt.o_mnt, fs_name);
1922         if (rc < 0) {
1923                 CT_ERROR(rc, "cannot find a Lustre filesystem mounted at '%s'",
1924                          opt.o_mnt);
1925                 return rc;
1926         }
1927
1928         opt.o_mnt_fd = open(opt.o_mnt, O_RDONLY);
1929         if (opt.o_mnt_fd < 0) {
1930                 rc = -errno;
1931                 CT_ERROR(rc, "cannot open mount point at '%s'",
1932                          opt.o_mnt);
1933                 return rc;
1934         }
1935
1936         return rc;
1937 }
1938
1939 static int ct_cleanup(void)
1940 {
1941         int     rc;
1942
1943         if (opt.o_mnt_fd >= 0) {
1944                 rc = close(opt.o_mnt_fd);
1945                 if (rc < 0) {
1946                         rc = -errno;
1947                         CT_ERROR(rc, "cannot close mount point");
1948                         return rc;
1949                 }
1950         }
1951
1952         if (arc_fd >= 0) {
1953                 rc = close(arc_fd);
1954                 if (rc < 0) {
1955                         rc = -errno;
1956                         CT_ERROR(rc, "cannot close archive root directory");
1957                         return rc;
1958                 }
1959         }
1960
1961         return 0;
1962 }
1963
1964 int main(int argc, char **argv)
1965 {
1966         int     rc;
1967
1968         snprintf(cmd_name, sizeof(cmd_name), "%s", basename(argv[0]));
1969         rc = ct_parseopts(argc, argv);
1970         if (rc < 0) {
1971                 CT_WARN("try '%s --help' for more information", cmd_name);
1972                 return -rc;
1973         }
1974
1975         rc = ct_setup();
1976         if (rc < 0)
1977                 goto error_cleanup;
1978
1979         switch (opt.o_action) {
1980         case CA_IMPORT:
1981                 rc = ct_import_recurse(opt.o_src);
1982                 break;
1983         case CA_REBIND:
1984                 rc = ct_rebind();
1985                 break;
1986         case CA_MAXSEQ:
1987                 rc = ct_max_sequence();
1988                 break;
1989         default:
1990                 rc = ct_run();
1991                 break;
1992         }
1993
1994         if (opt.o_action != CA_MAXSEQ)
1995                 CT_TRACE("process finished, errs: %d major, %d minor,"
1996                          " rc=%d (%s)", err_major, err_minor, rc,
1997                          strerror(-rc));
1998
1999 error_cleanup:
2000         ct_cleanup();
2001
2002         return -rc;
2003 }
2004