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