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