Whamcloud - gitweb
LU-10308 misc: update Intel copyright messages for 2017
[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, 2017, 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 <linux/lnet/lnetctl.h>
61 #include <lustre/lustreapi.h>
62 #include "lustreapi_internal.h"
63
64 #define OPEN_BY_FID_PATH dot_lustre_name"/fid"
65
66 /****** HSM Copytool API ********/
67 #define CT_PRIV_MAGIC 0xC0BE2001
68 struct hsm_copytool_private {
69         int                      magic;
70         char                    *mnt;
71         struct kuc_hdr          *kuch;
72         int                      mnt_fd;
73         int                      open_by_fid_fd;
74         struct lustre_kernelcomm kuc;
75         __u32                    archives;
76 };
77
78 #define CP_PRIV_MAGIC 0x19880429
79 struct hsm_copyaction_private {
80         __u32                                    magic;
81         __u32                                    source_fd;
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
439 cancel:
440         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
441                                  (char *)llapi_hsm_ct_ev2str(hai->hai_action +
442                                                              progress_type));
443         if (rc < 0)
444                 goto err;
445
446         rc = llapi_hsm_write_json_event(&json_items);
447         if (rc < 0)
448                 goto err;
449
450         goto out_free;
451
452 err:
453         llapi_error(LLAPI_MSG_ERROR, rc, "error in "
454                     "llapi_hsm_log_ct_progress()");
455
456 out_free:
457         if (json_items != NULL)
458                 llapi_json_destroy_list(&json_items);
459
460         return rc;
461 }
462
463 /**
464  * Given a path to a FIFO, create a filehandle for nonblocking writes to it.
465  * Intended to be used for copytool monitoring processes that read an
466  * event stream from the FIFO. Events written in the absence of a reader
467  * are lost.
468  *
469  * \param path               Path to monitor FIFO.
470  *
471  * \retval 0 on success.
472  * \retval -errno on error.
473  */
474 int llapi_hsm_register_event_fifo(const char *path)
475 {
476         int read_fd;
477         struct stat statbuf;
478         struct sigaction ignore_action;
479         int rc;
480
481         /* Create the FIFO if necessary. */
482         if ((mkfifo(path, 0644) < 0) && (errno != EEXIST)) {
483                 llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed", path);
484                 return -errno;
485         }
486         if (errno == EEXIST) {
487                 if (stat(path, &statbuf) < 0) {
488                         llapi_error(LLAPI_MSG_ERROR, errno, "mkfifo(%s) failed",
489                                     path);
490                         return -errno;
491                 }
492                 if (!S_ISFIFO(statbuf.st_mode) ||
493                     ((statbuf.st_mode & 0777) != 0644)) {
494                         llapi_error(LLAPI_MSG_ERROR, errno, "%s exists but is "
495                                     "not a pipe or has a wrong mode", path);
496                         return -errno;
497                 }
498         } else {
499                 created_hsm_event_fifo = true;
500         }
501
502         /* Open the FIFO for read so that the subsequent open for write
503          * doesn't immediately fail. */
504         read_fd = open(path, O_RDONLY | O_NONBLOCK);
505         if (read_fd < 0) {
506                 llapi_error(LLAPI_MSG_ERROR, errno,
507                             "cannot open(%s) for read", path);
508                 return -errno;
509         }
510
511         /* Open the FIFO for writes, but don't block on waiting
512          * for a reader. */
513         llapi_hsm_event_fd = open(path, O_WRONLY | O_NONBLOCK);
514         rc = -errno;
515
516         /* Now close the reader. An external monitoring process can
517          * now open the FIFO for reads. If no reader comes along the
518          * events are lost. NOTE: Only one reader at a time! */
519         close(read_fd);
520
521         if (llapi_hsm_event_fd < 0) {
522                 llapi_error(LLAPI_MSG_ERROR, -rc,
523                             "cannot open(%s) for write", path);
524                 return rc;
525         }
526
527         /* Ignore SIGPIPEs -- can occur if the reader goes away. */
528         memset(&ignore_action, 0, sizeof(ignore_action));
529         ignore_action.sa_handler = SIG_IGN;
530         sigemptyset(&ignore_action.sa_mask);
531         sigaction(SIGPIPE, &ignore_action, NULL);
532
533         return 0;
534 }
535
536 /**
537  * Given a path to a FIFO, close its filehandle and delete the FIFO.
538  *
539  * \param path               Path to monitor FIFO.
540  *
541  * \retval 0 on success.
542  * \retval -errno on error.
543  */
544 int llapi_hsm_unregister_event_fifo(const char *path)
545 {
546         /* Noop unless the event fd was initialized */
547         if (llapi_hsm_event_fd < 0)
548                 return 0;
549
550         if (close(llapi_hsm_event_fd) < 0)
551                 return -errno;
552
553         if (created_hsm_event_fifo) {
554                 unlink(path);
555                 created_hsm_event_fifo = false;
556         }
557
558         llapi_hsm_event_fd = -1;
559
560         return 0;
561 }
562
563 /**
564  * Custom logging callback to be used when a monitoring FIFO has been
565  * registered. Formats log entries as JSON events suitable for
566  * consumption by a copytool monitoring process.
567  *
568  * \param level              The message loglevel.
569  * \param _rc                The returncode associated with the message.
570  * \param fmt                The message format string.
571  * \param args               Arguments to be formatted by the format string.
572  *
573  * \retval None.
574  */
575 void llapi_hsm_log_error(enum llapi_message_level level, int _rc,
576                          const char *fmt, va_list args)
577 {
578         int                             rc;
579         int                             msg_len;
580         int                             real_level;
581         char                            *msg = NULL;
582         va_list                         args2;
583         struct llapi_json_item_list     *json_items;
584
585         /* Noop unless the event fd was initialized */
586         if (llapi_hsm_event_fd < 0)
587                 return;
588
589         rc = llapi_json_init_list(&json_items);
590         if (rc < 0)
591                 goto err;
592
593         if ((level & LLAPI_MSG_NO_ERRNO) == 0) {
594                 rc = llapi_json_add_item(&json_items, "errno",
595                                          LLAPI_JSON_INTEGER,
596                                          &_rc);
597                 if (rc < 0)
598                         goto err;
599
600                 rc = llapi_json_add_item(&json_items, "error",
601                                          LLAPI_JSON_STRING,
602                                          strerror(abs(_rc)));
603                 if (rc < 0)
604                         goto err;
605         }
606
607         va_copy(args2, args);
608         msg_len = vsnprintf(NULL, 0, fmt, args2) + 1;
609         va_end(args2);
610         if (msg_len >= 0) {
611                 msg = (char *) alloca(msg_len);
612                 if (msg == NULL) {
613                         rc = -ENOMEM;
614                         goto err;
615                 }
616
617                 rc = vsnprintf(msg, msg_len, fmt, args);
618                 if (rc < 0)
619                         goto err;
620
621                 rc = llapi_json_add_item(&json_items, "message",
622                                          LLAPI_JSON_STRING,
623                                          msg);
624                 if (rc < 0)
625                         goto err;
626         } else {
627                 rc = llapi_json_add_item(&json_items, "message",
628                                          LLAPI_JSON_STRING,
629                                          "INTERNAL ERROR: message failed");
630                 if (rc < 0)
631                         goto err;
632         }
633
634         real_level = level & LLAPI_MSG_NO_ERRNO;
635         real_level = real_level > 0 ? level - LLAPI_MSG_NO_ERRNO : level;
636
637         rc = llapi_json_add_item(&json_items, "level", LLAPI_JSON_STRING,
638                                  (void *)llapi_msg_level2str(real_level));
639         if (rc < 0)
640                 goto err;
641
642         rc = llapi_json_add_item(&json_items, "event_type", LLAPI_JSON_STRING,
643                                  "LOGGED_MESSAGE");
644         if (rc < 0)
645                 goto err;
646
647         rc = llapi_hsm_write_json_event(&json_items);
648         if (rc < 0)
649                 goto err;
650
651         goto out_free;
652
653 err:
654         /* Write directly to stderr to avoid llapi_error, which now
655          * emits JSON event messages. */
656         fprintf(stderr, "\nFATAL ERROR IN llapi_hsm_log_error(): rc %d,", rc);
657
658 out_free:
659         if (json_items != NULL)
660                 llapi_json_destroy_list(&json_items);
661
662         return;
663 }
664
665 /** Register a copytool
666  * \param[out] priv             Opaque private control structure
667  * \param mnt                   Lustre filesystem mount point
668  * \param archive_count         Number of valid archive IDs in \a archives
669  * \param archives              Which archive numbers this copytool is
670  *                              responsible for
671  * \param rfd_flags             flags applied to read fd of pipe
672  *                              (e.g. O_NONBLOCK)
673  *
674  * \retval 0 on success.
675  * \retval -errno on error.
676  */
677 int llapi_hsm_copytool_register(struct hsm_copytool_private **priv,
678                                 const char *mnt, int archive_count,
679                                 int *archives, int rfd_flags)
680 {
681         struct hsm_copytool_private     *ct;
682         int                              rc;
683
684         if (archive_count > 0 && archives == NULL) {
685                 llapi_err_noerrno(LLAPI_MSG_ERROR,
686                                   "NULL archive numbers");
687                 return -EINVAL;
688         }
689
690         if (archive_count > LL_HSM_MAX_ARCHIVE) {
691                 llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when maximum "
692                                   "of %zu archives supported", archive_count,
693                                   LL_HSM_MAX_ARCHIVE);
694                 return -EINVAL;
695         }
696
697         ct = calloc(1, sizeof(*ct));
698         if (ct == NULL)
699                 return -ENOMEM;
700
701         ct->magic = CT_PRIV_MAGIC;
702         ct->mnt_fd = -1;
703         ct->open_by_fid_fd = -1;
704         ct->kuc.lk_rfd = LK_NOFD;
705         ct->kuc.lk_wfd = LK_NOFD;
706
707         ct->mnt = strdup(mnt);
708         if (ct->mnt == NULL) {
709                 rc = -ENOMEM;
710                 goto out_err;
711         }
712
713         ct->kuch = malloc(HAL_MAXSIZE + sizeof(*ct->kuch));
714         if (ct->kuch == NULL) {
715                 rc = -ENOMEM;
716                 goto out_err;
717         }
718
719         ct->mnt_fd = open(ct->mnt, O_RDONLY);
720         if (ct->mnt_fd < 0) {
721                 rc = -errno;
722                 goto out_err;
723         }
724
725         ct->open_by_fid_fd = openat(ct->mnt_fd, OPEN_BY_FID_PATH, O_RDONLY);
726         if (ct->open_by_fid_fd < 0) {
727                 rc = -errno;
728                 goto out_err;
729         }
730
731         /* no archives specified means "match all". */
732         ct->archives = 0;
733         for (rc = 0; rc < archive_count; rc++) {
734                 if ((archives[rc] > LL_HSM_MAX_ARCHIVE) || (archives[rc] < 0)) {
735                         llapi_err_noerrno(LLAPI_MSG_ERROR, "%d requested when "
736                                           "archive id [0 - %zu] is supported",
737                                           archives[rc], LL_HSM_MAX_ARCHIVE);
738                         rc = -EINVAL;
739                         goto out_err;
740                 }
741                 /* in the list we have an all archive wildcard
742                  * so move to all archives mode
743                  */
744                 if (archives[rc] == 0) {
745                         ct->archives = 0;
746                         archive_count = 0;
747                         break;
748                 }
749                 ct->archives |= (1 << (archives[rc] - 1));
750         }
751
752         rc = libcfs_ukuc_start(&ct->kuc, KUC_GRP_HSM, rfd_flags);
753         if (rc < 0)
754                 goto out_err;
755
756         /* Storing archive(s) in lk_data; see mdc_ioc_hsm_ct_start */
757         ct->kuc.lk_data = ct->archives;
758         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, &ct->kuc);
759         if (rc < 0) {
760                 rc = -errno;
761                 llapi_error(LLAPI_MSG_ERROR, rc,
762                             "cannot start copytool on '%s'", mnt);
763                 goto out_kuc;
764         }
765
766         llapi_hsm_log_ct_registration(&ct, CT_REGISTER);
767
768         /* Only the kernel reference keeps the write side open */
769         close(ct->kuc.lk_wfd);
770         ct->kuc.lk_wfd = LK_NOFD;
771         *priv = ct;
772
773         return 0;
774
775 out_kuc:
776         /* cleanup the kuc channel */
777         libcfs_ukuc_stop(&ct->kuc);
778
779 out_err:
780         if (!(ct->mnt_fd < 0))
781                 close(ct->mnt_fd);
782
783         if (!(ct->open_by_fid_fd < 0))
784                 close(ct->open_by_fid_fd);
785
786         free(ct->mnt);
787
788         free(ct->kuch);
789
790         free(ct);
791
792         return rc;
793 }
794
795 /** Deregister a copytool
796  * Note: under Linux, until llapi_hsm_copytool_unregister is called
797  * (or the program is killed), the libcfs module will be referenced
798  * and unremovable, even after Lustre services stop.
799  */
800 int llapi_hsm_copytool_unregister(struct hsm_copytool_private **priv)
801 {
802         struct hsm_copytool_private *ct;
803
804         if (priv == NULL || *priv == NULL)
805                 return -EINVAL;
806
807         ct = *priv;
808         if (ct->magic != CT_PRIV_MAGIC)
809                 return -EINVAL;
810
811         /* Close the read side of the KUC pipe. This should be done
812          * before unregistering to avoid deadlock: a ldlm_cb thread
813          * enters libcfs_kkuc_group_put() acquires kg_sem and blocks
814          * in pipe_write() due to full pipe; then we attempt to
815          * unregister and block on kg_sem. */
816         libcfs_ukuc_stop(&ct->kuc);
817
818         /* Tell the kernel to stop sending us messages */
819         ct->kuc.lk_flags = LK_FLG_STOP;
820         ioctl(ct->mnt_fd, LL_IOC_HSM_CT_START, &ct->kuc);
821
822         llapi_hsm_log_ct_registration(&ct, CT_UNREGISTER);
823
824         close(ct->open_by_fid_fd);
825         close(ct->mnt_fd);
826         free(ct->mnt);
827         free(ct->kuch);
828         free(ct);
829         *priv = NULL;
830
831         return 0;
832 }
833
834 /** Returns a file descriptor to poll/select on.
835  * \param ct Opaque private control structure
836  * \retval -EINVAL on error
837  * \retval the file descriptor for reading HSM events from the kernel
838  */
839 int llapi_hsm_copytool_get_fd(struct hsm_copytool_private *ct)
840 {
841         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
842                 return -EINVAL;
843
844         return libcfs_ukuc_get_rfd(&ct->kuc);
845 }
846
847 /** Wait for the next hsm_action_list
848  * \param ct Opaque private control structure
849  * \param halh Action list handle, will be allocated here
850  * \param msgsize Number of bytes in the message, will be set here
851  * \return 0 valid message received; halh and msgsize are set
852  *         <0 error code
853  * Note: The application must not call llapi_hsm_copytool_recv until it has
854  * cleared the data in ct->kuch from the previous call.
855  */
856 int llapi_hsm_copytool_recv(struct hsm_copytool_private *ct,
857                             struct hsm_action_list **halh, int *msgsize)
858 {
859         struct kuc_hdr          *kuch;
860         struct hsm_action_list  *hal;
861         int                      rc = 0;
862
863         if (ct == NULL || ct->magic != CT_PRIV_MAGIC)
864                 return -EINVAL;
865
866         if (halh == NULL || msgsize == NULL)
867                 return -EINVAL;
868
869         kuch = ct->kuch;
870
871 repeat:
872         rc = libcfs_ukuc_msg_get(&ct->kuc, (char *)kuch,
873                                  HAL_MAXSIZE + sizeof(*kuch),
874                                  KUC_TRANSPORT_HSM);
875         if (rc < 0)
876                 goto out_err;
877
878         /* Handle generic messages */
879         if (kuch->kuc_transport == KUC_TRANSPORT_GENERIC &&
880             kuch->kuc_msgtype == KUC_MSG_SHUTDOWN) {
881                 rc = -ESHUTDOWN;
882                 goto out_err;
883         }
884
885         if (kuch->kuc_transport != KUC_TRANSPORT_HSM ||
886             kuch->kuc_msgtype != HMT_ACTION_LIST) {
887                 llapi_err_noerrno(LLAPI_MSG_ERROR,
888                                   "Unknown HSM message type %d:%d\n",
889                                   kuch->kuc_transport, kuch->kuc_msgtype);
890                 rc = -EPROTO;
891                 goto out_err;
892         }
893
894         if (kuch->kuc_msglen < sizeof(*kuch) + sizeof(*hal)) {
895                 llapi_err_noerrno(LLAPI_MSG_ERROR, "Short HSM message %d",
896                                   kuch->kuc_msglen);
897                 rc = -EPROTO;
898                 goto out_err;
899         }
900
901         /* Our message is a hsm_action_list. Use pointer math to skip
902         * kuch_hdr and point directly to the message payload.
903         */
904         hal = (struct hsm_action_list *)(kuch + 1);
905
906         /* Check that we have registered for this archive #
907          * if 0 registered, we serve any archive */
908         if (ct->archives &&
909             ((1 << (hal->hal_archive_id - 1)) & ct->archives) == 0) {
910                 llapi_err_noerrno(LLAPI_MSG_INFO,
911                                   "This copytool does not service archive #%d,"
912                                   " ignoring this request."
913                                   " Mask of served archive is 0x%.8X",
914                                   hal->hal_archive_id, ct->archives);
915
916                 goto repeat;
917         }
918
919         *halh = hal;
920         *msgsize = kuch->kuc_msglen - sizeof(*kuch);
921         return 0;
922
923 out_err:
924         *halh = NULL;
925         *msgsize = 0;
926         return rc;
927 }
928
929 /** Get parent path from mount point and fid.
930  *
931  * \param mnt        Filesystem root path.
932  * \param fid        Object FID.
933  * \param parent     Destination buffer.
934  * \param parent_len Destination buffer size.
935  * \return 0 on success.
936  */
937 static int fid_parent(const char *mnt, const struct lu_fid *fid, char *parent,
938                       size_t parent_len)
939 {
940         int              rc;
941         int              linkno = 0;
942         long long        recno = -1;
943         char             file[PATH_MAX];
944         char             strfid[FID_NOBRACE_LEN + 1];
945         char            *ptr;
946
947         snprintf(strfid, sizeof(strfid), DFID_NOBRACE, PFID(fid));
948
949         rc = llapi_fid2path(mnt, strfid, file, sizeof(file),
950                             &recno, &linkno);
951         if (rc < 0)
952                 return rc;
953
954         /* fid2path returns a relative path */
955         rc = snprintf(parent, parent_len, "%s/%s", mnt, file);
956         if (rc >= parent_len)
957                 return -ENAMETOOLONG;
958
959         /* remove file name */
960         ptr = strrchr(parent, '/');
961         if (ptr == NULL || ptr == parent) {
962                 rc = -EINVAL;
963         } else {
964                 *ptr = '\0';
965                 rc = 0;
966         }
967
968         return rc;
969 }
970
971 static int ct_open_by_fid(const struct hsm_copytool_private *ct,
972                           const struct lu_fid *fid, int open_flags)
973 {
974         char fid_name[FID_NOBRACE_LEN + 1];
975         int fd;
976
977         snprintf(fid_name, sizeof(fid_name), DFID_NOBRACE, PFID(fid));
978
979         fd = openat(ct->open_by_fid_fd, fid_name, open_flags);
980         return fd < 0 ? -errno : fd;
981 }
982
983 /**
984  * Get metadata attributes of file by FID.
985  *
986  * Use the IOC_MDC_GETFILEINFO ioctl (to send a MDS_GETATTR_NAME RPC)
987  * to get the attributes of the file identified by \a fid. This
988  * returns only the attributes stored on the MDT and avoids taking
989  * layout locks or accessing OST objects. It also bypasses the inode
990  * cache. Attributes are returned in \a st.
991  */
992 static int ct_md_getattr(const struct hsm_copytool_private *ct,
993                          const struct lu_fid *fid,
994                          lstat_t *st)
995 {
996         struct lov_user_mds_data *lmd;
997         size_t lmd_size;
998         int rc;
999
1000         lmd_size = sizeof(lmd->lmd_st) +
1001                 lov_user_md_size(LOV_MAX_STRIPE_COUNT, LOV_USER_MAGIC_V3);
1002
1003         if (lmd_size < sizeof(lmd->lmd_st) + XATTR_SIZE_MAX)
1004                 lmd_size = sizeof(lmd->lmd_st) + XATTR_SIZE_MAX;
1005
1006         if (lmd_size < FID_NOBRACE_LEN + 1)
1007                 lmd_size = FID_NOBRACE_LEN + 1;
1008
1009         lmd = malloc(lmd_size);
1010         if (lmd == NULL)
1011                 return -ENOMEM;
1012
1013         snprintf((char *)lmd, lmd_size, DFID_NOBRACE, PFID(fid));
1014
1015         rc = ioctl(ct->open_by_fid_fd, IOC_MDC_GETFILEINFO, lmd);
1016         if (rc != 0) {
1017                 rc = -errno;
1018                 llapi_error(LLAPI_MSG_ERROR, rc,
1019                             "cannot get metadata attributes of "DFID" in '%s'",
1020                             PFID(fid), ct->mnt);
1021                 goto out;
1022         }
1023
1024         *st = lmd->lmd_st;
1025 out:
1026         free(lmd);
1027
1028         return rc;
1029 }
1030
1031 /** Create the destination volatile file for a restore operation.
1032  *
1033  * \param hcp        Private copyaction handle.
1034  * \param mdt_index  MDT index where to create the volatile file.
1035  * \param flags      Volatile file creation flags.
1036  * \return 0 on success.
1037  */
1038 static int create_restore_volatile(struct hsm_copyaction_private *hcp,
1039                                    int mdt_index, int open_flags)
1040 {
1041         int                      rc;
1042         int                      fd;
1043         char                     parent[PATH_MAX + 1];
1044         const char              *mnt = hcp->ct_priv->mnt;
1045         struct hsm_action_item  *hai = &hcp->copy.hc_hai;
1046
1047         rc = fid_parent(mnt, &hai->hai_fid, parent, sizeof(parent));
1048         if (rc < 0) {
1049                 /* fid_parent() failed, try to keep on going */
1050                 llapi_error(LLAPI_MSG_ERROR, rc,
1051                             "cannot get parent path to restore "DFID" "
1052                             "using '%s'", PFID(&hai->hai_fid), mnt);
1053                 snprintf(parent, sizeof(parent), "%s", mnt);
1054         }
1055
1056         fd = llapi_create_volatile_idx(parent, mdt_index, open_flags);
1057         if (fd < 0)
1058                 return fd;
1059
1060         rc = fchown(fd, hcp->stat.st_uid, hcp->stat.st_gid);
1061         if (rc < 0)
1062                 goto err_cleanup;
1063
1064         rc = llapi_fd2fid(fd, &hai->hai_dfid);
1065         if (rc < 0)
1066                 goto err_cleanup;
1067
1068         hcp->data_fd = fd;
1069
1070         return 0;
1071
1072 err_cleanup:
1073         hcp->data_fd = -1;
1074         close(fd);
1075
1076         return rc;
1077 }
1078
1079 /** Start processing an HSM action.
1080  * Should be called by copytools just before starting handling a request.
1081  * It could be skipped if copytool only want to directly report an error,
1082  * \see llapi_hsm_action_end().
1083  *
1084  * \param hcp                Opaque action handle to be passed to
1085  *                           llapi_hsm_action_progress and llapi_hsm_action_end.
1086  * \param ct                 Copytool handle acquired at registration.
1087  * \param hai                The hsm_action_item describing the request.
1088  * \param restore_mdt_index  On restore: MDT index where to create the volatile
1089  *                           file. Use -1 for default.
1090  * \param restore_open_flags On restore: volatile file creation mode. Use
1091  *                           O_LOV_DELAY_CREATE to manually set the LOVEA
1092  *                           afterwards.
1093  * \param is_error           Whether this call is just to report an error.
1094  *
1095  * \return 0 on success.
1096  */
1097 int llapi_hsm_action_begin(struct hsm_copyaction_private **phcp,
1098                            const struct hsm_copytool_private *ct,
1099                            const struct hsm_action_item *hai,
1100                            int restore_mdt_index, int restore_open_flags,
1101                            bool is_error)
1102 {
1103         struct hsm_copyaction_private *hcp;
1104         int fd;
1105         int rc;
1106
1107         hcp = calloc(1, sizeof(*hcp));
1108         if (hcp == NULL)
1109                 return -ENOMEM;
1110
1111         hcp->source_fd = -1;
1112         hcp->data_fd = -1;
1113         hcp->ct_priv = ct;
1114         hcp->copy.hc_hai = *hai;
1115         hcp->copy.hc_hai.hai_len = sizeof(*hai);
1116
1117         if (is_error)
1118                 goto ok_out;
1119
1120         if (hai->hai_action == HSMA_ARCHIVE) {
1121                 fd = ct_open_by_fid(hcp->ct_priv, &hai->hai_dfid,
1122                                 O_RDONLY | O_NOATIME | O_NOFOLLOW | O_NONBLOCK);
1123                 if (fd < 0) {
1124                         rc = fd;
1125                         goto err_out;
1126                 }
1127
1128                 hcp->source_fd = fd;
1129         } else if (hai->hai_action == HSMA_RESTORE) {
1130                 rc = ct_md_getattr(hcp->ct_priv, &hai->hai_fid, &hcp->stat);
1131                 if (rc < 0)
1132                         goto err_out;
1133
1134                 rc = create_restore_volatile(hcp, restore_mdt_index,
1135                                              restore_open_flags);
1136                 if (rc < 0)
1137                         goto err_out;
1138         } else if (hai->hai_action == HSMA_REMOVE) {
1139                 /* Since remove is atomic there is no need to send an
1140                  * initial MDS_HSM_PROGRESS RPC. */
1141                 goto out_log;
1142         }
1143
1144         rc = ioctl(ct->mnt_fd, LL_IOC_HSM_COPY_START, &hcp->copy);
1145         if (rc < 0) {
1146                 rc = -errno;
1147                 goto err_out;
1148         }
1149
1150 out_log:
1151         llapi_hsm_log_ct_progress(&hcp, hai, CT_START, 0, 0);
1152
1153 ok_out:
1154         hcp->magic = CP_PRIV_MAGIC;
1155         *phcp = hcp;
1156         return 0;
1157
1158 err_out:
1159         if (!(hcp->source_fd < 0))
1160                 close(hcp->source_fd);
1161
1162         if (!(hcp->data_fd < 0))
1163                 close(hcp->data_fd);
1164
1165         free(hcp);
1166
1167         return rc;
1168 }
1169
1170 /** Terminate an HSM action processing.
1171  * Should be called by copytools just having finished handling the request.
1172  * \param hdl[in,out]  Handle returned by llapi_hsm_action_start.
1173  * \param he[in]       The final range of copied data (for copy actions).
1174  * \param errval[in]   The status code of the operation.
1175  * \param flags[in]    The flags about the termination status (HP_FLAG_RETRY if
1176  *                     the error is retryable).
1177  *
1178  * \return 0 on success.
1179  */
1180 int llapi_hsm_action_end(struct hsm_copyaction_private **phcp,
1181                          const struct hsm_extent *he, int hp_flags, int errval)
1182 {
1183         struct hsm_copyaction_private   *hcp;
1184         struct hsm_action_item          *hai;
1185         int                              rc;
1186
1187         if (phcp == NULL || *phcp == NULL || he == NULL)
1188                 return -EINVAL;
1189
1190         hcp = *phcp;
1191
1192         if (hcp->magic != CP_PRIV_MAGIC)
1193                 return -EINVAL;
1194
1195         hai = &hcp->copy.hc_hai;
1196
1197         if (hai->hai_action == HSMA_RESTORE && errval == 0) {
1198                 struct ll_futimes_3 lfu = {
1199                         .lfu_atime_sec = hcp->stat.st_atim.tv_sec,
1200                         .lfu_atime_nsec = hcp->stat.st_atim.tv_nsec,
1201                         .lfu_mtime_sec = hcp->stat.st_mtim.tv_sec,
1202                         .lfu_mtime_nsec = hcp->stat.st_mtim.tv_nsec,
1203                         .lfu_ctime_sec = hcp->stat.st_ctim.tv_sec,
1204                         .lfu_ctime_nsec = hcp->stat.st_ctim.tv_nsec,
1205                 };
1206
1207                 rc = fsync(hcp->data_fd);
1208                 if (rc < 0) {
1209                         errval = -errno;
1210                         goto end;
1211                 }
1212
1213                 /* Set {a,m,c}time of volatile file to that of original. */
1214                 rc = ioctl(hcp->data_fd, LL_IOC_FUTIMES_3, &lfu);
1215                 if (rc < 0) {
1216                         errval = -errno;
1217                         goto end;
1218                 }
1219         }
1220
1221 end:
1222         /* In some cases, like restore, 2 FIDs are used.
1223          * Set the right FID to use here. */
1224         if (hai->hai_action == HSMA_ARCHIVE || hai->hai_action == HSMA_RESTORE)
1225                 hai->hai_fid = hai->hai_dfid;
1226
1227         /* Fill the last missing data that will be needed by
1228          * kernel to send a hsm_progress. */
1229         hcp->copy.hc_flags  = hp_flags;
1230         hcp->copy.hc_errval = abs(errval);
1231
1232         hcp->copy.hc_hai.hai_extent = *he;
1233
1234         rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_COPY_END, &hcp->copy);
1235         if (rc) {
1236                 rc = -errno;
1237                 goto err_cleanup;
1238         }
1239
1240         llapi_hsm_log_ct_progress(&hcp, hai, CT_FINISH, 0, 0);
1241
1242 err_cleanup:
1243         if (!(hcp->source_fd < 0))
1244                 close(hcp->source_fd);
1245
1246         if (!(hcp->data_fd < 0))
1247                 close(hcp->data_fd);
1248
1249         free(hcp);
1250         *phcp = NULL;
1251
1252         return rc;
1253 }
1254
1255 /** Notify a progress in processing an HSM action.
1256  * \param hdl[in,out]   handle returned by llapi_hsm_action_start.
1257  * \param he[in]        the range of copied data (for copy actions).
1258  * \param total[in]     the expected total of copied data (for copy actions).
1259  * \param hp_flags[in]  HSM progress flags.
1260  * \return 0 on success.
1261  */
1262 int llapi_hsm_action_progress(struct hsm_copyaction_private *hcp,
1263                               const struct hsm_extent *he, __u64 total,
1264                               int hp_flags)
1265 {
1266         int                      rc;
1267         struct hsm_progress      hp;
1268         struct hsm_action_item  *hai;
1269
1270         if (hcp == NULL || he == NULL)
1271                 return -EINVAL;
1272
1273         if (hcp->magic != CP_PRIV_MAGIC)
1274                 return -EINVAL;
1275
1276         hai = &hcp->copy.hc_hai;
1277
1278         memset(&hp, 0, sizeof(hp));
1279
1280         hp.hp_cookie = hai->hai_cookie;
1281         hp.hp_flags  = hp_flags;
1282
1283         /* Progress is made on the data fid */
1284         hp.hp_fid = hai->hai_dfid;
1285         hp.hp_extent = *he;
1286
1287         rc = ioctl(hcp->ct_priv->mnt_fd, LL_IOC_HSM_PROGRESS, &hp);
1288         if (rc < 0)
1289                 rc = -errno;
1290
1291         llapi_hsm_log_ct_progress(&hcp, hai, CT_RUNNING, total, he->length);
1292
1293         return rc;
1294 }
1295
1296 /** Get the fid of object to be used for copying data.
1297  * @return error code if the action is not a copy operation.
1298  */
1299 int llapi_hsm_action_get_dfid(const struct hsm_copyaction_private *hcp,
1300                               struct lu_fid *fid)
1301 {
1302         const struct hsm_action_item    *hai = &hcp->copy.hc_hai;
1303
1304         if (hcp->magic != CP_PRIV_MAGIC)
1305                 return -EINVAL;
1306
1307         if (hai->hai_action != HSMA_RESTORE && hai->hai_action != HSMA_ARCHIVE)
1308                 return -EINVAL;
1309
1310         *fid = hai->hai_dfid;
1311
1312         return 0;
1313 }
1314
1315 /**
1316  * Get a file descriptor to be used for copying data. It's up to the
1317  * caller to close the FDs obtained from this function.
1318  *
1319  * @retval a file descriptor on success.
1320  * @retval a negative error code on failure.
1321  */
1322 int llapi_hsm_action_get_fd(const struct hsm_copyaction_private *hcp)
1323 {
1324         const struct hsm_action_item    *hai = &hcp->copy.hc_hai;
1325         int fd;
1326
1327         if (hcp->magic != CP_PRIV_MAGIC)
1328                 return -EINVAL;
1329
1330         if (hai->hai_action == HSMA_ARCHIVE) {
1331                 fd = dup(hcp->source_fd);
1332                 return fd < 0 ? -errno : fd;
1333         } else if (hai->hai_action == HSMA_RESTORE) {
1334                 fd = dup(hcp->data_fd);
1335                 return fd < 0 ? -errno : fd;
1336         } else {
1337                 return -EINVAL;
1338         }
1339 }
1340
1341 /**
1342  * Import an existing hsm-archived file into Lustre.
1343  *
1344  * Caller must access file by (returned) newfid value from now on.
1345  *
1346  * \param dst      path to Lustre destination (e.g. /mnt/lustre/my/file).
1347  * \param archive  archive number.
1348  * \param st       struct stat buffer containing file ownership, perm, etc.
1349  * \param stripe_* Striping options.  Currently ignored, since the restore
1350  *                 operation will set the striping.  In V2, this striping might
1351  *                 be used.
1352  * \param newfid[out] Filled with new Lustre fid.
1353  */
1354 int llapi_hsm_import(const char *dst, int archive, const struct stat *st,
1355                      unsigned long long stripe_size, int stripe_offset,
1356                      int stripe_count, int stripe_pattern, char *pool_name,
1357                      struct lu_fid *newfid)
1358 {
1359         struct hsm_user_import   hui;
1360         int                      fd;
1361         int                      rc = 0;
1362
1363         if (stripe_pattern == 0)
1364                 stripe_pattern = LOV_PATTERN_RAID0;
1365
1366         /* Create a non-striped file */
1367         fd = llapi_file_open_pool(dst, O_CREAT | O_WRONLY, st->st_mode,
1368                                   stripe_size, stripe_offset, stripe_count,
1369                                   stripe_pattern | LOV_PATTERN_F_RELEASED,
1370                                   pool_name);
1371         if (fd < 0) {
1372                 llapi_error(LLAPI_MSG_ERROR, fd,
1373                             "cannot create '%s' for import", dst);
1374                 return fd;
1375         }
1376
1377         /* Get the new fid in Lustre. Caller needs to use this fid
1378            from now on. */
1379         rc = llapi_fd2fid(fd, newfid);
1380         if (rc != 0) {
1381                 llapi_error(LLAPI_MSG_ERROR, rc,
1382                             "cannot get fid of '%s' for import", dst);
1383                 goto out_unlink;
1384         }
1385
1386         hui.hui_uid = st->st_uid;
1387         hui.hui_gid = st->st_gid;
1388         hui.hui_mode = st->st_mode;
1389         hui.hui_size = st->st_size;
1390         hui.hui_archive_id = archive;
1391         hui.hui_atime = st->st_atime;
1392         hui.hui_atime_ns = st->st_atim.tv_nsec;
1393         hui.hui_mtime = st->st_mtime;
1394         hui.hui_mtime_ns = st->st_mtim.tv_nsec;
1395         rc = ioctl(fd, LL_IOC_HSM_IMPORT, &hui);
1396         if (rc != 0) {
1397                 rc = -errno;
1398                 llapi_error(LLAPI_MSG_ERROR, rc, "cannot import '%s'", dst);
1399                 goto out_unlink;
1400         }
1401
1402 out_unlink:
1403         if (fd >= 0)
1404                 close(fd);
1405         if (rc)
1406                 unlink(dst);
1407         return rc;
1408 }
1409
1410 /**
1411  * Return the current HSM states and HSM requests related to file pointed by \a
1412  * path.
1413  *
1414  * \param hus  Should be allocated by caller. Will be filled with current file
1415  *             states.
1416  *
1417  * \retval 0 on success.
1418  * \retval -errno on error.
1419  */
1420 int llapi_hsm_state_get_fd(int fd, struct hsm_user_state *hus)
1421 {
1422         int rc;
1423
1424         rc = ioctl(fd, LL_IOC_HSM_STATE_GET, hus);
1425         /* If error, save errno value */
1426         rc = rc ? -errno : 0;
1427
1428         return rc;
1429 }
1430
1431 /**
1432  * Return the current HSM states and HSM requests related to file pointed by \a
1433  * path.
1434  *
1435  * see llapi_hsm_state_get_fd() for args use and return
1436  */
1437 int llapi_hsm_state_get(const char *path, struct hsm_user_state *hus)
1438 {
1439         int fd;
1440         int rc;
1441
1442         fd = open(path, O_RDONLY | O_NONBLOCK);
1443         if (fd < 0)
1444                 return -errno;
1445
1446         rc = llapi_hsm_state_get_fd(fd, hus);
1447
1448         close(fd);
1449         return rc;
1450 }
1451
1452 /**
1453  * Set HSM states of file pointed by \a fd
1454  *
1455  * Using the provided bitmasks, the current HSM states for this file will be
1456  * changed. \a archive_id could be used to change the archive number also. Set
1457  * it to 0 if you do not want to change it.
1458  *
1459  * \param setmask      Bitmask for flag to be set.
1460  * \param clearmask    Bitmask for flag to be cleared.
1461  * \param archive_id  Archive number identifier to use. 0 means no change.
1462  *
1463  * \retval 0 on success.
1464  * \retval -errno on error.
1465  */
1466 int llapi_hsm_state_set_fd(int fd, __u64 setmask, __u64 clearmask,
1467                            __u32 archive_id)
1468 {
1469         struct hsm_state_set     hss;
1470         int                      rc;
1471
1472         hss.hss_valid = HSS_SETMASK|HSS_CLEARMASK;
1473         hss.hss_setmask = setmask;
1474         hss.hss_clearmask = clearmask;
1475         /* Change archive_id if provided. We can only change
1476          * to set something different than 0. */
1477         if (archive_id > 0) {
1478                 hss.hss_valid |= HSS_ARCHIVE_ID;
1479                 hss.hss_archive_id = archive_id;
1480         }
1481         rc = ioctl(fd, LL_IOC_HSM_STATE_SET, &hss);
1482         /* If error, save errno value */
1483         rc = rc ? -errno : 0;
1484
1485         return rc;
1486 }
1487
1488 /**
1489  * Set HSM states of file pointed by \a path.
1490  *
1491  * see llapi_hsm_state_set_fd() for args use and return
1492  */
1493 int llapi_hsm_state_set(const char *path, __u64 setmask, __u64 clearmask,
1494                         __u32 archive_id)
1495 {
1496         int fd;
1497         int rc;
1498
1499         fd = open(path, O_WRONLY | O_LOV_DELAY_CREATE | O_NONBLOCK);
1500         if (fd < 0)
1501                 return -errno;
1502
1503         rc = llapi_hsm_state_set_fd(fd, setmask, clearmask, archive_id);
1504
1505         close(fd);
1506         return rc;
1507 }
1508
1509 /**
1510  * Return the current HSM request related to file pointed by \a path.
1511  *
1512  * \param hca  Should be allocated by caller. Will be filled with current file
1513  *             actions.
1514  *
1515  * \retval 0 on success.
1516  * \retval -errno on error.
1517  */
1518 int llapi_hsm_current_action(const char *path, struct hsm_current_action *hca)
1519 {
1520         int fd;
1521         int rc;
1522
1523         fd = open(path, O_RDONLY | O_NONBLOCK);
1524         if (fd < 0)
1525                 return -errno;
1526
1527         rc = ioctl(fd, LL_IOC_HSM_ACTION, hca);
1528         /* If error, save errno value */
1529         rc = rc ? -errno : 0;
1530
1531         close(fd);
1532         return rc;
1533 }
1534
1535 /**
1536  * Allocate a hsm_user_request with the specified carateristics.
1537  * This structure should be freed with free().
1538  *
1539  * \return an allocated structure on success, NULL otherwise.
1540  */
1541 struct hsm_user_request *llapi_hsm_user_request_alloc(int itemcount,
1542                                                       int data_len)
1543 {
1544         int len = 0;
1545
1546         len += sizeof(struct hsm_user_request);
1547         len += sizeof(struct hsm_user_item) * itemcount;
1548         len += data_len;
1549
1550         return (struct hsm_user_request *)malloc(len);
1551 }
1552
1553 /**
1554  * Send a HSM request to Lustre, described in \param request.
1555  *
1556  * \param path    Fullpath to the file to operate on.
1557  * \param request The request, allocated with llapi_hsm_user_request_alloc().
1558  *
1559  * \return 0 on success, an error code otherwise.
1560  */
1561 int llapi_hsm_request(const char *path, const struct hsm_user_request *request)
1562 {
1563         int rc;
1564         int fd;
1565
1566         rc = get_root_path(WANT_FD, NULL, &fd, (char *)path, -1);
1567         if (rc)
1568                 return rc;
1569
1570         rc = ioctl(fd, LL_IOC_HSM_REQUEST, request);
1571         /* If error, save errno value */
1572         rc = rc ? -errno : 0;
1573
1574         close(fd);
1575         return rc;
1576 }
1577