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