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