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