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