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