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