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