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