Whamcloud - gitweb
LU-5030 util: migrate liblustreapi to use cfs_get_paths()
[fs/lustre-release.git] / lustre / utils / liblustreapi_hsm.c
1 /*
2  * LGPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * (C) Copyright 2012 Commissariat a l'energie atomique et aux energies
7  *     alternatives
8  *
9  * Copyright (c) 2013, 2015, Intel Corporation.
10  *
11  * All rights reserved. This program and the accompanying materials
12  * are made available under the terms of the GNU Lesser General Public License
13  * (LGPL) version 2.1 or (at your discretion) any later version.
14  * (LGPL) version 2.1 accompanies this distribution, and is available at
15  * http://www.gnu.org/licenses/lgpl-2.1.html
16  *
17  * This library is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20  * Lesser General Public License for more details.
21  *
22  * LGPL HEADER END
23  */
24 /*
25  * lustre/utils/liblustreapi_hsm.c
26  *
27  * lustreapi library for hsm calls
28  *
29  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
30  * Author: JC Lafoucriere <jacques-charles.lafoucriere@cea.fr>
31  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
32  * Author: Henri Doreau <henri.doreau@cea.fr>
33  */
34
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <stddef.h>
39 #include <sys/ioctl.h>
40 #include <unistd.h>
41 #include <malloc.h>
42 #include <errno.h>
43 #include <dirent.h>
44 #include <stdarg.h>
45 #include <sys/stat.h>
46 #include <sys/time.h>
47 #include <sys/types.h>
48 #include <utime.h>
49 #include <sys/syscall.h>
50 #include <fnmatch.h>
51 #include <signal.h>
52 #ifdef HAVE_LINUX_UNISTD_H
53 #include <linux/unistd.h>
54 #else
55 #include <unistd.h>
56 #endif
57
58 #include <lnet/lnetctl.h>
59 #include <lustre/lustre_idl.h>
60 #include <lustre/lustreapi.h>
61 #include "lustreapi_internal.h"
62
63 #define OPEN_BY_FID_PATH dot_lustre_name"/fid"
64
65 /****** HSM Copytool API ********/
66 #define CT_PRIV_MAGIC 0xC0BE2001
67 struct hsm_copytool_private {
68         int                      magic;
69         char                    *mnt;
70         struct kuc_hdr          *kuch;
71         int                      mnt_fd;
72         int                      open_by_fid_fd;
73         struct lustre_kernelcomm kuc;
74         __u32                    archives;
75 };
76
77 #define CP_PRIV_MAGIC 0x19880429
78 struct hsm_copyaction_private {
79         __u32                                    magic;
80         __s32                                    data_fd;
81         const struct hsm_copytool_private       *ct_priv;
82         struct hsm_copy                          copy;
83         lstat_t                                  stat;
84 };
85
86 enum ct_progress_type {
87         CT_START        = 0,
88         CT_RUNNING      = 50,
89         CT_FINISH       = 100,
90         CT_CANCEL       = 150,
91         CT_ERROR        = 175
92 };
93
94 enum ct_event {
95         CT_REGISTER             = 1,
96         CT_UNREGISTER           = 2,
97         CT_ARCHIVE_START        = HSMA_ARCHIVE,
98         CT_ARCHIVE_RUNNING      = HSMA_ARCHIVE + CT_RUNNING,
99         CT_ARCHIVE_FINISH       = HSMA_ARCHIVE + CT_FINISH,
100         CT_ARCHIVE_CANCEL       = HSMA_ARCHIVE + CT_CANCEL,
101         CT_ARCHIVE_ERROR        = HSMA_ARCHIVE + CT_ERROR,
102         CT_RESTORE_START        = HSMA_RESTORE,
103         CT_RESTORE_RUNNING      = HSMA_RESTORE + CT_RUNNING,
104         CT_RESTORE_FINISH       = HSMA_RESTORE + CT_FINISH,
105         CT_RESTORE_CANCEL       = HSMA_RESTORE + CT_CANCEL,
106         CT_RESTORE_ERROR        = HSMA_RESTORE + CT_ERROR,
107         CT_REMOVE_START         = HSMA_REMOVE,
108         CT_REMOVE_RUNNING       = HSMA_REMOVE + CT_RUNNING,
109         CT_REMOVE_FINISH        = HSMA_REMOVE + CT_FINISH,
110         CT_REMOVE_CANCEL        = HSMA_REMOVE + CT_CANCEL,
111         CT_REMOVE_ERROR         = HSMA_REMOVE + CT_ERROR,
112         CT_EVENT_MAX
113 };
114
115 /* initialized in llapi_hsm_register_event_fifo() */
116 static int llapi_hsm_event_fd = -1;
117 static bool created_hsm_event_fifo;
118
119 static inline const char *llapi_hsm_ct_ev2str(int type)
120 {
121         switch (type) {
122         case CT_REGISTER:
123                 return "REGISTER";
124         case CT_UNREGISTER:
125                 return "UNREGISTER";
126         case CT_ARCHIVE_START:
127                 return "ARCHIVE_START";
128         case CT_ARCHIVE_RUNNING:
129                 return "ARCHIVE_RUNNING";
130         case CT_ARCHIVE_FINISH:
131                 return "ARCHIVE_FINISH";
132         case CT_ARCHIVE_CANCEL:
133                 return "ARCHIVE_CANCEL";
134         case CT_ARCHIVE_ERROR:
135                 return "ARCHIVE_ERROR";
136         case CT_RESTORE_START:
137                 return "RESTORE_START";
138         case CT_RESTORE_RUNNING:
139                 return "RESTORE_RUNNING";
140         case CT_RESTORE_FINISH:
141                 return "RESTORE_FINISH";
142         case CT_RESTORE_CANCEL:
143                 return "RESTORE_CANCEL";
144         case CT_RESTORE_ERROR:
145                 return "RESTORE_ERROR";
146         case CT_REMOVE_START:
147                 return "REMOVE_START";
148         case CT_REMOVE_RUNNING:
149                 return "REMOVE_RUNNING";
150         case CT_REMOVE_FINISH:
151                 return "REMOVE_FINISH";
152         case CT_REMOVE_CANCEL:
153                 return "REMOVE_CANCEL";
154         case CT_REMOVE_ERROR:
155                 return "REMOVE_ERROR";
156         default:
157                 llapi_err_noerrno(LLAPI_MSG_ERROR,
158                                   "Unknown event type: %d", type);
159                 return NULL;
160         }
161 }
162
163 /**
164  * Writes a JSON event to the monitor FIFO. Noop if no FIFO has been
165  * registered.
166  *
167  * \param event              A list of llapi_json_items comprising a
168  *                           single JSON-formatted event.
169  *
170  * \retval 0 on success.
171  * \retval -errno on error.
172  */
173 static int llapi_hsm_write_json_event(struct llapi_json_item_list **event)
174 {
175         int                             rc;
176         char                            time_string[40];
177         char                            json_buf[PIPE_BUF];
178         FILE                            *buf_file;
179         time_t                          event_time = time(0);
180         struct tm                       time_components;
181         struct llapi_json_item_list     *json_items;
182
183         /* Noop unless the event fd was initialized */
184         if (llapi_hsm_event_fd < 0)
185                 return 0;
186
187         if (event == NULL || *event == NULL)
188                 return -EINVAL;
189
190         json_items = *event;
191
192         localtime_r(&event_time, &time_components);
193
194         if (strftime(time_string, sizeof(time_string), "%Y-%m-%d %T %z",
195                      &time_components) == 0) {
196                 rc = -EINVAL;
197                 llapi_error(LLAPI_MSG_ERROR, rc, "strftime() failed");
198                 return rc;
199         }
200
201         rc = llapi_json_add_item(&json_items, "event_time", LLAPI_JSON_STRING,
202                                  time_string);
203         if (rc < 0) {
204                 llapi_error(LLAPI_MSG_ERROR, -rc, "error in "
205                             "llapi_json_add_item()");
206                 return rc;
207         }
208
209         buf_file = fmemopen(json_buf, sizeof(json_buf), "w");
210         if (buf_file == NULL)
211                 return -errno;
212
213         rc = llapi_json_write_list(event, buf_file);
214         if (rc < 0) {
215                 fclose(buf_file);
216                 return rc;
217         }
218
219         fclose(buf_file);
220
221         if (write(llapi_hsm_event_fd, json_buf, strlen(json_buf)) < 0) {
222                 /* Ignore write failures due to missing reader. */
223                 if (errno != EPIPE)
224                         return -errno;
225         }
226
227         return 0;
228 }
229
230 /**
231  * Hook for llapi_hsm_copytool_register and llapi_hsm_copytool_unregister
232  * to generate JSON events suitable for consumption by a copytool
233  * monitoring process.
234  *
235  * \param priv               Opaque private control structure.
236  * \param event_type         The type of event (register or unregister).
237  *
238  * \retval 0 on success.
239  * \retval -errno on error.
240  */
241 static int llapi_hsm_log_ct_registration(struct hsm_copytool_private **priv,
242                                          __u32 event_type)
243 {
244         int                             rc;
245         char                            agent_uuid[UUID_MAX];
246         struct hsm_copytool_private     *ct;
247         struct llapi_json_item_list     *json_items;
248
249         /* Noop unless the event fd was initialized */
250         if (llapi_hsm_event_fd < 0)
251                 return 0;
252
253         if (priv == NULL || *priv == NULL)
254                 return -EINVAL;
255
256         ct = *priv;
257         if (ct->magic != CT_PRIV_MAGIC)
258                 return -EINVAL;
259
260         if (event_type != CT_REGISTER && event_type != CT_UNREGISTER)
261                 return -EINVAL;
262
263         rc = llapi_json_init_list(&json_items);
264         if (rc < 0)
265                 goto err;
266
267         rc = llapi_get_agent_uuid(ct->mnt, agent_uuid, sizeof(agent_uuid));
268         if (rc < 0)
269                 goto err;
270         llapi_chomp_string(agent_uuid);
271
272         rc = llapi_json_add_item(&json_items, "uuid", LLAPI_JSON_STRING,
273                                  agent_uuid);
274         if (rc < 0)
275                 goto err;
276
277         rc = llapi_json_add_item(&json_items, "mount_point", LLAPI_JSON_STRING,
278                                  ct->mnt);
279         if (rc < 0)
280                 goto err;
281
282         rc = llapi_json_add_item(&json_items, "archive", LLAPI_JSON_INTEGER,
283                                  &ct->archives);
284         if (rc < 0)
285                 goto err;
286
287         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
288                                  (char *)llapi_hsm_ct_ev2str(event_type));
289         if (rc < 0)
290                 goto err;
291
292         rc = llapi_hsm_write_json_event(&json_items);
293         if (rc < 0)
294                 goto err;
295
296         goto out_free;
297
298 err:
299         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
300                     "llapi_hsm_log_ct_registration()");
301
302 out_free:
303         if (json_items != NULL)
304                 llapi_json_destroy_list(&json_items);
305
306         return rc;
307 }
308
309 /**
310  * Given a copytool progress update, construct a JSON event suitable for
311  * consumption by a copytool monitoring process.
312  *
313  * Examples of various events generated here and written by
314  * llapi_hsm_write_json_event:
315  *
316  * Copytool registration and deregistration:
317  * {"event_time": "2014-02-26 14:58:01 -0500", "event_type": "REGISTER",
318  *  "archive": 0, "mount_point": "/mnt/lustre",
319  *  "uuid": "80379a60-1f8a-743f-daf2-307cde793ec2"}
320  * {"event_time": "2014-02-26 14:58:01 -0500", "event_type": "UNREGISTER",
321  *  "archive": 0, "mount_point": "/mnt/lustre",
322  *  "uuid": "80379a60-1f8a-743f-daf2-307cde793ec2"}
323  *
324  * An archive action, start to completion:
325  * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "ARCHIVE_START",
326  *  "total_bytes": 0, "lustre_path": "d71.sanity-hsm/f71.sanity-hsm",
327  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
328  * {"event_time": "2014-02-26 14:50:18 -0500", "event_type": "ARCHIVE_RUNNING",
329  *  "current_bytes": 5242880, "total_bytes": 39000000,
330  *  "lustre_path": "d71.sanity-hsm/f71.sanity-hsm",
331  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
332  * {"event_time": "2014-02-26 14:50:50 -0500", "event_type": "ARCHIVE_FINISH",
333  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
334  *
335  * A log message:
336  * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "LOGGED_MESSAGE",
337  *  "level": "INFO",
338  *  "message": "lhsmtool_posix[42]: copytool fs=lustre archive#=2 item_count=1"}
339  *
340  * \param hcp                Opaque action handle returned by
341  *                           llapi_hsm_action_start.
342  * \param hai                The hsm_action_item describing the request.
343  * \param progress_type      The ct_progress_type describing the update.
344  * \param total              The total expected bytes for the request.
345  * \param current            The current copied byte count for the request.
346  *
347  * \retval 0 on success.
348  * \retval -errno on error.
349  */
350 static int llapi_hsm_log_ct_progress(struct hsm_copyaction_private **phcp,
351                                      const struct hsm_action_item *hai,
352                                      __u32 progress_type,
353                                      __u64 total, __u64 current)
354 {
355         int                             rc;
356         int                             linkno = 0;
357         long long                       recno = -1;
358         char                            lustre_path[PATH_MAX];
359         char                            strfid[FID_NOBRACE_LEN + 1];
360         struct hsm_copyaction_private   *hcp;
361         struct llapi_json_item_list     *json_items;
362
363         /* Noop unless the event fd was initialized */
364         if (llapi_hsm_event_fd < 0)
365                 return 0;
366
367         if (phcp == NULL || *phcp == NULL)
368                 return -EINVAL;
369
370         hcp = *phcp;
371
372         rc = llapi_json_init_list(&json_items);
373         if (rc < 0)
374                 goto err;
375
376         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(&hai->hai_dfid));
377         rc = llapi_json_add_item(&json_items, "data_fid",
378                                  LLAPI_JSON_STRING, strfid);
379         if (rc < 0)
380                 goto err;
381
382         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(&hai->hai_fid));
383         rc = llapi_json_add_item(&json_items, "source_fid",
384                                  LLAPI_JSON_STRING, strfid);
385         if (rc < 0)
386                 goto err;
387
388         if (hcp->copy.hc_errval == ECANCELED) {
389                 progress_type = CT_CANCEL;
390                 goto cancel;
391         }
392
393         if (hcp->copy.hc_errval != 0) {
394                 progress_type = CT_ERROR;
395
396                 rc = llapi_json_add_item(&json_items, "errno",
397                                          LLAPI_JSON_INTEGER,
398                                          &hcp->copy.hc_errval);
399                 if (rc < 0)
400                         goto err;
401
402                 rc = llapi_json_add_item(&json_items, "error",
403                                          LLAPI_JSON_STRING,
404                                          strerror(hcp->copy.hc_errval));
405                 if (rc < 0)
406                         goto err;
407
408                 goto cancel;
409         }
410
411         /* lustre_path isn't available after a restore completes */
412         /* total_bytes isn't available after a restore or archive completes */
413         if (progress_type != CT_FINISH) {
414                 rc = llapi_fid2path(hcp->ct_priv->mnt, strfid, lustre_path,
415                                     sizeof(lustre_path), &recno, &linkno);
416                 if (rc < 0)
417                         goto err;
418
419                 rc = llapi_json_add_item(&json_items, "lustre_path",
420                                          LLAPI_JSON_STRING, lustre_path);
421                 if (rc < 0)
422                         goto err;
423
424                 rc = llapi_json_add_item(&json_items, "total_bytes",
425                                          LLAPI_JSON_BIGNUM, &total);
426                 if (rc < 0)
427                         goto err;
428         }
429
430         if (progress_type == CT_RUNNING)
431                 rc = llapi_json_add_item(&json_items, "current_bytes",
432                                          LLAPI_JSON_BIGNUM, &current);
433                 if (rc < 0)
434                         goto err;
435
436 cancel:
437         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
438                                  (char *)llapi_hsm_ct_ev2str(hai->hai_action +
439                                                              progress_type));
440         if (rc < 0)
441                 goto err;
442
443         rc = llapi_hsm_write_json_event(&json_items);
444         if (rc < 0)
445                 goto err;
446
447         goto out_free;
448
449 err:
450         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
451                     "llapi_hsm_log_ct_progress()");
452
453 out_free:
454         if (json_items != NULL)
455                 llapi_json_destroy_list(&json_items);
456
457         return rc;
458 }
459
460 /**
461  * Given a path to a FIFO, create a filehandle for nonblocking writes to it.
462  * Intended to be used for copytool monitoring processes that read an
463  * event stream from the FIFO. Events written in the absence of a reader
464  * are lost.
465  *
466  * \param path               Path to monitor FIFO.
467  *
468  * \retval 0 on success.
469  * \retval -errno on error.
470  */
471 int llapi_hsm_register_event_fifo(const char *path)
472 {
473         int read_fd;
474         struct stat statbuf;
475
476         /* Create the FIFO if necessary. */
477         if ((mkfifo(path, 0644) < 0) && (errno != EEXIST)) {
478                 llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed", path);
479                 return -errno;
480         }
481         if (errno == EEXIST) {
482                 if (stat(path, &statbuf) < 0) {
483                         llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed",
484                                     path);
485                         return -errno;
486                 }
487                 if (!S_ISFIFO(statbuf.st_mode) ||
488                     ((statbuf.st_mode & 0777) != 0644)) {
489                         llapi_error(LLAPI_MSG_ERROR, errno, "%s exists but is "
490                                     "not a pipe or has a wrong mode", path);
491                         return -errno;
492                 }
493         } else {
494                 created_hsm_event_fifo = true;
495         }
496
497         /* Open the FIFO for read so that the subsequent open for write
498          * doesn't immediately fail. */
499         read_fd = open(path, O_RDONLY | O_NONBLOCK);
500         if (read_fd < 0) {
501                 llapi_error(LLAPI_MSG_ERROR, errno,
502                             "cannot open(%s) for read", path);
503                 return -errno;
504         }
505
506         /* Open the FIFO for writes, but don't block on waiting
507          * for a reader. */
508         llapi_hsm_event_fd = open(path, O_WRONLY | O_NONBLOCK);
509         if (llapi_hsm_event_fd < 0) {
510                 llapi_error(LLAPI_MSG_ERROR, errno,
511                             "cannot open(%s) for write", path);
512                 return -errno;
513         }
514
515         /* Now close the reader. An external monitoring process can
516          * now open the FIFO for reads. If no reader comes along the
517          * events are lost. NOTE: Only one reader at a time! */
518         close(read_fd);
519
520         /* Ignore SIGPIPEs -- can occur if the reader goes away. */
521         signal(SIGPIPE, SIG_IGN);
522
523         return 0;
524 }
525
526 /**
527  * Given a path to a FIFO, close its filehandle and delete the FIFO.
528  *
529  * \param path               Path to monitor FIFO.
530  *
531  * \retval 0 on success.
532  * \retval -errno on error.
533  */
534 int llapi_hsm_unregister_event_fifo(const char *path)
535 {
536         /* Noop unless the event fd was initialized */
537         if (llapi_hsm_event_fd < 0)
538                 return 0;
539
540         if (close(llapi_hsm_event_fd) < 0)
541                 return -errno;
542
543         if (created_hsm_event_fifo) {
544                 unlink(path);
545                 created_hsm_event_fifo = false;
546         }
547
548         llapi_hsm_event_fd = -1;
549
550         return 0;
551 }
552
553 /**
554  * Custom logging callback to be used when a monitoring FIFO has been
555  * registered. Formats log entries as JSON events suitable for
556  * consumption by a copytool monitoring process.
557  *
558  * \param level              The message loglevel.
559  * \param _rc                The returncode associated with the message.
560  * \param fmt                The message format string.
561  * \param args               Arguments to be formatted by the format string.
562  *
563  * \retval None.
564  */
565 void llapi_hsm_log_error(enum llapi_message_level level, int _rc,
566                          const char *fmt, va_list args)
567 {
568         int                             rc;
569         int                             msg_len;
570         int                             real_level;
571         char                            *msg = NULL;
572         va_list                         args2;
573         struct llapi_json_item_list     *json_items;
574
575         /* Noop unless the event fd was initialized */
576         if (llapi_hsm_event_fd < 0)
577                 return;
578
579         rc = llapi_json_init_list(&json_items);
580         if (rc < 0)
581                 goto err;
582
583         if ((level & LLAPI_MSG_NO_ERRNO) == 0) {
584                 rc = llapi_json_add_item(&json_items, "errno",
585                                          LLAPI_JSON_INTEGER,
586                                          &_rc);
587                 if (rc < 0)
588                         goto err;
589
590                 rc = llapi_json_add_item(&json_items, "error",
591                                          LLAPI_JSON_STRING,
592                                          strerror(abs(_rc)));
593                 if (rc < 0)
594                         goto err;
595         }
596
597         va_copy(args2, args);
598         msg_len = vsnprintf(NULL, 0, fmt, args2) + 1;
599         va_end(args2);
600         if (msg_len >= 0) {
601                 msg = (char *) alloca(msg_len);
602                 if (msg == NULL) {
603                         rc = -ENOMEM;
604                         goto err;
605                 }
606
607                 rc = vsnprintf(msg, msg_len, fmt, args);
608                 if (rc < 0)
609                         goto err;
610
611                 rc = llapi_json_add_item(&json_items, "message",
612                                          LLAPI_JSON_STRING,
613                                          msg);
614                 if (rc < 0)
615                         goto err;
616         } else {
617                 rc = llapi_json_add_item(&json_items, "message",
618                                          LLAPI_JSON_STRING,
619                                          "INTERNAL ERROR: message failed");
620                 if (rc < 0)
621                         goto err;
622         }
623
624         real_level = level & LLAPI_MSG_NO_ERRNO;
625         real_level = real_level > 0 ? level - LLAPI_MSG_NO_ERRNO : level;
626
627         rc = llapi_json_add_item(&json_items, "level", LLAPI_JSON_STRING,
628                                  (void *)llapi_msg_level2str(real_level));
629         if (rc < 0)
630                 goto err;
631
632         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
633                                  "LOGGED_MESSAGE");
634         if (rc < 0)
635                 goto err;
636
637         rc = llapi_hsm_write_json_event(&json_items);
638         if (rc < 0)
639                 goto err;
640
641         goto out_free;
642
643 err:
644         /* Write directly to stderr to avoid llapi_error, which now
645          * emits JSON event messages. */
646         fprintf(stderr, "\nFATAL ERROR IN llapi_hsm_log_error(): rc %d,", rc);
647
648 out_free:
649         if (json_items != NULL)
650                 llapi_json_destroy_list(&json_items);
651
652         return;
653 }
654
655 /** Register a copytool
656  * \param[out] priv             Opaque private control structure
657  * \param mnt                   Lustre filesystem mount point
658  * \param archive_count         Number of valid archive IDs in \a archives
659  * \param archives              Which archive numbers this copytool is
660  *                              responsible for
661  * \param rfd_flags             flags applied to read fd of pipe
662  *                              (e.g. O_NONBLOCK)
663  *
664  * \retval 0 on success.
665  * \retval -errno on error.
666  */
667 int llapi_hsm_copytool_register(struct hsm_copytool_private **priv,
668                                 const char *mnt, int archive_count,
669                                 int *archives, int rfd_flags)
670 {
671         struct hsm_copytool_private     *ct;
672         int                              rc;
673
674         if (archive_count > 0 && archives == NULL) {
675                 llapi_err_noerrno(LLAPI_MSG_ERROR,
676                                   "NULL archive numbers");
677                 return -EINVAL;
678         }
679
680         if (archive_count > LL_HSM_MAX_ARCHIVE) {
681                 llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when maximum "
682                                   "of %zu archives supported", archive_count,
683                                   LL_HSM_MAX_ARCHIVE);
684                 return -EINVAL;
685         }
686
687         ct = calloc(1, sizeof(*ct));
688         if (ct == NULL)
689                 return -ENOMEM;
690
691         ct->magic = CT_PRIV_MAGIC;
692         ct->mnt_fd = -1;
693         ct->open_by_fid_fd = -1;
694         ct->kuc.lk_rfd = LK_NOFD;
695         ct->kuc.lk_wfd = LK_NOFD;
696
697         ct->mnt = strdup(mnt);
698         if (ct->mnt == NULL) {
699                 rc = -ENOMEM;
700                 goto out_err;
701         }
702
703         ct->kuch = malloc(HAL_MAXSIZE + sizeof(*ct->kuch));
704         if (ct->kuch == NULL) {
705                 rc = -ENOMEM;
706                 goto out_err;
707         }
708
709         ct->mnt_fd = open(ct->mnt, O_RDONLY);
710         if (ct->mnt_fd < 0) {
711                 rc = -errno;
712                 goto out_err;
713         }
714
715         ct->open_by_fid_fd = openat(ct->mnt_fd, OPEN_BY_FID_PATH, O_RDONLY);
716         if (ct->open_by_fid_fd < 0) {
717                 rc = -errno;
718                 goto out_err;
719         }
720
721         /* no archives specified means "match all". */
722         ct->archives = 0;
723         for (rc = 0; rc < archive_count; rc++) {
724                 if ((archives[rc] > LL_HSM_MAX_ARCHIVE) || (archives[rc] < 0)) {
725                         llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when "
726                                           "archive id [0 - %zu] is supported",
727                                           archives[rc], LL_HSM_MAX_ARCHIVE);
728                         rc = -EINVAL;
729                         goto out_err;
730                 }
731                 /* in the list we have an all archive wildcard
732                  * so move to all archives mode
733                  */
734                 if (archives[rc] == 0) {
735                         ct->archives = 0;
736                         archive_count = 0;
737                         break;
738                 }
739                 ct->archives |= (1 << (archives[rc] - 1));
740         }
741
742         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM, rfd_flags);
743         if (rc < 0)
744                 goto out_err;
745
746         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
747         ct->kuc.lk_data = ct->archives;
748         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, &ct->kuc);
749         if (rc < 0) {
750                 rc = -errno;
751                 llapi_error(LLAPI_MSG_ERROR, rc,
752                             "cannot start copytool on '%s'", mnt);
753                 goto out_kuc;
754         }
755
756         llapi_hsm_log_ct_registration(&ct, CT_REGISTER);
757
758         /* Only the kernel reference keeps the write side open */
759         close(ct->kuc.lk_wfd);
760         ct->kuc.lk_wfd = LK_NOFD;
761         *priv = ct;
762
763         return 0;
764
765 out_kuc:
766         /* cleanup the kuc channel */
767         libcfs_ukuc_stop(&ct->kuc);
768
769 out_err:
770         if (!(ct->mnt_fd < 0))
771                 close(ct->mnt_fd);
772
773         if (!(ct->open_by_fid_fd < 0))
774                 close(ct->open_by_fid_fd);
775
776         free(ct->mnt);
777
778         free(ct->kuch);
779
780         free(ct);
781
782         return rc;
783 }
784
785 /** Deregister a copytool
786  * Note: under Linux, until llapi_hsm_copytool_unregister is called
787  * (or the program is killed), the libcfs module will be referenced
788  * and unremovable, even after Lustre services stop.
789  */
790 int llapi_hsm_copytool_unregister(struct hsm_copytool_private **priv)
791 {
792         struct hsm_copytool_private *ct;
793
794         if (priv == NULL || *priv == NULL)
795                 return -EINVAL;
796
797         ct = *priv;
798         if (ct->magic != CT_PRIV_MAGIC)
799                 return -EINVAL;
800
801         /* Tell the kernel to stop sending us messages */
802         ct->kuc.lk_flags = LK_FLG_STOP;
803         ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, &ct->kuc);
804
805         /* Shut down the kernelcomms */
806         libcfs_ukuc_stop(&ct->kuc);
807
808         llapi_hsm_log_ct_registration(&ct, CT_UNREGISTER);
809
810         close(ct->open_by_fid_fd);
811         close(ct->mnt_fd);
812         free(ct->mnt);
813         free(ct->kuch);
814         free(ct);
815         *priv = NULL;
816
817         return 0;
818 }
819
820 /** Returns a file descriptor to poll/select on.
821  * \param ct Opaque private control structure
822  * \retval -EINVAL on error
823  * \retval the file descriptor for reading HSM events from the kernel
824  */
825 int llapi_hsm_copytool_get_fd(struct hsm_copytool_private *ct)
826 {
827         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
828                 return -EINVAL;
829
830         return libcfs_ukuc_get_rfd(&ct->kuc);
831 }
832
833 /** Wait for the next hsm_action_list
834  * \param ct Opaque private control structure
835  * \param halh Action list handle, will be allocated here
836  * \param msgsize Number of bytes in the message, will be set here
837  * \return 0 valid message received; halh and msgsize are set
838  *         <0 error code
839  * Note: The application must not call llapi_hsm_copytool_recv until it has
840  * cleared the data in ct->kuch from the previous call.
841  */
842 int llapi_hsm_copytool_recv(struct hsm_copytool_private *ct,
843                             struct hsm_action_list **halh, int *msgsize)
844 {
845         struct kuc_hdr          *kuch;
846         struct hsm_action_list  *hal;
847         int                      rc = 0;
848
849         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
850                 return -EINVAL;
851
852         if (halh == NULL || msgsize == NULL)
853                 return -EINVAL;
854
855         kuch = ct->kuch;
856
857 repeat:
858         rc = libcfs_ukuc_msg_get(&ct->kuc, (char *)kuch,
859                                  HAL_MAXSIZE + sizeof(*kuch),
860                                  KUC_TRANSPORT_HSM);
861         if (rc < 0)
862                 goto out_err;
863
864         /* Handle generic messages */
865         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
866             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
867                 rc = -ESHUTDOWN;
868                 goto out_err;
869         }
870
871         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
872             kuch->kuc_msgtype != HMT_ACTION_LIST) {
873                 llapi_err_noerrno(LLAPI_MSG_ERROR,
874                                   "Unknown HSM message type %d:%d\n",
875                                   kuch->kuc_transport, kuch->kuc_msgtype);
876                 rc = -EPROTO;
877                 goto out_err;
878         }
879
880         if (kuch->kuc_msglen < sizeof(*kuch) + sizeof(*hal)) {
881                 llapi_err_noerrno(LLAPI_MSG_ERROR, "Short HSM message %d",
882                                   kuch->kuc_msglen);
883                 rc = -EPROTO;
884                 goto out_err;
885         }
886
887         /* Our message is a hsm_action_list. Use pointer math to skip
888         * kuch_hdr and point directly to the message payload.
889         */
890         hal = (struct hsm_action_list *)(kuch + 1);
891
892         /* Check that we have registered for this archive #
893          * if 0 registered, we serve any archive */
894         if (ct->archives &&
895             ((1 << (hal->hal_archive_id - 1)) & ct->archives) == 0) {
896                 llapi_err_noerrno(LLAPI_MSG_INFO,
897                                   "This copytool does not service archive #%d,"
898                                   " ignoring this request."
899                                   " Mask of served archive is 0x%.8X",
900                                   hal->hal_archive_id, ct->archives);
901
902                 goto repeat;
903         }
904
905         *halh = hal;
906         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
907         return 0;
908
909 out_err:
910         *halh = NULL;
911         *msgsize = 0;
912         return rc;
913 }
914
915 /** Get parent path from mount point and fid.
916  *
917  * \param mnt        Filesystem root path.
918  * \param fid        Object FID.
919  * \param parent     Destination buffer.
920  * \param parent_len Destination buffer size.
921  * \return 0 on success.
922  */
923 static int fid_parent(const char *mnt, const lustre_fid *fid, char *parent,
924                       size_t parent_len)
925 {
926         int              rc;
927         int              linkno = 0;
928         long long        recno = -1;
929         char             file[PATH_MAX];
930         char             strfid[FID_NOBRACE_LEN + 1];
931         char            *ptr;
932
933         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(fid));
934
935         rc = llapi_fid2path(mnt, strfid, file, sizeof(file),
936                             &recno, &linkno);
937         if (rc < 0)
938                 return rc;
939
940         /* fid2path returns a relative path */
941         rc = snprintf(parent, parent_len, "%s/%s", mnt, file);
942         if (rc >= parent_len)
943                 return -ENAMETOOLONG;
944
945         /* remove file name */
946         ptr = strrchr(parent, '/');
947         if (ptr == NULL || ptr == parent) {
948                 rc = -EINVAL;
949         } else {
950                 *ptr = '\0';
951                 rc = 0;
952         }
953
954         return rc;
955 }
956
957 static int ct_open_by_fid(const struct hsm_copytool_private *ct,
958                           const struct lu_fid *fid, int open_flags)
959 {
960         char fid_name[FID_NOBRACE_LEN + 1];
961         int fd;
962
963         snprintf(fid_name, sizeof(fid_name), DFID_NOBRACE, PFID(fid));
964
965         fd = openat(ct->open_by_fid_fd, fid_name, open_flags);
966         return fd < 0 ? -errno : fd;
967 }
968
969 /**
970  * Get metadata attributes of file by FID.
971  *
972  * Use the IOC_MDC_GETFILEINFO ioctl (to send a MDS_GETATTR_NAME RPC)
973  * to get the attributes of the file identified by \a fid. This
974  * returns only the attributes stored on the MDT and avoids taking
975  * layout locks or accessing OST objects. It also bypasses the inode
976  * cache. Attributes are returned in \a st.
977  */
978 static int ct_md_getattr(const struct hsm_copytool_private *ct,
979                          const struct lu_fid *fid,
980                          lstat_t *st)
981 {
982         struct lov_user_mds_data *lmd;
983         size_t lmd_size;
984         int rc;
985
986         lmd_size = sizeof(lmd->lmd_st) +
987                 lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
988
989         if (lmd_size < sizeof(lmd->lmd_st) + XATTR_SIZE_MAX)
990                 lmd_size = sizeof(lmd->lmd_st) + XATTR_SIZE_MAX;
991
992         if (lmd_size < FID_NOBRACE_LEN + 1)
993                 lmd_size = FID_NOBRACE_LEN + 1;
994
995         lmd = malloc(lmd_size);
996         if (lmd == NULL)
997                 return -ENOMEM;
998
999         snprintf((char *)lmd, lmd_size, DFID_NOBRACE, PFID(fid));
1000
1001         rc = ioctl(ct->open_by_fid_fd, IOC_MDC_GETFILEINFO, lmd);
1002         if (rc != 0) {
1003                 rc = -errno;
1004                 llapi_error(LLAPI_MSG_ERROR, rc,
1005                             "cannot get metadata attributes of "DFID" in '%s'",
1006                             PFID(fid), ct->mnt);
1007                 goto out;
1008         }
1009
1010         *st = lmd->lmd_st;
1011 out:
1012         free(lmd);
1013
1014         return rc;
1015 }
1016
1017 /** Create the destination volatile file for a restore operation.
1018  *
1019  * \param hcp        Private copyaction handle.
1020  * \param mdt_index  MDT index where to create the volatile file.
1021  * \param flags      Volatile file creation flags.
1022  * \return 0 on success.
1023  */
1024 static int create_restore_volatile(struct hsm_copyaction_private *hcp,
1025                                    int mdt_index, int open_flags)
1026 {
1027         int                      rc;
1028         int                      fd;
1029         char                     parent[PATH_MAX + 1];
1030         const char              *mnt = hcp->ct_priv->mnt;
1031         struct hsm_action_item  *hai = &hcp->copy.hc_hai;
1032
1033         rc = fid_parent(mnt, &hai->hai_fid, parent, sizeof(parent));
1034         if (rc < 0) {
1035                 /* fid_parent() failed, try to keep on going */
1036                 llapi_error(LLAPI_MSG_ERROR, rc,
1037                             "cannot get parent path to restore "DFID" "
1038                             "using '%s'", PFID(&hai->hai_fid), mnt);
1039                 snprintf(parent, sizeof(parent), "%s", mnt);
1040         }
1041
1042         fd = llapi_create_volatile_idx(parent, mdt_index, open_flags);
1043         if (fd < 0)
1044                 return fd;
1045
1046         rc = fchown(fd, hcp->stat.st_uid, hcp->stat.st_gid);
1047         if (rc < 0)
1048                 goto err_cleanup;
1049
1050         rc = llapi_fd2fid(fd, &hai->hai_dfid);
1051         if (rc < 0)
1052                 goto err_cleanup;
1053
1054         hcp->data_fd = fd;
1055
1056         return 0;
1057
1058 err_cleanup:
1059         hcp->data_fd = -1;
1060         close(fd);
1061
1062         return rc;
1063 }
1064
1065 /** Start processing an HSM action.
1066  * Should be called by copytools just before starting handling a request.
1067  * It could be skipped if copytool only want to directly report an error,
1068  * \see llapi_hsm_action_end().
1069  *
1070  * \param hcp                Opaque action handle to be passed to
1071  *                           llapi_hsm_action_progress and llapi_hsm_action_end.
1072  * \param ct                 Copytool handle acquired at registration.
1073  * \param hai                The hsm_action_item describing the request.
1074  * \param restore_mdt_index  On restore: MDT index where to create the volatile
1075  *                           file. Use -1 for default.
1076  * \param restore_open_flags On restore: volatile file creation mode. Use
1077  *                           O_LOV_DELAY_CREATE to manually set the LOVEA
1078  *                           afterwards.
1079  * \param is_error           Whether this call is just to report an error.
1080  *
1081  * \return 0 on success.
1082  */
1083 int llapi_hsm_action_begin(struct hsm_copyaction_private **phcp,
1084                            const struct hsm_copytool_private *ct,
1085                            const struct hsm_action_item *hai,
1086                            int restore_mdt_index, int restore_open_flags,
1087                            bool is_error)
1088 {
1089         struct hsm_copyaction_private   *hcp;
1090         int                              rc;
1091
1092         hcp = calloc(1, sizeof(*hcp));
1093         if (hcp == NULL)
1094                 return -ENOMEM;
1095
1096         hcp->data_fd = -1;
1097         hcp->ct_priv = ct;
1098         hcp->copy.hc_hai = *hai;
1099         hcp->copy.hc_hai.hai_len = sizeof(*hai);
1100
1101         if (is_error)
1102                 goto ok_out;
1103
1104         if (hai->hai_action == HSMA_RESTORE) {
1105                 rc = ct_md_getattr(hcp->ct_priv, &hai->hai_fid, &hcp->stat);
1106                 if (rc < 0)
1107                         goto err_out;
1108
1109                 rc = create_restore_volatile(hcp, restore_mdt_index,
1110                                              restore_open_flags);
1111                 if (rc < 0)
1112                         goto err_out;
1113         }
1114
1115         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_COPY_START, &hcp->copy);
1116         if (rc < 0) {
1117                 rc = -errno;
1118                 goto err_out;
1119         }
1120
1121         llapi_hsm_log_ct_progress(&hcp, hai, CT_START, 0, 0);
1122
1123 ok_out:
1124         hcp->magic = CP_PRIV_MAGIC;
1125         *phcp = hcp;
1126         return 0;
1127
1128 err_out:
1129         if (!(hcp->data_fd < 0))
1130                 close(hcp->data_fd);
1131
1132         free(hcp);
1133
1134         return rc;
1135 }
1136
1137 /** Terminate an HSM action processing.
1138  * Should be called by copytools just having finished handling the request.
1139  * \param hdl[in,out]  Handle returned by llapi_hsm_action_start.
1140  * \param he[in]       The final range of copied data (for copy actions).
1141  * \param errval[in]   The status code of the operation.
1142  * \param flags[in]    The flags about the termination status (HP_FLAG_RETRY if
1143  *                     the error is retryable).
1144  *
1145  * \return 0 on success.
1146  */
1147 int llapi_hsm_action_end(struct hsm_copyaction_private **phcp,
1148                          const struct hsm_extent *he, int hp_flags, int errval)
1149 {
1150         struct hsm_copyaction_private   *hcp;
1151         struct hsm_action_item          *hai;
1152         int                              rc;
1153
1154         if (phcp == NULL || *phcp == NULL || he == NULL)
1155                 return -EINVAL;
1156
1157         hcp = *phcp;
1158
1159         if (hcp->magic != CP_PRIV_MAGIC)
1160                 return -EINVAL;
1161
1162         hai = &hcp->copy.hc_hai;
1163
1164         if (hai->hai_action == HSMA_RESTORE && errval == 0) {
1165                 struct ll_futimes_3 lfu = {
1166                         .lfu_atime_sec = hcp->stat.st_atim.tv_sec,
1167                         .lfu_atime_nsec = hcp->stat.st_atim.tv_nsec,
1168                         .lfu_mtime_sec = hcp->stat.st_mtim.tv_sec,
1169                         .lfu_mtime_nsec = hcp->stat.st_mtim.tv_nsec,
1170                         .lfu_ctime_sec = hcp->stat.st_ctim.tv_sec,
1171                         .lfu_ctime_nsec = hcp->stat.st_ctim.tv_nsec,
1172                 };
1173
1174                 /* Set {a,m,c}time of volatile file to that of original. */
1175                 if (ioctl(hcp->data_fd, LL_IOC_FUTIMES_3, &lfu) < 0) {
1176                         errval = -errno;
1177                         goto end;
1178                 }
1179
1180                 rc = fsync(hcp->data_fd);
1181                 if (rc < 0) {
1182                         errval = -errno;
1183                         goto end;
1184                 }
1185         }
1186
1187 end:
1188         /* In some cases, like restore, 2 FIDs are used.
1189          * Set the right FID to use here. */
1190         if (hai->hai_action == HSMA_ARCHIVE || hai->hai_action == HSMA_RESTORE)
1191                 hai->hai_fid = hai->hai_dfid;
1192
1193         /* Fill the last missing data that will be needed by
1194          * kernel to send a hsm_progress. */
1195         hcp->copy.hc_flags  = hp_flags;
1196         hcp->copy.hc_errval = abs(errval);
1197
1198         hcp->copy.hc_hai.hai_extent = *he;
1199
1200         rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_COPY_END, &hcp->copy);
1201         if (rc) {
1202                 rc = -errno;
1203                 goto err_cleanup;
1204         }
1205
1206         llapi_hsm_log_ct_progress(&hcp, hai, CT_FINISH, 0, 0);
1207
1208 err_cleanup:
1209         if (!(hcp->data_fd < 0))
1210                 close(hcp->data_fd);
1211
1212         free(hcp);
1213         *phcp = NULL;
1214
1215         return rc;
1216 }
1217
1218 /** Notify a progress in processing an HSM action.
1219  * \param hdl[in,out]   handle returned by llapi_hsm_action_start.
1220  * \param he[in]        the range of copied data (for copy actions).
1221  * \param total[in]     the expected total of copied data (for copy actions).
1222  * \param hp_flags[in]  HSM progress flags.
1223  * \return 0 on success.
1224  */
1225 int llapi_hsm_action_progress(struct hsm_copyaction_private *hcp,
1226                               const struct hsm_extent *he, __u64 total,
1227                               int hp_flags)
1228 {
1229         int                      rc;
1230         struct hsm_progress      hp;
1231         struct hsm_action_item  *hai;
1232
1233         if (hcp == NULL || he == NULL)
1234                 return -EINVAL;
1235
1236         if (hcp->magic != CP_PRIV_MAGIC)
1237                 return -EINVAL;
1238
1239         hai = &hcp->copy.hc_hai;
1240
1241         memset(&hp, 0, sizeof(hp));
1242
1243         hp.hp_cookie = hai->hai_cookie;
1244         hp.hp_flags  = hp_flags;
1245
1246         /* Progress is made on the data fid */
1247         hp.hp_fid = hai->hai_dfid;
1248         hp.hp_extent = *he;
1249
1250         rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_PROGRESS, &hp);
1251         if (rc < 0)
1252                 rc = -errno;
1253
1254         llapi_hsm_log_ct_progress(&hcp, hai, CT_RUNNING, total, he->length);
1255
1256         return rc;
1257 }
1258
1259 /** Get the fid of object to be used for copying data.
1260  * @return error code if the action is not a copy operation.
1261  */
1262 int llapi_hsm_action_get_dfid(const struct hsm_copyaction_private *hcp,
1263                               lustre_fid *fid)
1264 {
1265         const struct hsm_action_item    *hai = &hcp->copy.hc_hai;
1266
1267         if (hcp->magic != CP_PRIV_MAGIC)
1268                 return -EINVAL;
1269
1270         if (hai->hai_action != HSMA_RESTORE && hai->hai_action != HSMA_ARCHIVE)
1271                 return -EINVAL;
1272
1273         *fid = hai->hai_dfid;
1274
1275         return 0;
1276 }
1277
1278 /**
1279  * Get a file descriptor to be used for copying data. It's up to the
1280  * caller to close the FDs obtained from this function.
1281  *
1282  * @retval a file descriptor on success.
1283  * @retval a negative error code on failure.
1284  */
1285 int llapi_hsm_action_get_fd(const struct hsm_copyaction_private *hcp)
1286 {
1287         const struct hsm_action_item    *hai = &hcp->copy.hc_hai;
1288         int fd;
1289
1290         if (hcp->magic != CP_PRIV_MAGIC)
1291                 return -EINVAL;
1292
1293         if (hai->hai_action == HSMA_ARCHIVE) {
1294                 return ct_open_by_fid(hcp->ct_priv, &hai->hai_dfid,
1295                                 O_RDONLY | O_NOATIME | O_NOFOLLOW | O_NONBLOCK);
1296         } else if (hai->hai_action == HSMA_RESTORE) {
1297                 fd = dup(hcp->data_fd);
1298                 return fd < 0 ? -errno : fd;
1299         } else {
1300                 return -EINVAL;
1301         }
1302 }
1303
1304 /**
1305  * Import an existing hsm-archived file into Lustre.
1306  *
1307  * Caller must access file by (returned) newfid value from now on.
1308  *
1309  * \param dst      path to Lustre destination (e.g. /mnt/lustre/my/file).
1310  * \param archive  archive number.
1311  * \param st       struct stat buffer containing file ownership, perm, etc.
1312  * \param stripe_* Striping options.  Currently ignored, since the restore
1313  *                 operation will set the striping.  In V2, this striping might
1314  *                 be used.
1315  * \param newfid[out] Filled with new Lustre fid.
1316  */
1317 int llapi_hsm_import(const char *dst, int archive, const struct stat *st,
1318                      unsigned long long stripe_size, int stripe_offset,
1319                      int stripe_count, int stripe_pattern, char *pool_name,
1320                      lustre_fid *newfid)
1321 {
1322         struct hsm_user_import   hui;
1323         int                      fd;
1324         int                      rc = 0;
1325
1326         if (stripe_pattern == 0)
1327                 stripe_pattern = LOV_PATTERN_RAID0;
1328
1329         /* Create a non-striped file */
1330         fd = llapi_file_open_pool(dst, O_CREAT | O_WRONLY, st->st_mode,
1331                                   stripe_size, stripe_offset, stripe_count,
1332                                   stripe_pattern | LOV_PATTERN_F_RELEASED,
1333                                   pool_name);
1334         if (fd < 0) {
1335                 llapi_error(LLAPI_MSG_ERROR, fd,
1336                             "cannot create '%s' for import", dst);
1337                 return fd;
1338         }
1339
1340         /* Get the new fid in Lustre. Caller needs to use this fid
1341            from now on. */
1342         rc = llapi_fd2fid(fd, newfid);
1343         if (rc != 0) {
1344                 llapi_error(LLAPI_MSG_ERROR, rc,
1345                             "cannot get fid of '%s' for import", dst);
1346                 goto out_unlink;
1347         }
1348
1349         hui.hui_uid = st->st_uid;
1350         hui.hui_gid = st->st_gid;
1351         hui.hui_mode = st->st_mode;
1352         hui.hui_size = st->st_size;
1353         hui.hui_archive_id = archive;
1354         hui.hui_atime = st->st_atime;
1355         hui.hui_atime_ns = st->st_atim.tv_nsec;
1356         hui.hui_mtime = st->st_mtime;
1357         hui.hui_mtime_ns = st->st_mtim.tv_nsec;
1358         rc = ioctl(fd, LL_IOC_HSM_IMPORT, &hui);
1359         if (rc != 0) {
1360                 rc = -errno;
1361                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot import '%s'", dst);
1362                 goto out_unlink;
1363         }
1364
1365 out_unlink:
1366         if (fd >= 0)
1367                 close(fd);
1368         if (rc)
1369                 unlink(dst);
1370         return rc;
1371 }
1372
1373 /**
1374  * Return the current HSM states and HSM requests related to file pointed by \a
1375  * path.
1376  *
1377  * \param hus  Should be allocated by caller. Will be filled with current file
1378  *             states.
1379  *
1380  * \retval 0 on success.
1381  * \retval -errno on error.
1382  */
1383 int llapi_hsm_state_get_fd(int fd, struct hsm_user_state *hus)
1384 {
1385         int rc;
1386
1387         rc = ioctl(fd, LL_IOC_HSM_STATE_GET, hus);
1388         /* If error, save errno value */
1389         rc = rc ? -errno : 0;
1390
1391         return rc;
1392 }
1393
1394 /**
1395  * Return the current HSM states and HSM requests related to file pointed by \a
1396  * path.
1397  *
1398  * see llapi_hsm_state_get_fd() for args use and return
1399  */
1400 int llapi_hsm_state_get(const char *path, struct hsm_user_state *hus)
1401 {
1402         int fd;
1403         int rc;
1404
1405         fd = open(path, O_RDONLY | O_NONBLOCK);
1406         if (fd < 0)
1407                 return -errno;
1408
1409         rc = llapi_hsm_state_get_fd(fd, hus);
1410
1411         close(fd);
1412         return rc;
1413 }
1414
1415 /**
1416  * Set HSM states of file pointed by \a fd
1417  *
1418  * Using the provided bitmasks, the current HSM states for this file will be
1419  * changed. \a archive_id could be used to change the archive number also. Set
1420  * it to 0 if you do not want to change it.
1421  *
1422  * \param setmask      Bitmask for flag to be set.
1423  * \param clearmask    Bitmask for flag to be cleared.
1424  * \param archive_id  Archive number identifier to use. 0 means no change.
1425  *
1426  * \retval 0 on success.
1427  * \retval -errno on error.
1428  */
1429 int llapi_hsm_state_set_fd(int fd, __u64 setmask, __u64 clearmask,
1430                            __u32 archive_id)
1431 {
1432         struct hsm_state_set     hss;
1433         int                      rc;
1434
1435         hss.hss_valid = HSS_SETMASK|HSS_CLEARMASK;
1436         hss.hss_setmask = setmask;
1437         hss.hss_clearmask = clearmask;
1438         /* Change archive_id if provided. We can only change
1439          * to set something different than 0. */
1440         if (archive_id > 0) {
1441                 hss.hss_valid |= HSS_ARCHIVE_ID;
1442                 hss.hss_archive_id = archive_id;
1443         }
1444         rc = ioctl(fd, LL_IOC_HSM_STATE_SET, &hss);
1445         /* If error, save errno value */
1446         rc = rc ? -errno : 0;
1447
1448         return rc;
1449 }
1450
1451 /**
1452  * Set HSM states of file pointed by \a path.
1453  *
1454  * see llapi_hsm_state_set_fd() for args use and return
1455  */
1456 int llapi_hsm_state_set(const char *path, __u64 setmask, __u64 clearmask,
1457                         __u32 archive_id)
1458 {
1459         int fd;
1460         int rc;
1461
1462         fd = open(path, O_WRONLY | O_LOV_DELAY_CREATE | O_NONBLOCK);
1463         if (fd < 0)
1464                 return -errno;
1465
1466         rc = llapi_hsm_state_set_fd(fd, setmask, clearmask, archive_id);
1467
1468         close(fd);
1469         return rc;
1470 }
1471
1472 /**
1473  * Return the current HSM request related to file pointed by \a path.
1474  *
1475  * \param hca  Should be allocated by caller. Will be filled with current file
1476  *             actions.
1477  *
1478  * \retval 0 on success.
1479  * \retval -errno on error.
1480  */
1481 int llapi_hsm_current_action(const char *path, struct hsm_current_action *hca)
1482 {
1483         int fd;
1484         int rc;
1485
1486         fd = open(path, O_RDONLY | O_NONBLOCK);
1487         if (fd < 0)
1488                 return -errno;
1489
1490         rc = ioctl(fd, LL_IOC_HSM_ACTION, hca);
1491         /* If error, save errno value */
1492         rc = rc ? -errno : 0;
1493
1494         close(fd);
1495         return rc;
1496 }
1497
1498 /**
1499  * Allocate a hsm_user_request with the specified carateristics.
1500  * This structure should be freed with free().
1501  *
1502  * \return an allocated structure on success, NULL otherwise.
1503  */
1504 struct hsm_user_request *llapi_hsm_user_request_alloc(int itemcount,
1505                                                       int data_len)
1506 {
1507         int len = 0;
1508
1509         len += sizeof(struct hsm_user_request);
1510         len += sizeof(struct hsm_user_item) * itemcount;
1511         len += data_len;
1512
1513         return (struct hsm_user_request *)malloc(len);
1514 }
1515
1516 /**
1517  * Send a HSM request to Lustre, described in \param request.
1518  *
1519  * \param path    Fullpath to the file to operate on.
1520  * \param request The request, allocated with llapi_hsm_user_request_alloc().
1521  *
1522  * \return 0 on success, an error code otherwise.
1523  */
1524 int llapi_hsm_request(const char *path, const struct hsm_user_request *request)
1525 {
1526         int rc;
1527         int fd;
1528
1529         rc = get_root_path(WANT_FD, NULL, &fd, (char *)path, -1);
1530         if (rc)
1531                 return rc;
1532
1533         rc = ioctl(fd, LL_IOC_HSM_REQUEST, request);
1534         /* If error, save errno value */
1535         rc = rc ? -errno : 0;
1536
1537         close(fd);
1538         return rc;
1539 }
1540