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