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