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