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