Whamcloud - gitweb
baf1fac973734e03467c41f313bf3e37d1fdd0e3
[fs/lustre-release.git] / lustre / utils / lhsmtool_posix.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.htm
19  *
20  * GPL HEADER END
21  */
22 /*
23  * (C) Copyright 2012 Commissariat a l'energie atomique et aux energies
24  *     alternatives
25  *
26  */
27 /* HSM copytool program for POSIX filesystem-based HSM's.
28  *
29  * An HSM copytool daemon acts on action requests from Lustre to copy files
30  * to and from an HSM archive system. This one in particular makes regular
31  * POSIX filesystem calls to a given path, where an HSM is presumably mounted.
32  *
33  * This particular tool can also import an existing HSM archive.
34  */
35 #include <stdint.h>
36 #include <stdlib.h>
37 #include <dirent.h>
38 #include <errno.h>
39 #include <utime.h>
40 #include <sys/xattr.h>
41 #include <lustre/lustre_idl.h>
42 #include <lustre/lustreapi.h>
43
44 /* Progress reporting period */
45 #define REPORT_INTERVAL_DEFAULT 30
46 /* HSM hash subdir permissions */
47 #define DIR_PERM S_IRWXU
48 /* HSM hash file permissions */
49 #define FILE_PERM (S_IRUSR | S_IWUSR)
50
51 #define ONE_MB 0x100000
52
53 /* copytool uses a 32b bitmask field to register with kuc
54  * archive num = 0 => all
55  * archive num from 1 to 32
56  */
57 #define MAX_ARCHIVE_CNT (sizeof(__u32) * 8)
58
59 enum ct_action {
60         CA_IMPORT = 1,
61         CA_REBIND,
62         CA_MAXSEQ,
63 };
64
65 struct options {
66         int                      o_copy_attrs;
67         int                      o_daemonize;
68         int                      o_dry_run;
69         int                      o_abort_on_error;
70         int                      o_shadow_tree;
71         int                      o_verbose;
72         int                      o_copy_xattrs;
73         int                      o_archive_cnt;
74         int                      o_archive_id[MAX_ARCHIVE_CNT];
75         int                      o_report_int;
76         unsigned long long       o_bandwidth;
77         size_t                   o_chunk_size;
78         enum ct_action           o_action;
79         char                    *o_mnt;
80         char                    *o_hsm_root;
81         char                    *o_src; /* for import, or rebind */
82         char                    *o_dst; /* for import, or rebind */
83 };
84
85 /* everything else is zeroed */
86 struct options opt = {
87         .o_copy_attrs = 1,
88         .o_shadow_tree = 1,
89         .o_verbose = LLAPI_MSG_WARN,
90         .o_copy_xattrs = 1,
91         .o_report_int = REPORT_INTERVAL_DEFAULT,
92         .o_chunk_size = ONE_MB,
93 };
94
95 /* 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 %zu\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 %jd)"
526                          " failed (%s)\n",
527                          src, hai->hai_extent.offset, (intmax_t)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 %jd failed (%s)\n",
678                                  dst, (intmax_t)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         }
722
723         return 0;
724 }
725
726 static int ct_copy_xattr(const char *src, const char *dst, int src_fd,
727                          int dst_fd, bool is_restore)
728 {
729         char     list[XATTR_LIST_MAX];
730         char     value[XATTR_SIZE_MAX];
731         char    *name;
732         ssize_t  list_len;
733         int      rc;
734
735         list_len = flistxattr(src_fd, list, sizeof(list));
736         if (list_len < 0)
737                 return -errno;
738
739         name = list;
740         while (name < list + list_len) {
741                 rc = fgetxattr(src_fd, name, value, sizeof(value));
742                 if (rc < 0)
743                         return -errno;
744
745                 /* when we restore, we do not restore lustre xattr */
746                 if (!is_restore ||
747                     (strncmp(XATTR_TRUSTED_PREFIX, name,
748                              sizeof(XATTR_TRUSTED_PREFIX) - 1) != 0)) {
749                         rc = fsetxattr(dst_fd, name, value, rc, 0);
750                         CT_TRACE("'%s' fsetxattr of '%s' rc=%d (%s)\n",
751                                  dst, name, rc, strerror(errno));
752                         /* lustre.* attrs aren't supported on other FS's */
753                         if (rc < 0 && errno != EOPNOTSUPP) {
754                                 CT_ERROR("'%s' fsetxattr of '%s' failed (%s)\n",
755                                          dst, name, strerror(errno));
756                                 return -errno;
757                         }
758                 }
759                 name += strlen(name) + 1;
760         }
761
762         return 0;
763 }
764
765 static int ct_path_lustre(char *buf, int sz, const char *mnt,
766                           const lustre_fid *fid)
767 {
768         return snprintf(buf, sz, "%s/%s/fid/"DFID_NOBRACE, mnt,
769                         dot_lustre_name, PFID(fid));
770 }
771
772 static int ct_path_archive(char *buf, int sz, const char *archive_dir,
773                            const lustre_fid *fid)
774 {
775         return snprintf(buf, sz, "%s/%04x/%04x/%04x/%04x/%04x/%04x/"
776                         DFID_NOBRACE, archive_dir,
777                         (fid)->f_oid       & 0xFFFF,
778                         (fid)->f_oid >> 16 & 0xFFFF,
779                         (unsigned int)((fid)->f_seq       & 0xFFFF),
780                         (unsigned int)((fid)->f_seq >> 16 & 0xFFFF),
781                         (unsigned int)((fid)->f_seq >> 32 & 0xFFFF),
782                         (unsigned int)((fid)->f_seq >> 48 & 0xFFFF),
783                         PFID(fid));
784 }
785
786 static bool ct_is_retryable(int err)
787 {
788         return err == -ETIMEDOUT;
789 }
790
791 static int ct_begin_restore(struct hsm_copyaction_private **phcp,
792                             const struct hsm_action_item *hai,
793                             int mdt_index, int open_flags)
794 {
795         char     src[PATH_MAX];
796         int      rc;
797
798         rc = llapi_hsm_action_begin(phcp, ctdata, hai, mdt_index, open_flags,
799                                     false);
800         if (rc < 0) {
801                 ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_fid);
802                 CT_ERROR("'%s' copy start failed (%s)\n", src, strerror(-rc));
803         }
804
805         return rc;
806 }
807
808 static int ct_begin(struct hsm_copyaction_private **phcp,
809                     const struct hsm_action_item *hai)
810 {
811         /* Restore takes specific parameters. Call the same function w/ default
812          * values for all other operations. */
813         return ct_begin_restore(phcp, hai, -1, 0);
814 }
815
816 static int ct_fini(struct hsm_copyaction_private **phcp,
817                    const struct hsm_action_item *hai, int flags, int ct_rc)
818 {
819         char    lstr[PATH_MAX];
820         int     rc;
821
822         CT_TRACE("Action completed, notifying coordinator "
823                  "cookie="LPX64", FID="DFID", flags=%d err=%d\n",
824                  hai->hai_cookie, PFID(&hai->hai_fid),
825                  flags, -ct_rc);
826
827         ct_path_lustre(lstr, sizeof(lstr), opt.o_mnt, &hai->hai_fid);
828         rc = llapi_hsm_action_end(phcp, &hai->hai_extent, flags, abs(ct_rc));
829         if (rc == -ECANCELED)
830                 CT_ERROR("'%s' completed action has been canceled: "
831                          "cookie="LPX64", FID="DFID"\n", lstr, hai->hai_cookie,
832                          PFID(&hai->hai_fid));
833         else if (rc < 0)
834                 CT_ERROR("'%s' copy end failed (%s)\n", lstr, strerror(-rc));
835         else
836                 CT_TRACE("'%s' copy end ok (rc=%d)\n", lstr, rc);
837
838         return rc;
839 }
840
841 static int ct_archive(const struct hsm_action_item *hai, const long hal_flags)
842 {
843         struct hsm_copyaction_private   *hcp = NULL;
844         char                             src[PATH_MAX];
845         char                             dst[PATH_MAX];
846         int                              rc;
847         int                              rcf = 0;
848         bool                             rename_needed = false;
849         int                              ct_flags = 0;
850         int                              open_flags;
851         int                              src_fd = -1;
852         int                              dst_fd = -1;
853
854         rc = ct_begin(&hcp, hai);
855         if (rc < 0)
856                 goto fini_major;
857
858         /* we fill archive so:
859          * source = data FID
860          * destination = lustre FID
861          */
862         ct_path_lustre(src, sizeof(src), opt.o_mnt, &hai->hai_dfid);
863         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, &hai->hai_fid);
864         if (hai->hai_extent.length == -1) {
865                 /* whole file, write it to tmp location and atomically
866                  * replace old archived file */
867                 strncat(dst, "_tmp", sizeof(dst) - strlen(dst) - 1);
868                 /* we cannot rely on the same test because ct_copy_data()
869                  * updates hai_extent.length */
870                 rename_needed = true;
871         }
872
873         CT_TRACE("'%s' archived to %s\n", src, dst);
874
875         if (opt.o_dry_run) {
876                 rc = 0;
877                 goto fini_major;
878         }
879
880         rc = ct_mkdir_p(dst);
881         if (rc < 0) {
882                 CT_ERROR("'%s' mkdir_p failed (%s)\n", dst, strerror(-rc));
883                 goto fini_major;
884         }
885
886         src_fd = open(src, O_RDONLY | O_NOATIME | O_NONBLOCK | O_NOFOLLOW);
887         if (src_fd == -1) {
888                 CT_ERROR("'%s' open read failed (%s)\n", src, strerror(errno));
889                 rc = -errno;
890                 goto fini_major;
891         }
892
893         open_flags = O_WRONLY | O_NOFOLLOW | O_NONBLOCK;
894         /* If extent is specified, don't truncate an old archived copy */
895         open_flags |= ((hai->hai_extent.length == -1) ? O_TRUNC : 0) | O_CREAT;
896
897         dst_fd = open(dst, open_flags, FILE_PERM);
898         if (dst_fd == -1) {
899                 CT_ERROR("'%s' open write failed (%s)\n", dst, strerror(errno));
900                 rc = -errno;
901                 goto fini_major;
902         }
903
904         /* saving stripe is not critical */
905         rc = ct_save_stripe(src_fd, src, dst);
906         if (rc < 0)
907                 CT_ERROR("'%s' cannot save file striping info in '%s' (%s)\n",
908                          src, dst, strerror(-rc));
909
910         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
911         if (rc < 0) {
912                 CT_ERROR("'%s' data copy failed to '%s' (%s)\n",
913                          src, dst, strerror(-rc));
914                 goto fini_major;
915         }
916
917         CT_TRACE("'%s' data archived to '%s' done\n", src, dst);
918
919         /* attrs will remain on the MDS; no need to copy them, except possibly
920           for disaster recovery */
921         if (opt.o_copy_attrs) {
922                 rc = ct_copy_attr(src, dst, src_fd, dst_fd);
923                 if (rc < 0) {
924                         CT_ERROR("'%s' attr copy failed to '%s' (%s)\n",
925                                  src, dst, strerror(-rc));
926                         rcf = rc;
927                 }
928                 CT_TRACE("'%s' attr file copied to archive '%s'\n",
929                          src, dst);
930         }
931
932         /* xattrs will remain on the MDS; no need to copy them, except possibly
933          for disaster recovery */
934         if (opt.o_copy_xattrs) {
935                 rc = ct_copy_xattr(src, dst, src_fd, dst_fd, false);
936                 if (rc < 0) {
937                         CT_ERROR("'%s' xattr copy failed to '%s' (%s)\n",
938                                  src, dst, strerror(-rc));
939                         rcf = rcf ? rcf : rc;
940                 }
941                 CT_ERROR("'%s' xattr file copied to archive '%s'\n",
942                          src, dst);
943         }
944
945         if (rename_needed == true) {
946                 char     tmp_src[PATH_MAX];
947                 char     tmp_dst[PATH_MAX];
948
949                 /* atomically replace old archived file */
950                 ct_path_archive(src, sizeof(src), opt.o_hsm_root,
951                                 &hai->hai_fid);
952                 rc = rename(dst, src);
953                 if (rc < 0) {
954                         CT_ERROR("'%s' renamed to '%s' failed (%s)\n", dst, src,
955                                  strerror(errno));
956                         rc = -errno;
957                         goto fini_major;
958                 }
959                 /* rename lov file */
960                 snprintf(tmp_src, sizeof(tmp_src), "%s.lov", src);
961                 snprintf(tmp_dst, sizeof(tmp_dst), "%s.lov", dst);
962                 rc = rename(tmp_dst, tmp_src);
963                 if (rc < 0)
964                         CT_ERROR("'%s' renamed to '%s' failed (%s)\n",
965                                  tmp_dst, tmp_src, strerror(errno));
966         }
967
968         if (opt.o_shadow_tree) {
969                 /* Create a namespace of softlinks that shadows the original
970                  * Lustre namespace.  This will only be current at
971                  * time-of-archive (won't follow renames).
972                  * WARNING: release won't kill these links; a manual
973                  * cleanup of dead links would be required.
974                  */
975                 char             buf[PATH_MAX];
976                 long long        recno = -1;
977                 int              linkno = 0;
978                 char            *ptr;
979                 int              depth = 0;
980                 int              sz;
981
982                 sprintf(buf, DFID, PFID(&hai->hai_fid));
983                 sprintf(src, "%s/shadow/", opt.o_hsm_root);
984
985                 ptr = opt.o_hsm_root;
986                 while (*ptr)
987                         (*ptr++ == '/') ? depth-- : 0;
988
989                 rc = llapi_fid2path(opt.o_mnt, buf, src + strlen(src),
990                                     sizeof(src) - strlen(src), &recno, &linkno);
991                 if (rc < 0) {
992                         CT_ERROR("'%s' fid2path failed (%s)\n", buf,
993                                  strerror(-rc));
994                         rcf = rcf ? rcf : rc;
995                         goto fini_minor;
996                 }
997
998                 /* Figure out how many parent dirs to symlink back */
999                 ptr = src;
1000                 while (*ptr)
1001                         (*ptr++ == '/') ? depth++ : 0;
1002                 sprintf(buf, "..");
1003                 while (--depth > 1)
1004                         strcat(buf, "/..");
1005
1006                 ct_path_archive(dst, sizeof(dst), buf, &hai->hai_fid);
1007
1008                 if (ct_mkdir_p(src)) {
1009                         CT_ERROR("'%s' mkdir_p failed (%s)\n", src,
1010                                  strerror(errno));
1011                         rcf = rcf ? rcf : -errno;
1012                         goto fini_minor;
1013                 }
1014                 /* symlink already exists ? */
1015                 sz = readlink(src, buf, sizeof(buf));
1016                 if (sz >= 0) {
1017                         buf[sz] = '\0';
1018                         if (sz == 0 || strncmp(buf, dst, sz) != 0) {
1019                                 if (unlink(src) && errno != ENOENT) {
1020                                         CT_ERROR("'%s' unlink symlink failed "
1021                                                  "(%s)\n", src,
1022                                                  strerror(errno));
1023                                         rcf = rcf ? rcf : -errno;
1024                                         goto fini_minor;
1025                                 /* unlink old symlink done */
1026                                 CT_TRACE("'%s' remove old symlink pointing"
1027                                          " to '%s'\n", src, buf);
1028                                 }
1029                         } else {
1030                                 /* symlink already ok */
1031                                 CT_TRACE("'%s' symlink already pointing"
1032                                          " to '%s'\n", src, dst);
1033                                 rcf = 0;
1034                                 goto fini_minor;
1035                         }
1036                 }
1037                 if (symlink(dst, src)) {
1038                         CT_ERROR("'%s' symlink to '%s' failed (%s)\n", src, dst,
1039                                  strerror(errno));
1040                         rcf = rcf ? rcf : -errno;
1041                         goto fini_minor;
1042                 }
1043                 CT_TRACE("'%s' symlink to '%s' done\n", src, dst);
1044         }
1045 fini_minor:
1046         if (rcf)
1047                 err_minor++;
1048         goto out;
1049
1050
1051 fini_major:
1052         err_major++;
1053
1054         unlink(dst);
1055         if (ct_is_retryable(rc))
1056                 ct_flags |= HP_FLAG_RETRY;
1057
1058         rcf = rc;
1059
1060 out:
1061         if (!(src_fd < 0))
1062                 close(src_fd);
1063
1064         if (!(dst_fd < 0))
1065                 close(dst_fd);
1066
1067         if (hcp != NULL)
1068                 rc = ct_fini(&hcp, hai, ct_flags, rcf);
1069
1070         return rc;
1071 }
1072
1073 static int ct_restore(const struct hsm_action_item *hai, const long hal_flags)
1074 {
1075         struct hsm_copyaction_private   *hcp = NULL;
1076         char                             src[PATH_MAX];
1077         char                             dst[PATH_MAX];
1078         char                             lov_buf[XATTR_SIZE_MAX];
1079         size_t                           lov_size = sizeof(lov_buf);
1080         int                              rc;
1081         int                              flags = 0;
1082         int                              src_fd = -1;
1083         int                              dst_fd = -1;
1084         int                              mdt_index = -1; /* Not implemented */
1085         int                              open_flags = 0;
1086         bool                             set_lovea;
1087         lustre_fid                       dfid;
1088
1089         /* we fill lustre so:
1090          * source = lustre FID in the backend
1091          * destination = data FID = volatile file
1092          */
1093
1094         /* build backend file name from released file FID */
1095         ct_path_archive(src, sizeof(src), opt.o_hsm_root, &hai->hai_fid);
1096
1097         /* restore loads and sets the LOVEA w/o interpreting it to avoid
1098          * dependency on the structure format. */
1099         rc = ct_load_stripe(src, lov_buf, &lov_size);
1100         if (rc < 0) {
1101                 CT_WARN("'%s' cannot get stripe rules (%s), use default\n",
1102                         src, strerror(-rc));
1103                 set_lovea = false;
1104         } else {
1105                 open_flags |= O_LOV_DELAY_CREATE;
1106                 set_lovea = true;
1107         }
1108
1109         rc = ct_begin_restore(&hcp, hai, mdt_index, open_flags);
1110         if (rc < 0)
1111                 goto fini;
1112
1113         /* get the FID of the volatile file */
1114         rc = llapi_hsm_action_get_dfid(hcp, &dfid);
1115         if (rc < 0) {
1116                 CT_ERROR("restoring "DFID", cannot get FID of created volatile"
1117                          " file (%s)\n", PFID(&hai->hai_fid), strerror(-rc));
1118                 goto fini;
1119         }
1120
1121         /* build volatile "file name", for messages */
1122         snprintf(dst, sizeof(dst), "{VOLATILE}="DFID, PFID(&dfid));
1123
1124         CT_TRACE("'%s' restore data to '%s'\n", src, dst);
1125
1126         if (opt.o_dry_run) {
1127                 rc = 0;
1128                 goto fini;
1129         }
1130
1131         src_fd = open(src, O_RDONLY | O_NOATIME | O_NONBLOCK | O_NOFOLLOW);
1132         if (src_fd < 0) {
1133                 CT_ERROR("'%s' open for read failed (%s)\n", src,
1134                          strerror(errno));
1135                 rc = -errno;
1136                 goto fini;
1137         }
1138
1139         dst_fd = llapi_hsm_action_get_fd(hcp);
1140
1141         if (set_lovea) {
1142                 /* the layout cannot be allocated through .fid so we have to
1143                  * restore a layout */
1144                 rc = ct_restore_stripe(src, dst, dst_fd, lov_buf, lov_size);
1145                 if (rc < 0) {
1146                         CT_ERROR("'%s' cannot restore file striping info from "
1147                                  "'%s' (%s)\n", dst, src, strerror(-rc));
1148                         err_major++;
1149                         goto fini;
1150                 }
1151         }
1152
1153         rc = ct_copy_data(hcp, src, dst, src_fd, dst_fd, hai, hal_flags);
1154         if (rc < 0) {
1155                 CT_ERROR("'%s' data copy to '%s' failed (%s)\n", src, dst,
1156                          strerror(-rc));
1157                 err_major++;
1158                 if (ct_is_retryable(rc))
1159                         flags |= HP_FLAG_RETRY;
1160                 goto fini;
1161         }
1162
1163         CT_TRACE("'%s' data restore done to %s\n", src, dst);
1164
1165 fini:
1166         if (hcp != NULL)
1167                 rc = ct_fini(&hcp, hai, flags, rc);
1168
1169         /* object swaping is done by cdt at copy end, so close of volatile file
1170          * cannot be done before */
1171         if (!(src_fd < 0))
1172                 close(src_fd);
1173
1174         if (!(dst_fd < 0))
1175                 close(dst_fd);
1176
1177         return rc;
1178 }
1179
1180 static int ct_remove(const struct hsm_action_item *hai, const long hal_flags)
1181 {
1182         struct hsm_copyaction_private   *hcp = NULL;
1183         char                             dst[PATH_MAX];
1184         int                              rc;
1185
1186         rc = ct_begin(&hcp, hai);
1187         if (rc < 0)
1188                 goto fini;
1189
1190         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, &hai->hai_fid);
1191
1192         CT_TRACE("'%s' removed file\n", dst);
1193
1194         if (opt.o_dry_run) {
1195                 rc = 0;
1196                 goto fini;
1197         }
1198
1199         rc = unlink(dst);
1200         if (rc < 0) {
1201                 rc = -errno;
1202                 CT_ERROR("'%s' unlink failed (%s)\n", dst, strerror(-rc));
1203                 err_minor++;
1204                 goto fini;
1205         }
1206
1207         strncat(dst, ".lov", sizeof(dst) - strlen(dst) - 1);
1208         rc = unlink(dst);
1209         if (rc < 0) {
1210                 rc = -errno;
1211                 CT_ERROR("'%s' unlink failed (%s)\n", dst, strerror(-rc));
1212                 err_minor++;
1213                 goto fini;
1214         }
1215
1216 fini:
1217         if (hcp != NULL)
1218                 rc = ct_fini(&hcp, hai, 0, rc);
1219
1220         return rc;
1221 }
1222
1223 static int ct_report_error(const struct hsm_action_item *hai, int flags,
1224                            int errval)
1225 {
1226         struct hsm_copyaction_private   *hcp;
1227         int                              rc;
1228
1229         rc = llapi_hsm_action_begin(&hcp, ctdata, hai, -1, 0, true);
1230         if (rc < 0)
1231                 return rc;
1232
1233         rc = llapi_hsm_action_end(&hcp, &hai->hai_extent, flags, abs(errval));
1234
1235         return rc;
1236 }
1237
1238 static int ct_process_item(struct hsm_action_item *hai, const long hal_flags)
1239 {
1240         int     rc = 0;
1241
1242         if (opt.o_verbose >= LLAPI_MSG_INFO || opt.o_dry_run) {
1243                 /* Print the original path */
1244                 char            fid[128];
1245                 char            path[PATH_MAX];
1246                 long long       recno = -1;
1247                 int             linkno = 0;
1248
1249                 sprintf(fid, DFID, PFID(&hai->hai_fid));
1250                 CT_TRACE("'%s' action %s reclen %d, cookie="LPX64"\n",
1251                          fid, hsm_copytool_action2name(hai->hai_action),
1252                          hai->hai_len, hai->hai_cookie);
1253                 rc = llapi_fid2path(opt.o_mnt, fid, path,
1254                                     sizeof(path), &recno, &linkno);
1255                 if (rc < 0)
1256                         CT_ERROR("'%s' fid2path failed (%s)\n", fid,
1257                                  strerror(-rc));
1258                 else
1259                         CT_TRACE("'%s' processing file\n", path);
1260         }
1261
1262         switch (hai->hai_action) {
1263         /* set err_major, minor inside these functions */
1264         case HSMA_ARCHIVE:
1265                 rc = ct_archive(hai, hal_flags);
1266                 break;
1267         case HSMA_RESTORE:
1268                 rc = ct_restore(hai, hal_flags);
1269                 break;
1270         case HSMA_REMOVE:
1271                 rc = ct_remove(hai, hal_flags);
1272                 break;
1273         case HSMA_CANCEL:
1274                 CT_TRACE("'%s' cancel not implemented\n", opt.o_mnt);
1275                 /* Don't report progress to coordinator for this cookie:
1276                  * the copy function will get ECANCELED when reporting
1277                  * progress. */
1278                 err_minor++;
1279                 return 0;
1280                 break;
1281         default:
1282                 CT_ERROR("'%s' unknown action %d\n", opt.o_mnt,
1283                          hai->hai_action);
1284                 err_minor++;
1285                 ct_report_error(hai, 0, -EINVAL);
1286         }
1287
1288         return 0;
1289 }
1290
1291 struct ct_th_data {
1292         long                     hal_flags;
1293         struct hsm_action_item  *hai;
1294 };
1295
1296 static void *ct_thread(void *data)
1297 {
1298         struct ct_th_data *cttd = data;
1299         int rc;
1300
1301         rc = ct_process_item(cttd->hai, cttd->hal_flags);
1302
1303         free(cttd->hai);
1304         free(cttd);
1305         pthread_exit((void *)(intptr_t)rc);
1306 }
1307
1308 static int ct_process_item_async(const struct hsm_action_item *hai,
1309                                  long hal_flags)
1310 {
1311         pthread_attr_t           attr;
1312         pthread_t                thread;
1313         struct ct_th_data       *data;
1314         int                      rc;
1315
1316         data = malloc(sizeof(*data));
1317         if (data == NULL)
1318                 return -ENOMEM;
1319
1320         data->hai = malloc(hai->hai_len);
1321         if (data->hai == NULL) {
1322                 free(data);
1323                 return -ENOMEM;
1324         }
1325
1326         memcpy(data->hai, hai, hai->hai_len);
1327         data->hal_flags = hal_flags;
1328
1329         rc = pthread_attr_init(&attr);
1330         if (rc != 0) {
1331                 CT_ERROR("'%s' pthread_attr_init: %s\n", opt.o_mnt,
1332                          strerror(rc));
1333                 free(data->hai);
1334                 free(data);
1335                 return -rc;
1336         }
1337
1338         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1339
1340         rc = pthread_create(&thread, &attr, ct_thread, data);
1341         if (rc != 0)
1342                 CT_ERROR("'%s' thread create: (%s)\n", opt.o_mnt, strerror(rc));
1343
1344         pthread_attr_destroy(&attr);
1345         return 0;
1346 }
1347
1348 static int ct_import_one(const char *src, const char *dst)
1349 {
1350         char            newarc[PATH_MAX];
1351         lustre_fid      fid;
1352         struct stat     st;
1353         int             rc;
1354
1355         CT_TRACE("'%s' importing from %s\n", dst, src);
1356
1357         if (stat(src, &st) < 0) {
1358                 CT_ERROR("'%s' stat failed (%s)\n", src, strerror(errno));
1359                 return -errno;
1360         }
1361
1362         if (opt.o_dry_run)
1363                 return 0;
1364
1365         rc = llapi_hsm_import(dst,
1366                               opt.o_archive_cnt ? opt.o_archive_id[0] : 0,
1367                               &st, 0, 0, 0, 0, NULL, &fid);
1368         if (rc < 0) {
1369                 CT_ERROR("'%s' import from '%s' failed (%s)\n", dst, src,
1370                          strerror(-rc));
1371                 return -rc;
1372         }
1373
1374         ct_path_archive(newarc, sizeof(newarc), opt.o_hsm_root, &fid);
1375
1376         rc = ct_mkdir_p(newarc);
1377         if (rc < 0) {
1378                 CT_ERROR("'%s' mkdir_p failed (%s)\n", newarc, strerror(-rc));
1379                 err_major++;
1380                 return rc;
1381
1382         }
1383
1384         /* Lots of choices now: mv, ln, ln -s ? */
1385         rc = link(src, newarc); /* hardlink */
1386         if (rc < 0) {
1387                 CT_ERROR("'%s' link to '%s' failed (%s)\n", newarc, src,
1388                          strerror(errno));
1389                 err_major++;
1390                 return -errno;
1391         }
1392         CT_TRACE("'%s' imported from '%s'=='%s'\n", dst, newarc, src);
1393
1394         return 0;
1395 }
1396
1397 static char *path_concat(const char *dirname, const char *basename)
1398 {
1399         char    *result;
1400         int      dirlen = strlen(dirname);
1401
1402         result = malloc(dirlen + strlen(basename) + 2);
1403         if (result == NULL)
1404                 return NULL;
1405
1406         memcpy(result, dirname, dirlen);
1407         result[dirlen] = '/';
1408         strcpy(result + dirlen + 1, basename);
1409
1410         return result;
1411 }
1412
1413 static int ct_import_recurse(const char *relpath)
1414 {
1415         DIR             *dir;
1416         struct dirent    ent, *cookie = NULL;
1417         char            *srcpath, *newpath;
1418         int              rc;
1419
1420         if (relpath == NULL)
1421                 return -EINVAL;
1422
1423         srcpath = path_concat(opt.o_hsm_root, relpath);
1424         if (srcpath == NULL) {
1425                 err_major++;
1426                 return -ENOMEM;
1427         }
1428
1429         dir = opendir(srcpath);
1430         if (dir == NULL) {
1431                 /* Not a dir, or error */
1432                 if (errno == ENOTDIR) {
1433                         /* Single regular file case, treat o_dst as absolute
1434                            final location. */
1435                         rc = ct_import_one(srcpath, opt.o_dst);
1436                 } else {
1437                         CT_ERROR("'%s' opendir failed (%s)\n", srcpath,
1438                                  strerror(errno));
1439                         err_major++;
1440                         rc = -errno;
1441                 }
1442                 free(srcpath);
1443                 return rc;
1444         }
1445         free(srcpath);
1446
1447         while (1) {
1448                 rc = readdir_r(dir, &ent, &cookie);
1449                 if (rc != 0) {
1450                         CT_ERROR("'%s' readdir_r failed (%s)\n", relpath,
1451                                  strerror(errno));
1452                         err_major++;
1453                         rc = -errno;
1454                         goto out;
1455                 } else if ((rc == 0) && (cookie == NULL)) {
1456                         /* end of directory */
1457                         break;
1458                 }
1459
1460                 if (!strcmp(ent.d_name, ".") ||
1461                     !strcmp(ent.d_name, ".."))
1462                         continue;
1463
1464                 /* New relative path */
1465                 newpath = path_concat(relpath, ent.d_name);
1466                 if (newpath == NULL) {
1467                         err_major++;
1468                         rc = -ENOMEM;
1469                         goto out;
1470                 }
1471
1472                 if (ent.d_type == DT_DIR) {
1473                         rc = ct_import_recurse(newpath);
1474                 } else {
1475                         char src[PATH_MAX];
1476                         char dst[PATH_MAX];
1477
1478                         sprintf(src, "%s/%s", opt.o_hsm_root, newpath);
1479                         sprintf(dst, "%s/%s", opt.o_dst, newpath);
1480                         /* Make the target dir in the Lustre fs */
1481                         rc = ct_mkdir_p(dst);
1482                         if (rc == 0) {
1483                                 /* Import the file */
1484                                 rc = ct_import_one(src, dst);
1485                         } else {
1486                                 CT_ERROR("'%s' ct_mkdir_p failed (%s)\n", dst,
1487                                          strerror(-rc));
1488                                 err_major++;
1489                         }
1490                 }
1491
1492                 if (rc != 0) {
1493                         CT_ERROR("'%s' importing failed\n", newpath);
1494                         if (err_major && opt.o_abort_on_error) {
1495                                 free(newpath);
1496                                 goto out;
1497                         }
1498                 }
1499                 free(newpath);
1500         }
1501
1502         rc = 0;
1503 out:
1504         closedir(dir);
1505         return rc;
1506 }
1507
1508 static int ct_rebind_one(const lustre_fid *old_fid, const lustre_fid *new_fid)
1509 {
1510         char src[PATH_MAX];
1511         char dst[PATH_MAX];
1512
1513         CT_TRACE("rebind "DFID" to "DFID"\n", PFID(old_fid), PFID(new_fid));
1514
1515         ct_path_archive(src, sizeof(src), opt.o_hsm_root, old_fid);
1516         ct_path_archive(dst, sizeof(dst), opt.o_hsm_root, new_fid);
1517
1518         if (!opt.o_dry_run) {
1519                 ct_mkdir_p(dst);
1520                 if (rename(src, dst)) {
1521                         CT_ERROR("'%s' rename to '%s' failed (%s)\n", src, dst,
1522                                  strerror(errno));
1523                         return -errno;
1524                 }
1525                 /* rename lov file */
1526                 strncat(src, ".lov", sizeof(src) - strlen(src) - 1);
1527                 strncat(dst, ".lov", sizeof(dst) - strlen(dst) - 1);
1528                 if (rename(src, dst))
1529                         CT_ERROR("'%s' rename to '%s' failed (%s)\n", src, dst,
1530                                  strerror(errno));
1531
1532         }
1533         return 0;
1534 }
1535
1536 static bool fid_is_file(lustre_fid *fid)
1537 {
1538         return fid_is_norm(fid) || fid_is_igif(fid);
1539 }
1540
1541 static bool should_ignore_line(const char *line)
1542 {
1543         int     i;
1544
1545         for (i = 0; line[i] != '\0'; i++) {
1546                 if (isspace(line[i]))
1547                         continue;
1548                 else if (line[i] == '#')
1549                         return true;
1550                 else
1551                         return false;
1552         }
1553
1554         return true;
1555 }
1556
1557 static int ct_rebind_list(const char *list)
1558 {
1559         int              rc;
1560         FILE            *filp;
1561         ssize_t          r;
1562         char            *line = NULL;
1563         size_t           line_size = 0;
1564         unsigned int     nl = 0;
1565         unsigned int     ok = 0;
1566
1567         filp = fopen(list, "r");
1568         if (filp == NULL) {
1569                 CT_ERROR("'%s' open failed (%s)\n", list, strerror(errno));
1570                 return -errno;
1571         }
1572
1573         /* each line consists of 2 FID */
1574         while ((r = getline(&line, &line_size, filp)) != -1) {
1575                 lustre_fid      old_fid;
1576                 lustre_fid      new_fid;
1577
1578                 /* Ignore empty and commented out ('#...') lines. */
1579                 if (should_ignore_line(line))
1580                         continue;
1581
1582                 nl++;
1583
1584                 rc = sscanf(line, SFID" "SFID, RFID(&old_fid), RFID(&new_fid));
1585                 if (rc != 6 || !fid_is_file(&old_fid) ||
1586                     !fid_is_file(&new_fid)) {
1587                         CT_ERROR("'%s' FID expected near '%s', line %u\n",
1588                                  list, line, nl);
1589                         err_major++;
1590                         continue;
1591                 }
1592
1593                 if (ct_rebind_one(&old_fid, &new_fid))
1594                         err_major++;
1595                 else
1596                         ok++;
1597         }
1598
1599         fclose(filp);
1600
1601         if (line)
1602                 free(line);
1603
1604         /* return 0 if all rebinds were sucessful */
1605         CT_TRACE("'%s' %u lines read, %u rebind successful\n", list, nl, ok);
1606
1607         return ok == nl ? 0 : -1;
1608 }
1609
1610 static int ct_rebind(void)
1611 {
1612         int     rc;
1613
1614         if (opt.o_dst) {
1615                 lustre_fid      old_fid;
1616                 lustre_fid      new_fid;
1617
1618                 if (sscanf(opt.o_src, SFID, RFID(&old_fid)) != 3 ||
1619                     !fid_is_file(&old_fid)) {
1620                         CT_ERROR("'%s' invalid FID format\n", opt.o_src);
1621                         return -EINVAL;
1622                 }
1623
1624                 if (sscanf(opt.o_dst, SFID, RFID(&new_fid)) != 3 ||
1625                     !fid_is_file(&new_fid)) {
1626                         CT_ERROR("'%s' invalid FID format\n", opt.o_dst);
1627                         return -EINVAL;
1628                 }
1629
1630                 rc = ct_rebind_one(&old_fid, &new_fid);
1631
1632                 return rc;
1633         }
1634
1635         /* o_src is a list file */
1636         rc = ct_rebind_list(opt.o_src);
1637
1638         return rc;
1639 }
1640
1641 static int ct_dir_level_max(const char *dirpath, __u16 *sub_seqmax)
1642 {
1643         DIR             *dir;
1644         int              rc;
1645         __u16            sub_seq;
1646         struct dirent    ent, *cookie = NULL;
1647
1648         *sub_seqmax = 0;
1649
1650         dir = opendir(dirpath);
1651         if (dir == NULL) {
1652                 rc = -errno;
1653                 CT_ERROR("'%s' failed to open directory (%s)\n", opt.o_hsm_root,
1654                          strerror(-rc));
1655                 return rc;
1656         }
1657
1658         while ((rc = readdir_r(dir, &ent, &cookie)) == 0) {
1659                 if (cookie == NULL)
1660                         /* end of directory.
1661                          * rc is 0 and seqmax contains the max value. */
1662                         goto out;
1663
1664                 if (!strcmp(ent.d_name, ".") || !strcmp(ent.d_name, ".."))
1665                         continue;
1666
1667                 if (sscanf(ent.d_name, "%hx", &sub_seq) != 1) {
1668                         CT_TRACE("'%s' unexpected dirname format, "
1669                                  "skip entry.\n", ent.d_name);
1670                         continue;
1671                 }
1672                 if (sub_seq > *sub_seqmax)
1673                         *sub_seqmax = sub_seq;
1674         }
1675         rc = -errno;
1676         CT_ERROR("'%s' readdir_r failed (%s)\n", dirpath, strerror(-rc));
1677
1678 out:
1679         closedir(dir);
1680         return rc;
1681 }
1682
1683 static int ct_max_sequence(void)
1684 {
1685         int   rc, i;
1686         char  path[PATH_MAX];
1687         __u64 seq = 0;
1688         __u16 subseq;
1689
1690         strncpy(path, opt.o_hsm_root, sizeof(path));
1691         /* FID sequence is stored in top-level directory names:
1692          * hsm_root/16bits (high weight)/16 bits/16 bits/16 bits (low weight).
1693          */
1694         for (i = 0; i < 4; i++) {
1695                 rc = ct_dir_level_max(path, &subseq);
1696                 if (rc != 0)
1697                         return rc;
1698                 seq |= ((__u64)subseq << ((3 - i) * 16));
1699                 sprintf(path + strlen(path), "/%04x", subseq);
1700         }
1701
1702         printf("max_sequence: %016Lx\n", seq);
1703
1704         return 0;
1705 }
1706
1707 static void handler(int signal)
1708 {
1709         psignal(signal, "exiting");
1710         /* If we don't clean up upon interrupt, umount thinks there's a ref
1711          * and doesn't remove us from mtab (EINPROGRESS). The lustre client
1712          * does successfully unmount and the mount is actually gone, but the
1713          * mtab entry remains. So this just makes mtab happier. */
1714         llapi_hsm_copytool_unregister(&ctdata);
1715         _exit(1);
1716 }
1717
1718 /* Daemon waits for messages from the kernel; run it in the background. */
1719 static int ct_run(void)
1720 {
1721         int     rc;
1722
1723         if (opt.o_daemonize) {
1724                 rc = daemon(1, 1);
1725                 if (rc < 0) {
1726                         CT_ERROR("%d: cannot start as daemon (%s)", getpid(),
1727                                  strerror(errno));
1728                         return -errno;
1729                 }
1730         }
1731
1732         rc = llapi_hsm_copytool_register(&ctdata, opt.o_mnt, 0,
1733                                          opt.o_archive_cnt, opt.o_archive_id);
1734         if (rc < 0) {
1735                 CT_ERROR("%d: cannot start copytool interface: %s\n", getpid(),
1736                          strerror(-rc));
1737                 return rc;
1738         }
1739
1740         signal(SIGINT, handler);
1741         signal(SIGTERM, handler);
1742
1743         while (1) {
1744                 struct hsm_action_list  *hal;
1745                 struct hsm_action_item  *hai;
1746                 int                      msgsize;
1747                 int                      i = 0;
1748
1749                 CT_TRACE("%d: waiting for message from kernel\n", getpid());
1750
1751                 rc = llapi_hsm_copytool_recv(ctdata, &hal, &msgsize);
1752                 if (rc == -ESHUTDOWN) {
1753                         CT_TRACE("%d: shutting down", getpid());
1754                         break;
1755                 } else if (rc == -EAGAIN) {
1756                         continue; /* msg not for us */
1757                 } else if (rc < 0) {
1758                         CT_WARN("%d: message receive: (%s)\n", getpid(),
1759                                 strerror(-rc));
1760                         err_major++;
1761                         if (opt.o_abort_on_error)
1762                                 break;
1763                         else
1764                                 continue;
1765                 }
1766
1767                 CT_TRACE("%d: copytool fs=%s archive#=%d item_count=%d\n",
1768                          getpid(), hal->hal_fsname, hal->hal_archive_id,
1769                          hal->hal_count);
1770
1771                 if (strcmp(hal->hal_fsname, fs_name) != 0) {
1772                         CT_ERROR("'%s' invalid fs name, expecting: %s\n",
1773                                  hal->hal_fsname, fs_name);
1774                         err_major++;
1775                         if (opt.o_abort_on_error)
1776                                 break;
1777                         else
1778                                 continue;
1779                 }
1780
1781                 hai = hai_first(hal);
1782                 while (++i <= hal->hal_count) {
1783                         if ((char *)hai - (char *)hal > msgsize) {
1784                                 CT_ERROR("'%s' item %d past end of message!\n",
1785                                          opt.o_mnt, i);
1786                                 err_major++;
1787                                 rc = -EPROTO;
1788                                 break;
1789                         }
1790                         rc = ct_process_item_async(hai, hal->hal_flags);
1791                         if (rc < 0)
1792                                 CT_ERROR("'%s' item %d process err: %s\n",
1793                                          opt.o_mnt, i, strerror(-rc));
1794                         if (opt.o_abort_on_error && err_major)
1795                                 break;
1796                         hai = hai_next(hai);
1797                 }
1798
1799                 llapi_hsm_action_list_free(&hal);
1800
1801                 if (opt.o_abort_on_error && err_major)
1802                         break;
1803         }
1804
1805         llapi_hsm_copytool_unregister(&ctdata);
1806
1807         return rc;
1808 }
1809
1810 static int ct_setup(void)
1811 {
1812         int     rc;
1813
1814         /* set llapi message level */
1815         llapi_msg_set_level(opt.o_verbose);
1816
1817         arc_fd = open(opt.o_hsm_root, O_DIRECTORY);
1818         if (arc_fd < 0) {
1819                 CT_ERROR("cannot open archive at '%s': %s\n", opt.o_hsm_root,
1820                          strerror(errno));
1821                 return -errno;
1822         }
1823
1824         rc = llapi_search_fsname(opt.o_mnt, fs_name);
1825         if (rc < 0) {
1826                 CT_ERROR("cannot find a Lustre filesystem mounted at: %s\n",
1827                          opt.o_mnt);
1828                 return -rc;
1829         }
1830
1831         return rc;
1832 }
1833
1834 static int ct_cleanup(void)
1835 {
1836         if (arc_fd < 0)
1837                 return 0;
1838
1839         if (close(arc_fd) < 0) {
1840                 CT_ERROR("cannot close archive: %s.\n", strerror(errno));
1841                 return -errno;
1842         }
1843
1844         return 0;
1845 }
1846
1847 int main(int argc, char **argv)
1848 {
1849         int     rc;
1850
1851         strncpy(cmd_name, basename(argv[0]), sizeof(cmd_name));
1852         rc = ct_parseopts(argc, argv);
1853         if (rc < 0) {
1854                 CT_ERROR("try '%s --help' for more information.\n", cmd_name);
1855                 return -rc;
1856         }
1857
1858         ct_setup();
1859
1860         switch (opt.o_action) {
1861         case CA_IMPORT:
1862                 rc = ct_import_recurse(opt.o_src);
1863                 break;
1864         case CA_REBIND:
1865                 rc = ct_rebind();
1866                 break;
1867         case CA_MAXSEQ:
1868                 rc = ct_max_sequence();
1869                 break;
1870         default:
1871                 rc = ct_run();
1872                 break;
1873         }
1874
1875         if (opt.o_action != CA_MAXSEQ)
1876                 CT_TRACE("%s(%d) finished, errs: %d major, %d minor, "
1877                          "rc=%d (%s)\n", argv[0], getpid(), err_major,
1878                          err_minor, rc, strerror(-rc));
1879
1880         ct_cleanup();
1881
1882         return -rc;
1883 }
1884