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