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