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