Whamcloud - gitweb
LU-6245 utils: split kernel comm between user and kernel
[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, 2014, 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/types.h>
47 #include <utime.h>
48 #include <sys/syscall.h>
49 #include <fnmatch.h>
50 #include <glob.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 <libcfs/libcfs.h>
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 #include <libcfs/libcfs.h>
88
89 enum ct_progress_type {
90         CT_START        = 0,
91         CT_RUNNING      = 50,
92         CT_FINISH       = 100,
93         CT_CANCEL       = 150,
94         CT_ERROR        = 175
95 };
96
97 enum ct_event {
98         CT_REGISTER             = 1,
99         CT_UNREGISTER           = 2,
100         CT_ARCHIVE_START        = HSMA_ARCHIVE,
101         CT_ARCHIVE_RUNNING      = HSMA_ARCHIVE + CT_RUNNING,
102         CT_ARCHIVE_FINISH       = HSMA_ARCHIVE + CT_FINISH,
103         CT_ARCHIVE_CANCEL       = HSMA_ARCHIVE + CT_CANCEL,
104         CT_ARCHIVE_ERROR        = HSMA_ARCHIVE + CT_ERROR,
105         CT_RESTORE_START        = HSMA_RESTORE,
106         CT_RESTORE_RUNNING      = HSMA_RESTORE + CT_RUNNING,
107         CT_RESTORE_FINISH       = HSMA_RESTORE + CT_FINISH,
108         CT_RESTORE_CANCEL       = HSMA_RESTORE + CT_CANCEL,
109         CT_RESTORE_ERROR        = HSMA_RESTORE + CT_ERROR,
110         CT_REMOVE_START         = HSMA_REMOVE,
111         CT_REMOVE_RUNNING       = HSMA_REMOVE + CT_RUNNING,
112         CT_REMOVE_FINISH        = HSMA_REMOVE + CT_FINISH,
113         CT_REMOVE_CANCEL        = HSMA_REMOVE + CT_CANCEL,
114         CT_REMOVE_ERROR         = HSMA_REMOVE + CT_ERROR,
115         CT_EVENT_MAX
116 };
117
118 /* initialized in llapi_hsm_register_event_fifo() */
119 static int llapi_hsm_event_fd = -1;
120 static bool created_hsm_event_fifo;
121
122 static inline const char *llapi_hsm_ct_ev2str(int type)
123 {
124         switch (type) {
125         case CT_REGISTER:
126                 return "REGISTER";
127         case CT_UNREGISTER:
128                 return "UNREGISTER";
129         case CT_ARCHIVE_START:
130                 return "ARCHIVE_START";
131         case CT_ARCHIVE_RUNNING:
132                 return "ARCHIVE_RUNNING";
133         case CT_ARCHIVE_FINISH:
134                 return "ARCHIVE_FINISH";
135         case CT_ARCHIVE_CANCEL:
136                 return "ARCHIVE_CANCEL";
137         case CT_ARCHIVE_ERROR:
138                 return "ARCHIVE_ERROR";
139         case CT_RESTORE_START:
140                 return "RESTORE_START";
141         case CT_RESTORE_RUNNING:
142                 return "RESTORE_RUNNING";
143         case CT_RESTORE_FINISH:
144                 return "RESTORE_FINISH";
145         case CT_RESTORE_CANCEL:
146                 return "RESTORE_CANCEL";
147         case CT_RESTORE_ERROR:
148                 return "RESTORE_ERROR";
149         case CT_REMOVE_START:
150                 return "REMOVE_START";
151         case CT_REMOVE_RUNNING:
152                 return "REMOVE_RUNNING";
153         case CT_REMOVE_FINISH:
154                 return "REMOVE_FINISH";
155         case CT_REMOVE_CANCEL:
156                 return "REMOVE_CANCEL";
157         case CT_REMOVE_ERROR:
158                 return "REMOVE_ERROR";
159         default:
160                 llapi_err_noerrno(LLAPI_MSG_ERROR,
161                                   "Unknown event type: %d", type);
162                 return NULL;
163         }
164 }
165
166 /**
167  * Writes a JSON event to the monitor FIFO. Noop if no FIFO has been
168  * registered.
169  *
170  * \param event              A list of llapi_json_items comprising a
171  *                           single JSON-formatted event.
172  *
173  * \retval 0 on success.
174  * \retval -errno on error.
175  */
176 static int llapi_hsm_write_json_event(struct llapi_json_item_list **event)
177 {
178         int                             rc;
179         char                            time_string[40];
180         char                            json_buf[PIPE_BUF];
181         FILE                            *buf_file;
182         time_t                          event_time = time(0);
183         struct tm                       time_components;
184         struct llapi_json_item_list     *json_items;
185
186         /* Noop unless the event fd was initialized */
187         if (llapi_hsm_event_fd < 0)
188                 return 0;
189
190         if (event == NULL || *event == NULL)
191                 return -EINVAL;
192
193         json_items = *event;
194
195         localtime_r(&event_time, &time_components);
196
197         if (strftime(time_string, sizeof(time_string), "%Y-%m-%d %T %z",
198                      &time_components) == 0) {
199                 rc = -EINVAL;
200                 llapi_error(LLAPI_MSG_ERROR, rc, "strftime() failed");
201                 return rc;
202         }
203
204         rc = llapi_json_add_item(&json_items, "event_time", LLAPI_JSON_STRING,
205                                  time_string);
206         if (rc < 0) {
207                 llapi_error(LLAPI_MSG_ERROR, -rc, "error in "
208                             "llapi_json_add_item()");
209                 return rc;
210         }
211
212         buf_file = fmemopen(json_buf, sizeof(json_buf), "w");
213         if (buf_file == NULL)
214                 return -errno;
215
216         rc = llapi_json_write_list(event, buf_file);
217         if (rc < 0) {
218                 fclose(buf_file);
219                 return rc;
220         }
221
222         fclose(buf_file);
223
224         if (write(llapi_hsm_event_fd, json_buf, strlen(json_buf)) < 0) {
225                 /* Ignore write failures due to missing reader. */
226                 if (errno != EPIPE)
227                         return -errno;
228         }
229
230         return 0;
231 }
232
233 /**
234  * Hook for llapi_hsm_copytool_register and llapi_hsm_copytool_unregister
235  * to generate JSON events suitable for consumption by a copytool
236  * monitoring process.
237  *
238  * \param priv               Opaque private control structure.
239  * \param event_type         The type of event (register or unregister).
240  *
241  * \retval 0 on success.
242  * \retval -errno on error.
243  */
244 static int llapi_hsm_log_ct_registration(struct hsm_copytool_private **priv,
245                                          __u32 event_type)
246 {
247         int                             rc;
248         char                            agent_uuid[UUID_MAX];
249         struct hsm_copytool_private     *ct;
250         struct llapi_json_item_list     *json_items;
251
252         /* Noop unless the event fd was initialized */
253         if (llapi_hsm_event_fd < 0)
254                 return 0;
255
256         if (priv == NULL || *priv == NULL)
257                 return -EINVAL;
258
259         ct = *priv;
260         if (ct->magic != CT_PRIV_MAGIC)
261                 return -EINVAL;
262
263         if (event_type != CT_REGISTER && event_type != CT_UNREGISTER)
264                 return -EINVAL;
265
266         rc = llapi_json_init_list(&json_items);
267         if (rc < 0)
268                 goto err;
269
270         rc = llapi_get_agent_uuid(ct->mnt, agent_uuid, sizeof(agent_uuid));
271         if (rc < 0)
272                 goto err;
273         llapi_chomp_string(agent_uuid);
274
275         rc = llapi_json_add_item(&json_items, "uuid", LLAPI_JSON_STRING,
276                                  agent_uuid);
277         if (rc < 0)
278                 goto err;
279
280         rc = llapi_json_add_item(&json_items, "mount_point", LLAPI_JSON_STRING,
281                                  ct->mnt);
282         if (rc < 0)
283                 goto err;
284
285         rc = llapi_json_add_item(&json_items, "archive", LLAPI_JSON_INTEGER,
286                                  &ct->archives);
287         if (rc < 0)
288                 goto err;
289
290         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
291                                  (char *)llapi_hsm_ct_ev2str(event_type));
292         if (rc < 0)
293                 goto err;
294
295         rc = llapi_hsm_write_json_event(&json_items);
296         if (rc < 0)
297                 goto err;
298
299         goto out_free;
300
301 err:
302         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
303                     "llapi_hsm_log_ct_registration()");
304
305 out_free:
306         if (json_items != NULL)
307                 llapi_json_destroy_list(&json_items);
308
309         return rc;
310 }
311
312 /**
313  * Given a copytool progress update, construct a JSON event suitable for
314  * consumption by a copytool monitoring process.
315  *
316  * Examples of various events generated here and written by
317  * llapi_hsm_write_json_event:
318  *
319  * Copytool registration and deregistration:
320  * {"event_time": "2014-02-26 14:58:01 -0500", "event_type": "REGISTER",
321  *  "archive": 0, "mount_point": "/mnt/lustre",
322  *  "uuid": "80379a60-1f8a-743f-daf2-307cde793ec2"}
323  * {"event_time": "2014-02-26 14:58:01 -0500", "event_type": "UNREGISTER",
324  *  "archive": 0, "mount_point": "/mnt/lustre",
325  *  "uuid": "80379a60-1f8a-743f-daf2-307cde793ec2"}
326  *
327  * An archive action, start to completion:
328  * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "ARCHIVE_START",
329  *  "total_bytes": 0, "lustre_path": "d71.sanity-hsm/f71.sanity-hsm",
330  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
331  * {"event_time": "2014-02-26 14:50:18 -0500", "event_type": "ARCHIVE_RUNNING",
332  *  "current_bytes": 5242880, "total_bytes": 39000000,
333  *  "lustre_path": "d71.sanity-hsm/f71.sanity-hsm",
334  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
335  * {"event_time": "2014-02-26 14:50:50 -0500", "event_type": "ARCHIVE_FINISH",
336  *  "source_fid": "0x2000013a1:0x2:0x0", "data_fid": "0x2000013a1:0x2:0x0"}
337  *
338  * A log message:
339  * {"event_time": "2014-02-26 14:50:13 -0500", "event_type": "LOGGED_MESSAGE",
340  *  "level": "INFO",
341  *  "message": "lhsmtool_posix[42]: copytool fs=lustre archive#=2 item_count=1"}
342  *
343  * \param hcp                Opaque action handle returned by
344  *                           llapi_hsm_action_start.
345  * \param hai                The hsm_action_item describing the request.
346  * \param progress_type      The ct_progress_type describing the update.
347  * \param total              The total expected bytes for the request.
348  * \param current            The current copied byte count for the request.
349  *
350  * \retval 0 on success.
351  * \retval -errno on error.
352  */
353 static int llapi_hsm_log_ct_progress(struct hsm_copyaction_private **phcp,
354                                      const struct hsm_action_item *hai,
355                                      __u32 progress_type,
356                                      __u64 total, __u64 current)
357 {
358         int                             rc;
359         int                             linkno = 0;
360         long long                       recno = -1;
361         char                            lustre_path[PATH_MAX];
362         char                            strfid[FID_NOBRACE_LEN + 1];
363         struct hsm_copyaction_private   *hcp;
364         struct llapi_json_item_list     *json_items;
365
366         /* Noop unless the event fd was initialized */
367         if (llapi_hsm_event_fd < 0)
368                 return 0;
369
370         if (phcp == NULL || *phcp == NULL)
371                 return -EINVAL;
372
373         hcp = *phcp;
374
375         rc = llapi_json_init_list(&json_items);
376         if (rc < 0)
377                 goto err;
378
379         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(&hai->hai_dfid));
380         rc = llapi_json_add_item(&json_items, "data_fid",
381                                  LLAPI_JSON_STRING, strfid);
382         if (rc < 0)
383                 goto err;
384
385         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(&hai->hai_fid));
386         rc = llapi_json_add_item(&json_items, "source_fid",
387                                  LLAPI_JSON_STRING, strfid);
388         if (rc < 0)
389                 goto err;
390
391         if (hcp->copy.hc_errval == ECANCELED) {
392                 progress_type = CT_CANCEL;
393                 goto cancel;
394         }
395
396         if (hcp->copy.hc_errval != 0) {
397                 progress_type = CT_ERROR;
398
399                 rc = llapi_json_add_item(&json_items, "errno",
400                                          LLAPI_JSON_INTEGER,
401                                          &hcp->copy.hc_errval);
402                 if (rc < 0)
403                         goto err;
404
405                 rc = llapi_json_add_item(&json_items, "error",
406                                          LLAPI_JSON_STRING,
407                                          strerror(hcp->copy.hc_errval));
408                 if (rc < 0)
409                         goto err;
410
411                 goto cancel;
412         }
413
414         /* lustre_path isn't available after a restore completes */
415         /* total_bytes isn't available after a restore or archive completes */
416         if (progress_type != CT_FINISH) {
417                 rc = llapi_fid2path(hcp->ct_priv->mnt, strfid, lustre_path,
418                                     sizeof(lustre_path), &recno, &linkno);
419                 if (rc < 0)
420                         goto err;
421
422                 rc = llapi_json_add_item(&json_items, "lustre_path",
423                                          LLAPI_JSON_STRING, lustre_path);
424                 if (rc < 0)
425                         goto err;
426
427                 rc = llapi_json_add_item(&json_items, "total_bytes",
428                                          LLAPI_JSON_BIGNUM, &total);
429                 if (rc < 0)
430                         goto err;
431         }
432
433         if (progress_type == CT_RUNNING)
434                 rc = llapi_json_add_item(&json_items, "current_bytes",
435                                          LLAPI_JSON_BIGNUM, &current);
436                 if (rc < 0)
437                         goto err;
438
439 cancel:
440         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
441                                  (char *)llapi_hsm_ct_ev2str(hai->hai_action +
442                                                              progress_type));
443         if (rc < 0)
444                 goto err;
445
446         rc = llapi_hsm_write_json_event(&json_items);
447         if (rc < 0)
448                 goto err;
449
450         goto out_free;
451
452 err:
453         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
454                     "llapi_hsm_log_ct_progress()");
455
456 out_free:
457         if (json_items != NULL)
458                 llapi_json_destroy_list(&json_items);
459
460         return rc;
461 }
462
463 /**
464  * Given a path to a FIFO, create a filehandle for nonblocking writes to it.
465  * Intended to be used for copytool monitoring processes that read an
466  * event stream from the FIFO. Events written in the absence of a reader
467  * are lost.
468  *
469  * \param path               Path to monitor FIFO.
470  *
471  * \retval 0 on success.
472  * \retval -errno on error.
473  */
474 int llapi_hsm_register_event_fifo(const char *path)
475 {
476         int read_fd;
477         struct stat statbuf;
478
479         /* Create the FIFO if necessary. */
480         if ((mkfifo(path, 0644) < 0) && (errno != EEXIST)) {
481                 llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed", path);
482                 return -errno;
483         }
484         if (errno == EEXIST) {
485                 if (stat(path, &statbuf) < 0) {
486                         llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed",
487                                     path);
488                         return -errno;
489                 }
490                 if (!S_ISFIFO(statbuf.st_mode) ||
491                     ((statbuf.st_mode & 0777) != 0644)) {
492                         llapi_error(LLAPI_MSG_ERROR, errno, "%s exists but is "
493                                     "not a pipe or has a wrong mode", path);
494                         return -errno;
495                 }
496         } else {
497                 created_hsm_event_fifo = true;
498         }
499
500         /* Open the FIFO for read so that the subsequent open for write
501          * doesn't immediately fail. */
502         read_fd = open(path, O_RDONLY | O_NONBLOCK);
503         if (read_fd < 0) {
504                 llapi_error(LLAPI_MSG_ERROR, errno,
505                             "cannot open(%s) for read", path);
506                 return -errno;
507         }
508
509         /* Open the FIFO for writes, but don't block on waiting
510          * for a reader. */
511         llapi_hsm_event_fd = open(path, O_WRONLY | O_NONBLOCK);
512         if (llapi_hsm_event_fd < 0) {
513                 llapi_error(LLAPI_MSG_ERROR, errno,
514                             "cannot open(%s) for write", path);
515                 return -errno;
516         }
517
518         /* Now close the reader. An external monitoring process can
519          * now open the FIFO for reads. If no reader comes along the
520          * events are lost. NOTE: Only one reader at a time! */
521         close(read_fd);
522
523         /* Ignore SIGPIPEs -- can occur if the reader goes away. */
524         signal(SIGPIPE, SIG_IGN);
525
526         return 0;
527 }
528
529 /**
530  * Given a path to a FIFO, close its filehandle and delete the FIFO.
531  *
532  * \param path               Path to monitor FIFO.
533  *
534  * \retval 0 on success.
535  * \retval -errno on error.
536  */
537 int llapi_hsm_unregister_event_fifo(const char *path)
538 {
539         /* Noop unless the event fd was initialized */
540         if (llapi_hsm_event_fd < 0)
541                 return 0;
542
543         if (close(llapi_hsm_event_fd) < 0)
544                 return -errno;
545
546         if (created_hsm_event_fifo) {
547                 unlink(path);
548                 created_hsm_event_fifo = false;
549         }
550
551         llapi_hsm_event_fd = -1;
552
553         return 0;
554 }
555
556 /**
557  * Custom logging callback to be used when a monitoring FIFO has been
558  * registered. Formats log entries as JSON events suitable for
559  * consumption by a copytool monitoring process.
560  *
561  * \param level              The message loglevel.
562  * \param _rc                The returncode associated with the message.
563  * \param fmt                The message format string.
564  * \param args               Arguments to be formatted by the format string.
565  *
566  * \retval None.
567  */
568 void llapi_hsm_log_error(enum llapi_message_level level, int _rc,
569                          const char *fmt, va_list args)
570 {
571         int                             rc;
572         int                             msg_len;
573         int                             real_level;
574         char                            *msg = NULL;
575         va_list                         args2;
576         struct llapi_json_item_list     *json_items;
577
578         /* Noop unless the event fd was initialized */
579         if (llapi_hsm_event_fd < 0)
580                 return;
581
582         rc = llapi_json_init_list(&json_items);
583         if (rc < 0)
584                 goto err;
585
586         if ((level & LLAPI_MSG_NO_ERRNO) == 0) {
587                 rc = llapi_json_add_item(&json_items, "errno",
588                                          LLAPI_JSON_INTEGER,
589                                          &_rc);
590                 if (rc < 0)
591                         goto err;
592
593                 rc = llapi_json_add_item(&json_items, "error",
594                                          LLAPI_JSON_STRING,
595                                          strerror(abs(_rc)));
596                 if (rc < 0)
597                         goto err;
598         }
599
600         va_copy(args2, args);
601         msg_len = vsnprintf(NULL, 0, fmt, args2) + 1;
602         va_end(args2);
603         if (msg_len >= 0) {
604                 msg = (char *) alloca(msg_len);
605                 if (msg == NULL) {
606                         rc = -ENOMEM;
607                         goto err;
608                 }
609
610                 rc = vsnprintf(msg, msg_len, fmt, args);
611                 if (rc < 0)
612                         goto err;
613
614                 rc = llapi_json_add_item(&json_items, "message",
615                                          LLAPI_JSON_STRING,
616                                          msg);
617                 if (rc < 0)
618                         goto err;
619         } else {
620                 rc = llapi_json_add_item(&json_items, "message",
621                                          LLAPI_JSON_STRING,
622                                          "INTERNAL ERROR: message failed");
623                 if (rc < 0)
624                         goto err;
625         }
626
627         real_level = level & LLAPI_MSG_NO_ERRNO;
628         real_level = real_level > 0 ? level - LLAPI_MSG_NO_ERRNO : level;
629
630         rc = llapi_json_add_item(&json_items, "level", LLAPI_JSON_STRING,
631                                  (void *)llapi_msg_level2str(real_level));
632         if (rc < 0)
633                 goto err;
634
635         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
636                                  "LOGGED_MESSAGE");
637         if (rc < 0)
638                 goto err;
639
640         rc = llapi_hsm_write_json_event(&json_items);
641         if (rc < 0)
642                 goto err;
643
644         goto out_free;
645
646 err:
647         /* Write directly to stderr to avoid llapi_error, which now
648          * emits JSON event messages. */
649         fprintf(stderr, "\nFATAL ERROR IN llapi_hsm_log_error(): rc %d,", rc);
650
651 out_free:
652         if (json_items != NULL)
653                 llapi_json_destroy_list(&json_items);
654
655         return;
656 }
657
658 /** Register a copytool
659  * \param[out] priv             Opaque private control structure
660  * \param mnt                   Lustre filesystem mount point
661  * \param archive_count         Number of valid archive IDs in \a archives
662  * \param archives              Which archive numbers this copytool is
663  *                              responsible for
664  * \param rfd_flags             flags applied to read fd of pipe
665  *                              (e.g. O_NONBLOCK)
666  *
667  * \retval 0 on success.
668  * \retval -errno on error.
669  */
670 int llapi_hsm_copytool_register(struct hsm_copytool_private **priv,
671                                 const char *mnt, int archive_count,
672                                 int *archives, int rfd_flags)
673 {
674         struct hsm_copytool_private     *ct;
675         int                              rc;
676
677         if (archive_count > 0 && archives == NULL) {
678                 llapi_err_noerrno(LLAPI_MSG_ERROR,
679                                   "NULL archive numbers");
680                 return -EINVAL;
681         }
682
683         if (archive_count > LL_HSM_MAX_ARCHIVE) {
684                 llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when maximum "
685                                   "of %zu archives supported", archive_count,
686                                   LL_HSM_MAX_ARCHIVE);
687                 return -EINVAL;
688         }
689
690         ct = calloc(1, sizeof(*ct));
691         if (ct == NULL)
692                 return -ENOMEM;
693
694         ct->magic = CT_PRIV_MAGIC;
695         ct->mnt_fd = -1;
696         ct->open_by_fid_fd = -1;
697         ct->kuc.lk_rfd = LK_NOFD;
698         ct->kuc.lk_wfd = LK_NOFD;
699
700         ct->mnt = strdup(mnt);
701         if (ct->mnt == NULL) {
702                 rc = -ENOMEM;
703                 goto out_err;
704         }
705
706         ct->kuch = malloc(HAL_MAXSIZE + sizeof(*ct->kuch));
707         if (ct->kuch == NULL) {
708                 rc = -ENOMEM;
709                 goto out_err;
710         }
711
712         ct->mnt_fd = open(ct->mnt, O_RDONLY);
713         if (ct->mnt_fd < 0) {
714                 rc = -errno;
715                 goto out_err;
716         }
717
718         ct->open_by_fid_fd = openat(ct->mnt_fd, OPEN_BY_FID_PATH, O_RDONLY);
719         if (ct->open_by_fid_fd < 0) {
720                 rc = -errno;
721                 goto out_err;
722         }
723
724         /* no archives specified means "match all". */
725         ct->archives = 0;
726         for (rc = 0; rc < archive_count; rc++) {
727                 if ((archives[rc] > LL_HSM_MAX_ARCHIVE) || (archives[rc] < 0)) {
728                         llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when "
729                                           "archive id [0 - %zu] is supported",
730                                           archives[rc], LL_HSM_MAX_ARCHIVE);
731                         rc = -EINVAL;
732                         goto out_err;
733                 }
734                 /* in the list we have an all archive wildcard
735                  * so move to all archives mode
736                  */
737                 if (archives[rc] == 0) {
738                         ct->archives = 0;
739                         archive_count = 0;
740                         break;
741                 }
742                 ct->archives |= (1 << (archives[rc] - 1));
743         }
744
745         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM, rfd_flags);
746         if (rc < 0)
747                 goto out_err;
748
749         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
750         ct->kuc.lk_data = ct->archives;
751         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, &ct->kuc);
752         if (rc < 0) {
753                 rc = -errno;
754                 llapi_error(LLAPI_MSG_ERROR, rc,
755                             "cannot start copytool on '%s'", mnt);
756                 goto out_kuc;
757         }
758
759         llapi_hsm_log_ct_registration(&ct, CT_REGISTER);
760
761         /* Only the kernel reference keeps the write side open */
762         close(ct->kuc.lk_wfd);
763         ct->kuc.lk_wfd = LK_NOFD;
764         *priv = ct;
765
766         return 0;
767
768 out_kuc:
769         /* cleanup the kuc channel */
770         libcfs_ukuc_stop(&ct->kuc);
771
772 out_err:
773         if (!(ct->mnt_fd < 0))
774                 close(ct->mnt_fd);
775
776         if (!(ct->open_by_fid_fd < 0))
777                 close(ct->open_by_fid_fd);
778
779         free(ct->mnt);
780
781         free(ct->kuch);
782
783         free(ct);
784
785         return rc;
786 }
787
788 /** Deregister a copytool
789  * Note: under Linux, until llapi_hsm_copytool_unregister is called
790  * (or the program is killed), the libcfs module will be referenced
791  * and unremovable, even after Lustre services stop.
792  */
793 int llapi_hsm_copytool_unregister(struct hsm_copytool_private **priv)
794 {
795         struct hsm_copytool_private *ct;
796
797         if (priv == NULL || *priv == NULL)
798                 return -EINVAL;
799
800         ct = *priv;
801         if (ct->magic != CT_PRIV_MAGIC)
802                 return -EINVAL;
803
804         /* Tell the kernel to stop sending us messages */
805         ct->kuc.lk_flags = LK_FLG_STOP;
806         ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, &ct->kuc);
807
808         /* Shut down the kernelcomms */
809         libcfs_ukuc_stop(&ct->kuc);
810
811         llapi_hsm_log_ct_registration(&ct, CT_UNREGISTER);
812
813         close(ct->open_by_fid_fd);
814         close(ct->mnt_fd);
815         free(ct->mnt);
816         free(ct->kuch);
817         free(ct);
818         *priv = NULL;
819
820         return 0;
821 }
822
823 /** Returns a file descriptor to poll/select on.
824  * \param ct Opaque private control structure
825  * \retval -EINVAL on error
826  * \retval the file descriptor for reading HSM events from the kernel
827  */
828 int llapi_hsm_copytool_get_fd(struct hsm_copytool_private *ct)
829 {
830         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
831                 return -EINVAL;
832
833         return libcfs_ukuc_get_rfd(&ct->kuc);
834 }
835
836 /** Wait for the next hsm_action_list
837  * \param ct Opaque private control structure
838  * \param halh Action list handle, will be allocated here
839  * \param msgsize Number of bytes in the message, will be set here
840  * \return 0 valid message received; halh and msgsize are set
841  *         <0 error code
842  * Note: The application must not call llapi_hsm_copytool_recv until it has
843  * cleared the data in ct->kuch from the previous call.
844  */
845 int llapi_hsm_copytool_recv(struct hsm_copytool_private *ct,
846                             struct hsm_action_list **halh, int *msgsize)
847 {
848         struct kuc_hdr          *kuch;
849         struct hsm_action_list  *hal;
850         int                      rc = 0;
851
852         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
853                 return -EINVAL;
854
855         if (halh == NULL || msgsize == NULL)
856                 return -EINVAL;
857
858         kuch = ct->kuch;
859
860 repeat:
861         rc = libcfs_ukuc_msg_get(&ct->kuc, (char *)kuch,
862                                  HAL_MAXSIZE + sizeof(*kuch),
863                                  KUC_TRANSPORT_HSM);
864         if (rc < 0)
865                 goto out_err;
866
867         /* Handle generic messages */
868         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
869             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
870                 rc = -ESHUTDOWN;
871                 goto out_err;
872         }
873
874         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
875             kuch->kuc_msgtype != HMT_ACTION_LIST) {
876                 llapi_err_noerrno(LLAPI_MSG_ERROR,
877                                   "Unknown HSM message type %d:%d\n",
878                                   kuch->kuc_transport, kuch->kuc_msgtype);
879                 rc = -EPROTO;
880                 goto out_err;
881         }
882
883         if (kuch->kuc_msglen < sizeof(*kuch) + sizeof(*hal)) {
884                 llapi_err_noerrno(LLAPI_MSG_ERROR, "Short HSM message %d",
885                                   kuch->kuc_msglen);
886                 rc = -EPROTO;
887                 goto out_err;
888         }
889
890         /* Our message is a hsm_action_list. Use pointer math to skip
891         * kuch_hdr and point directly to the message payload.
892         */
893         hal = (struct hsm_action_list *)(kuch + 1);
894
895         /* Check that we have registered for this archive #
896          * if 0 registered, we serve any archive */
897         if (ct->archives &&
898             ((1 << (hal->hal_archive_id - 1)) & ct->archives) == 0) {
899                 llapi_err_noerrno(LLAPI_MSG_INFO,
900                                   "This copytool does not service archive #%d,"
901                                   " ignoring this request."
902                                   " Mask of served archive is 0x%.8X",
903                                   hal->hal_archive_id, ct->archives);
904
905                 goto repeat;
906         }
907
908         *halh = hal;
909         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
910         return 0;
911
912 out_err:
913         *halh = NULL;
914         *msgsize = 0;
915         return rc;
916 }
917
918 /** Get parent path from mount point and fid.
919  *
920  * \param mnt        Filesystem root path.
921  * \param fid        Object FID.
922  * \param parent     Destination buffer.
923  * \param parent_len Destination buffer size.
924  * \return 0 on success.
925  */
926 static int fid_parent(const char *mnt, const lustre_fid *fid, char *parent,
927                       size_t parent_len)
928 {
929         int              rc;
930         int              linkno = 0;
931         long long        recno = -1;
932         char             file[PATH_MAX];
933         char             strfid[FID_NOBRACE_LEN + 1];
934         char            *ptr;
935
936         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(fid));
937
938         rc = llapi_fid2path(mnt, strfid, file, sizeof(file),
939                             &recno, &linkno);
940         if (rc < 0)
941                 return rc;
942
943         /* fid2path returns a relative path */
944         rc = snprintf(parent, parent_len, "%s/%s", mnt, file);
945         if (rc >= parent_len)
946                 return -ENAMETOOLONG;
947
948         /* remove file name */
949         ptr = strrchr(parent, '/');
950         if (ptr == NULL || ptr == parent) {
951                 rc = -EINVAL;
952         } else {
953                 *ptr = '\0';
954                 rc = 0;
955         }
956
957         return rc;
958 }
959
960 static int ct_open_by_fid(const struct hsm_copytool_private *ct,
961                           const struct lu_fid *fid, int open_flags)
962 {
963         char fid_name[FID_NOBRACE_LEN + 1];
964         int fd;
965
966         snprintf(fid_name, sizeof(fid_name), DFID_NOBRACE, PFID(fid));
967
968         fd = openat(ct->open_by_fid_fd, fid_name, open_flags);
969         return fd < 0 ? -errno : fd;
970 }
971
972 /**
973  * Get metadata attributes of file by FID.
974  *
975  * Use the IOC_MDC_GETFILEINFO ioctl (to send a MDS_GETATTR_NAME RPC)
976  * to get the attributes of the file identified by \a fid. This
977  * returns only the attributes stored on the MDT and avoids taking
978  * layout locks or accessing OST objects. It also bypasses the inode
979  * cache. Attributes are returned in \a st.
980  */
981 static int ct_md_getattr(const struct hsm_copytool_private *ct,
982                          const struct lu_fid *fid,
983                          lstat_t *st)
984 {
985         struct lov_user_mds_data *lmd;
986         size_t lmd_size;
987         int rc;
988
989         lmd_size = sizeof(lmd->lmd_st) +
990                 lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
991
992         if (lmd_size < sizeof(lmd->lmd_st) + XATTR_SIZE_MAX)
993                 lmd_size = sizeof(lmd->lmd_st) + XATTR_SIZE_MAX;
994
995         if (lmd_size < FID_NOBRACE_LEN + 1)
996                 lmd_size = FID_NOBRACE_LEN + 1;
997
998         lmd = malloc(lmd_size);
999         if (lmd == NULL)
1000                 return -ENOMEM;
1001
1002         snprintf((char *)lmd, lmd_size, DFID_NOBRACE, PFID(fid));
1003
1004         rc = ioctl(ct->open_by_fid_fd, IOC_MDC_GETFILEINFO, lmd);
1005         if (rc != 0) {
1006                 rc = -errno;
1007                 llapi_error(LLAPI_MSG_ERROR, rc,
1008                             "cannot get metadata attributes of "DFID" in '%s'",
1009                             PFID(fid), ct->mnt);
1010                 goto out;
1011         }
1012
1013         *st = lmd->lmd_st;
1014 out:
1015         free(lmd);
1016
1017         return rc;
1018 }
1019
1020 /** Create the destination volatile file for a restore operation.
1021  *
1022  * \param hcp        Private copyaction handle.
1023  * \param mdt_index  MDT index where to create the volatile file.
1024  * \param flags      Volatile file creation flags.
1025  * \return 0 on success.
1026  */
1027 static int create_restore_volatile(struct hsm_copyaction_private *hcp,
1028                                    int mdt_index, int open_flags)
1029 {
1030         int                      rc;
1031         int                      fd;
1032         char                     parent[PATH_MAX + 1];
1033         const char              *mnt = hcp->ct_priv->mnt;
1034         struct hsm_action_item  *hai = &hcp->copy.hc_hai;
1035
1036         rc = fid_parent(mnt, &hai->hai_fid, parent, sizeof(parent));
1037         if (rc < 0) {
1038                 /* fid_parent() failed, try to keep on going */
1039                 llapi_error(LLAPI_MSG_ERROR, rc,
1040                             "cannot get parent path to restore "DFID" "
1041                             "using '%s'", PFID(&hai->hai_fid), mnt);
1042                 snprintf(parent, sizeof(parent), "%s", mnt);
1043         }
1044
1045         fd = llapi_create_volatile_idx(parent, mdt_index, open_flags);
1046         if (fd < 0)
1047                 return fd;
1048
1049         rc = fchown(fd, hcp->stat.st_uid, hcp->stat.st_gid);
1050         if (rc < 0)
1051                 goto err_cleanup;
1052
1053         rc = llapi_fd2fid(fd, &hai->hai_dfid);
1054         if (rc < 0)
1055                 goto err_cleanup;
1056
1057         hcp->data_fd = fd;
1058
1059         return 0;
1060
1061 err_cleanup:
1062         hcp->data_fd = -1;
1063         close(fd);
1064
1065         return rc;
1066 }
1067
1068 /** Start processing an HSM action.
1069  * Should be called by copytools just before starting handling a request.
1070  * It could be skipped if copytool only want to directly report an error,
1071  * \see llapi_hsm_action_end().
1072  *
1073  * \param hcp                Opaque action handle to be passed to
1074  *                           llapi_hsm_action_progress and llapi_hsm_action_end.
1075  * \param ct                 Copytool handle acquired at registration.
1076  * \param hai                The hsm_action_item describing the request.
1077  * \param restore_mdt_index  On restore: MDT index where to create the volatile
1078  *                           file. Use -1 for default.
1079  * \param restore_open_flags On restore: volatile file creation mode. Use
1080  *                           O_LOV_DELAY_CREATE to manually set the LOVEA
1081  *                           afterwards.
1082  * \param is_error           Whether this call is just to report an error.
1083  *
1084  * \return 0 on success.
1085  */
1086 int llapi_hsm_action_begin(struct hsm_copyaction_private **phcp,
1087                            const struct hsm_copytool_private *ct,
1088                            const struct hsm_action_item *hai,
1089                            int restore_mdt_index, int restore_open_flags,
1090                            bool is_error)
1091 {
1092         struct hsm_copyaction_private   *hcp;
1093         int                              rc;
1094
1095         hcp = calloc(1, sizeof(*hcp));
1096         if (hcp == NULL)
1097                 return -ENOMEM;
1098
1099         hcp->data_fd = -1;
1100         hcp->ct_priv = ct;
1101         hcp->copy.hc_hai = *hai;
1102         hcp->copy.hc_hai.hai_len = sizeof(*hai);
1103
1104         if (is_error)
1105                 goto ok_out;
1106
1107         if (hai->hai_action == HSMA_RESTORE) {
1108                 rc = ct_md_getattr(hcp->ct_priv, &hai->hai_fid, &hcp->stat);
1109                 if (rc < 0)
1110                         goto err_out;
1111
1112                 rc = create_restore_volatile(hcp, restore_mdt_index,
1113                                              restore_open_flags);
1114                 if (rc < 0)
1115                         goto err_out;
1116         }
1117
1118         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_COPY_START, &hcp->copy);
1119         if (rc < 0) {
1120                 rc = -errno;
1121                 goto err_out;
1122         }
1123
1124         llapi_hsm_log_ct_progress(&hcp, hai, CT_START, 0, 0);
1125
1126 ok_out:
1127         hcp->magic = CP_PRIV_MAGIC;
1128         *phcp = hcp;
1129         return 0;
1130
1131 err_out:
1132         if (!(hcp->data_fd < 0))
1133                 close(hcp->data_fd);
1134
1135         free(hcp);
1136
1137         return rc;
1138 }
1139
1140 /** Terminate an HSM action processing.
1141  * Should be called by copytools just having finished handling the request.
1142  * \param hdl[in,out]  Handle returned by llapi_hsm_action_start.
1143  * \param he[in]       The final range of copied data (for copy actions).
1144  * \param errval[in]   The status code of the operation.
1145  * \param flags[in]    The flags about the termination status (HP_FLAG_RETRY if
1146  *                     the error is retryable).
1147  *
1148  * \return 0 on success.
1149  */
1150 int llapi_hsm_action_end(struct hsm_copyaction_private **phcp,
1151                          const struct hsm_extent *he, int hp_flags, int errval)
1152 {
1153         struct hsm_copyaction_private   *hcp;
1154         struct hsm_action_item          *hai;
1155         int                              rc;
1156
1157         if (phcp == NULL || *phcp == NULL || he == NULL)
1158                 return -EINVAL;
1159
1160         hcp = *phcp;
1161
1162         if (hcp->magic != CP_PRIV_MAGIC)
1163                 return -EINVAL;
1164
1165         hai = &hcp->copy.hc_hai;
1166
1167         if (hai->hai_action == HSMA_RESTORE && errval == 0) {
1168                 struct timeval tv[2];
1169
1170                 /* Set {a,m}time of volatile file to that of original. */
1171                 tv[0].tv_sec = hcp->stat.st_atime;
1172                 tv[0].tv_usec = 0;
1173                 tv[1].tv_sec = hcp->stat.st_mtime;
1174                 tv[1].tv_usec = 0;
1175                 if (futimes(hcp->data_fd, tv) < 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