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